# all files / src/prePass/ ShadowMap.js

70.6% Statements 293/415
57.25% Branches 79/138
74.07% Functions 20/27
70.77% Lines 293/414

    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

    1×

    1×

    1×

    1×
    4×

    4×

    4×

    4×
    4×
    4×
    4×

    4×

    4×

    4×
    4×
    4×

    12×
    12×
    12×

    12×

    12×

    12×
    12×
    12×
    12×

    4×
    4×
    32×
    12×

    4×
    4×
    4×
    4×

    4×
    12×

    4×
    4×

    4×

    4×
    4×

    4×
    4×

    4×
    4×

    4×

    4×

    4×
    4×
    4×

    4×

    4×
    4×
    4×
    4×
    4×
    4×

    4×
    4×
    4×

    2×

    2×

    2×

    2×

    2×

    2×
    2×

    4×

    4×
    12×
    12×
    12×
    36×
    36×
    36×
    36×
    12×

    24×

    4×
    12×
    12×
    12×

    12×

    4×

    2×

    4×
    2×
    2×
    2×
    2×
    2×

    4×

    4×
    2×

    1×
    1×
    1×
    1×
    1×
    1×
    1×

    1×

    2×
    2×

    12×

    6×

    2×
    2×
    2×

    2×
    2×

    2×

    2×
    2×
    2×
    2×
    2×

    2×
    2×

    2×
    2×
    2×
    4×
    4×
    4×
    4×
    4×

    2×
    2×

    2×

    2×
    2×
    2×
    2×

    2×

    2×
    2×
    2×
    2×

    2×
    2×
    2×
    2×
    2×
    2×
    2×
    2×
    2×
    2×
    2×

    2×

    2×

    2×
    2×

    2×

    2×
    2×

    2×

    2×

    2×

    2×

    2×
    2×
    2×

    2×
    2×

    12×

    2×

    2×
    2×
    2×
    2×
    2×
    2×
    2×
    2×
    2×

    2×
    2×
    16×
    6×
    6×

    6×
    6×

    6×
    6×
    36×

    6×
    48×
    48×
    48×
    48×
    48×
    48×
    48×
    48×
    48×
    48×

    6×
    36×
    6×

    2×
    12×
    12×

    12×
    12×
    12×

    12×

    2×

    4×
    4×
    4×
    4×
    4×

    4×

    4×
    2×

    4×
    2×

    4×

    4×

    4×
    2×
    2×

    4×

    4×
    4×
    4×
    4×
    4×
    4×
    2×

    2×

    4×
    4×
    4×

    4×
    4×
    4×

    4×

    4×

    12×
    2×

    12×

    12×
    12×
    12×
    12×

    2×
    2×

    2×
    2×

    2×
    2×

    2×
    2×

    2×
    2×

    2×
    2×

    12×
    12×

    12×

    1×
    1×
    1×

    1×
    2×
    2×

    2×

    2×
    2×

    2×

    2×
    2×
    2×

    2×
    2×

    2×

    2×
    2×

    2×

    2×
    2×

    2×
    2×

    2×
    2×
    2×
    2×
    2×

    2×

    1×

    1×

     import Base from '../core/Base';
    import glenum from '../core/glenum';
    import Vector3 from '../math/Vector3';
    import BoundingBox from '../math/BoundingBox';
    import Frustum from '../math/Frustum';
    import Matrix4 from '../math/Matrix4';
    import Renderer from '../Renderer';
    import Shader from '../Shader';
    import Material from '../Material';
    import FrameBuffer from '../FrameBuffer';
    import Texture from '../Texture';
    import Texture2D from '../Texture2D';
    import TextureCube from '../TextureCube';
    import PerspectiveCamera from '../camera/Perspective';
    import OrthoCamera from '../camera/Orthographic';

    import Pass from '../compositor/Pass';
    import TexturePool from '../compositor/TexturePool';

    import glMatrix from '../dep/glmatrix';
    var mat4 = glMatrix.mat4;

    var targets = ['px', 'nx', 'py', 'ny', 'pz', 'nz'];

    import shadowmapEssl from '../shader/source/shadowmap.glsl.js';
    Shader['import'](shadowmapEssl);

    /**
     * Pass rendering shadow map.
     *
     * @constructor clay.prePass.ShadowMap
     * @extends clay.core.Base
     * @example
     *     var shadowMapPass = new clay.prePass.ShadowMap({
     *         softShadow: clay.prePass.ShadowMap.VSM
     *     });
     *     ...
     *     animation.on('frame', function (frameTime) {
     *         shadowMapPass.render(renderer, scene, camera);
     *         renderer.render(scene, camera);
     *     });
     */
    var ShadowMapPass = Base.extend(function () {
        return /** @lends clay.prePass.ShadowMap# */ {
            /**
             * Soft shadow technique.
             * Can be {@link clay.prePass.ShadowMap.PCF} or {@link clay.prePass.ShadowMap.VSM}
             * @type {number}
             */
            softShadow: ShadowMapPass.PCF,

            /**
             * Soft shadow blur size
             * @type {number}
             */
            shadowBlur: 1.0,

            lightFrustumBias: 'auto',

            kernelPCF: new Float32Array([
                1, 0,
                1, 1,
                -1, 1,
                0, 1,
                -1, 0,
                -1, -1,
                1, -1,
                0, -1
            ]),

            precision: 'highp',

            _lastRenderNotCastShadow: false,

            _frameBuffer: new FrameBuffer(),

            _textures: {},
            _shadowMapNumber: {
                'POINT_LIGHT': 0,
                'DIRECTIONAL_LIGHT': 0,
                'SPOT_LIGHT': 0
            },

            _depthMaterials: {},
            _distanceMaterials: {},

            _receivers: [],
            _lightsCastShadow: [],

            _lightCameras: {},
            _lightMaterials: {},

            _texturePool: new TexturePool()
        };
    }, function () {
        // Gaussian filter pass for VSM
        this._gaussianPassH = new Pass({
            fragment: Shader.source('clay.compositor.gaussian_blur')
        });
        this._gaussianPassV = new Pass({
            fragment: Shader.source('clay.compositor.gaussian_blur')
        });
        this._gaussianPassH.setUniform('blurSize', this.shadowBlur);
        this._gaussianPassH.setUniform('blurDir', 0.0);
        this._gaussianPassV.setUniform('blurSize', this.shadowBlur);
        this._gaussianPassV.setUniform('blurDir', 1.0);

        this._outputDepthPass = new Pass({
            fragment: Shader.source('clay.sm.debug_depth')
        });
    }, {
        /**
         * Render scene to shadow textures
         * @param  {clay.Renderer} renderer
         * @param  {clay.Scene} scene
         * @param  {clay.Camera} sceneCamera
         * @param  {boolean} [notUpdateScene=false]
         * @memberOf clay.prePass.ShadowMap.prototype
         */
        render: function (renderer, scene, sceneCamera, notUpdateScene) {
            Iif (!sceneCamera) {
                sceneCamera = scene.getMainCamera();
            }
            this.trigger('beforerender', this, renderer, scene, sceneCamera);
            this._renderShadowPass(renderer, scene, sceneCamera, notUpdateScene);
            this.trigger('afterrender', this, renderer, scene, sceneCamera);
        },

        /**
         * Debug rendering of shadow textures
         * @param  {clay.Renderer} renderer
         * @param  {number} size
         * @memberOf clay.prePass.ShadowMap.prototype
         */
        renderDebug: function (renderer, size) {
            renderer.saveClear();
            var viewport = renderer.viewport;
            var x = 0, y = 0;
            var width = size || viewport.width / 4;
            var height = width;
            if (this.softShadow === ShadowMapPass.VSM) {
                this._outputDepthPass.material.define('fragment', 'USE_VSM');
            }
            else {
                this._outputDepthPass.material.undefine('fragment', 'USE_VSM');
            }
            for (var name in this._textures) {
                var texture = this._textures[name];
                renderer.setViewport(x, y, width * texture.width / texture.height, height);
                this._outputDepthPass.setUniform('depthMap', texture);
                this._outputDepthPass.render(renderer);
                x += width * texture.width / texture.height;
            }
            renderer.setViewport(viewport);
            renderer.restoreClear();
        },

        _updateReceivers: function (renderer, mesh) {
            Eif (mesh.receiveShadow) {
                this._receivers.push(mesh);
                mesh.material.set('shadowEnabled', 1);

                mesh.material.set('pcfKernel', this.kernelPCF);
            }
            else {
                mesh.material.set('shadowEnabled', 0);
            }

            Iif (this.softShadow === ShadowMapPass.VSM) {
                mesh.material.define('fragment', 'USE_VSM');
                mesh.material.undefine('fragment', 'PCF_KERNEL_SIZE');
            }
            else {
                mesh.material.undefine('fragment', 'USE_VSM');
                var kernelPCF = this.kernelPCF;
                Eif (kernelPCF && kernelPCF.length) {
                    mesh.material.define('fragment', 'PCF_KERNEL_SIZE', kernelPCF.length / 2);
                }
                else {
                    mesh.material.undefine('fragment', 'PCF_KERNEL_SIZE');
                }
            }
        },

        _update: function (renderer, scene) {
            var self = this;
            scene.traverse(function (renderable) {
                if (renderable.isRenderable()) {
                    self._updateReceivers(renderer, renderable);
                }
            });

            for (var i = 0; i < scene.lights.length; i++) {
                var light = scene.lights[i];
                Eif (light.castShadow && !light.invisible) {
                    this._lightsCastShadow.push(light);
                }
            }
        },

        _renderShadowPass: function (renderer, scene, sceneCamera, notUpdateScene) {
            // reset
            for (var name in this._shadowMapNumber) {
                this._shadowMapNumber[name] = 0;
            }
            this._lightsCastShadow.length = 0;
            this._receivers.length = 0;

            var _gl = renderer.gl;

            Eif (!notUpdateScene) {
                scene.update();
            }
            Eif (sceneCamera) {
                sceneCamera.update();
            }

            scene.updateLights();
            this._update(renderer, scene);

            // Needs to update the receivers again if shadows come from 1 to 0.
            Iif (!this._lightsCastShadow.length && this._lastRenderNotCastShadow) {
                return;
            }

            this._lastRenderNotCastShadow = this._lightsCastShadow === 0;

            _gl.enable(_gl.DEPTH_TEST);
            _gl.depthMask(true);
            _gl.disable(_gl.BLEND);

            // Clear with high-z, so the part not rendered will not been shadowed
            // TODO
            // TODO restore
            _gl.clearColor(1.0, 1.0, 1.0, 1.0);

            // Shadow uniforms
            var spotLightShadowMaps = [];
            var spotLightMatrices = [];
            var directionalLightShadowMaps = [];
            var directionalLightMatrices = [];
            var shadowCascadeClips = [];
            var pointLightShadowMaps = [];

            var dirLightHasCascade;
            // Create textures for shadow map
            for (var i = 0; i < this._lightsCastShadow.length; i++) {
                var light = this._lightsCastShadow[i];
                if (light.type === 'DIRECTIONAL_LIGHT') {

                    Iif (dirLightHasCascade) {
                        console.warn('Only one direectional light supported with shadow cascade');
                        continue;
                    }
                    Iif (light.shadowCascade > 4) {
                        console.warn('Support at most 4 cascade');
                        continue;
                    }
                    Iif (light.shadowCascade > 1) {
                        dirLightHasCascade = light;
                    }

                    this.renderDirectionalLightShadow(
                        renderer,
                        scene,
                        sceneCamera,
                        light,
                        shadowCascadeClips,
                        directionalLightMatrices,
                        directionalLightShadowMaps
                    );
                }
                else Iif (light.type === 'SPOT_LIGHT') {
                    this.renderSpotLightShadow(
                        renderer,
                        scene,
                        light,
                        spotLightMatrices,
                        spotLightShadowMaps
                    );
                }
                else Eif (light.type === 'POINT_LIGHT') {
                    this.renderPointLightShadow(
                        renderer,
                        scene,
                        light,
                        pointLightShadowMaps
                    );
                }

                this._shadowMapNumber[light.type]++;
            }

            for (var lightType in this._shadowMapNumber) {
                var number = this._shadowMapNumber[lightType];
                var key = lightType + '_SHADOWMAP_COUNT';
                for (var i = 0; i < this._receivers.length; i++) {
                    var mesh = this._receivers[i];
                    var material = mesh.material;
                    Eif (material.fragmentDefines[key] !== number) {
                        if (number > 0) {
                            material.define('fragment', key, number);
                        }
                        else Iif (material.isDefined('fragment', key)) {
                            material.undefine('fragment', key);
                        }
                    }
                }
            }
            for (var i = 0; i < this._receivers.length; i++) {
                var mesh = this._receivers[i];
                var material = mesh.material;
                Iif (dirLightHasCascade) {
                    material.define('fragment', 'SHADOW_CASCADE', dirLightHasCascade.shadowCascade);
                }
                else {
                    material.undefine('fragment', 'SHADOW_CASCADE');
                }
            }

            var shadowUniforms = scene.shadowUniforms;

            function getSize(texture) {
                return texture.height;
            }
            if (directionalLightShadowMaps.length > 0) {
                var directionalLightShadowMapSizes = directionalLightShadowMaps.map(getSize);
                shadowUniforms.directionalLightShadowMaps = { value: directionalLightShadowMaps, type: 'tv' };
                shadowUniforms.directionalLightMatrices = { value: directionalLightMatrices, type: 'm4v' };
                shadowUniforms.directionalLightShadowMapSizes = { value: directionalLightShadowMapSizes, type: '1fv' };
                Iif (dirLightHasCascade) {
                    var shadowCascadeClipsNear = shadowCascadeClips.slice();
                    var shadowCascadeClipsFar = shadowCascadeClips.slice();
                    shadowCascadeClipsNear.pop();
                    shadowCascadeClipsFar.shift();

                    // Iterate from far to near
                    shadowCascadeClipsNear.reverse();
                    shadowCascadeClipsFar.reverse();
                    // directionalLightShadowMaps.reverse();
                    directionalLightMatrices.reverse();
                    shadowUniforms.shadowCascadeClipsNear = { value: shadowCascadeClipsNear, type: '1fv' };
                    shadowUniforms.shadowCascadeClipsFar = { value: shadowCascadeClipsFar, type: '1fv' };
                }
            }

            Iif (spotLightShadowMaps.length > 0) {
                var spotLightShadowMapSizes = spotLightShadowMaps.map(getSize);
                var shadowUniforms = scene.shadowUniforms;
                shadowUniforms.spotLightShadowMaps = { value: spotLightShadowMaps, type: 'tv' };
                shadowUniforms.spotLightMatrices = { value: spotLightMatrices, type: 'm4v' };
                shadowUniforms.spotLightShadowMapSizes = { value: spotLightShadowMapSizes, type: '1fv' };
            }

            if (pointLightShadowMaps.length > 0) {
                shadowUniforms.pointLightShadowMaps = { value: pointLightShadowMaps, type: 'tv' };
            }
        },

        renderDirectionalLightShadow: (function () {

            var splitFrustum = new Frustum();
            var splitProjMatrix = new Matrix4();
            var cropBBox = new BoundingBox();
            var cropMatrix = new Matrix4();
            var lightViewMatrix = new Matrix4();
            var lightViewProjMatrix = new Matrix4();
            var lightProjMatrix = new Matrix4();

            return function (renderer, scene, sceneCamera, light, shadowCascadeClips, directionalLightMatrices, directionalLightShadowMaps) {

                var defaultShadowMaterial = this._getDepthMaterial(light);
                var passConfig = {
                    getMaterial: function (renderable) {
                        return renderable.shadowDepthMaterial || defaultShadowMaterial;
                    },
                    ifRender: function (renderable) {
                        return renderable.castShadow;
                    },
                    sortCompare: Renderer.opaqueSortCompare
                };

                // First frame
                Eif (!scene.viewBoundingBoxLastFrame.isFinite()) {
                    var boundingBox = scene.getBoundingBox();
                    scene.viewBoundingBoxLastFrame
                        .copy(boundingBox).applyTransform(sceneCamera.viewMatrix);
                }
                // Considering moving speed since the bounding box is from last frame
                // TODO: add a bias
                var clippedFar = Math.min(-scene.viewBoundingBoxLastFrame.min.z, sceneCamera.far);
                var clippedNear = Math.max(-scene.viewBoundingBoxLastFrame.max.z, sceneCamera.near);

                var lightCamera = this._getDirectionalLightCamera(light, scene, sceneCamera);

                var lvpMat4Arr = lightViewProjMatrix.array;
                lightProjMatrix.copy(lightCamera.projectionMatrix);
                mat4.invert(lightViewMatrix.array, lightCamera.worldTransform.array);
                mat4.multiply(lightViewMatrix.array, lightViewMatrix.array, sceneCamera.worldTransform.array);
                mat4.multiply(lvpMat4Arr, lightProjMatrix.array, lightViewMatrix.array);

                var clipPlanes = [];
                var isPerspective = sceneCamera instanceof PerspectiveCamera;

                var scaleZ = (sceneCamera.near + sceneCamera.far) / (sceneCamera.near - sceneCamera.far);
                var offsetZ = 2 * sceneCamera.near * sceneCamera.far / (sceneCamera.near - sceneCamera.far);
                for (var i = 0; i <= light.shadowCascade; i++) {
                    var clog = clippedNear * Math.pow(clippedFar / clippedNear, i / light.shadowCascade);
                    var cuni = clippedNear + (clippedFar - clippedNear) * i / light.shadowCascade;
                    var c = clog * light.cascadeSplitLogFactor + cuni * (1 - light.cascadeSplitLogFactor);
                    clipPlanes.push(c);
                    shadowCascadeClips.push(-(-c * scaleZ + offsetZ) / -c);
                }
                var texture = this._getTexture(light, light.shadowCascade);
                directionalLightShadowMaps.push(texture);

                var viewport = renderer.viewport;

                var _gl = renderer.gl;
                this._frameBuffer.attach(texture);
                this._frameBuffer.bind(renderer);
                _gl.clear(_gl.COLOR_BUFFER_BIT | _gl.DEPTH_BUFFER_BIT);

                for (var i = 0; i < light.shadowCascade; i++) {
                    // Get the splitted frustum
                    var nearPlane = clipPlanes[i];
                    var farPlane = clipPlanes[i + 1];
                    Eif (isPerspective) {
                        mat4.perspective(splitProjMatrix.array, sceneCamera.fov / 180 * Math.PI, sceneCamera.aspect, nearPlane, farPlane);
                    }
                    else {
                        mat4.ortho(
                            splitProjMatrix.array,
                            sceneCamera.left, sceneCamera.right, sceneCamera.bottom, sceneCamera.top,
                            nearPlane, farPlane
                        );
                    }
                    splitFrustum.setFromProjection(splitProjMatrix);
                    splitFrustum.getTransformedBoundingBox(cropBBox, lightViewMatrix);
                    cropBBox.applyProjection(lightProjMatrix);
                    var _min = cropBBox.min.array;
                    var _max = cropBBox.max.array;
                    _min[0] = Math.max(_min[0], -1);
                    _min[1] = Math.max(_min[1], -1);
                    _max[0] = Math.min(_max[0], 1);
                    _max[1] = Math.min(_max[1], 1);
                    cropMatrix.ortho(_min[0], _max[0], _min[1], _max[1], 1, -1);
                    lightCamera.projectionMatrix.multiplyLeft(cropMatrix);

                    var shadowSize = light.shadowResolution || 512;

                    // Reversed, left to right => far to near
                    renderer.setViewport((light.shadowCascade - i - 1) * shadowSize, 0, shadowSize, shadowSize, 1);

                    var renderList = scene.updateRenderList(lightCamera);
                    renderer.renderPass(renderList.opaque, lightCamera, passConfig);

                    // Filter for VSM
                    Iif (this.softShadow === ShadowMapPass.VSM) {
                        this._gaussianFilter(renderer, texture, texture.width);
                    }

                    var matrix = new Matrix4();
                    matrix.copy(lightCamera.viewMatrix)
                        .multiplyLeft(lightCamera.projectionMatrix);

                    directionalLightMatrices.push(matrix.array);

                    lightCamera.projectionMatrix.copy(lightProjMatrix);
                }

                this._frameBuffer.unbind(renderer);

                renderer.setViewport(viewport);
            };
        })(),

        renderSpotLightShadow: function (renderer, scene, light, spotLightMatrices, spotLightShadowMaps) {

            var texture = this._getTexture(light);
            var lightCamera = this._getSpotLightCamera(light);
            var _gl = renderer.gl;

            this._frameBuffer.attach(texture);
            this._frameBuffer.bind(renderer);

            _gl.clear(_gl.COLOR_BUFFER_BIT | _gl.DEPTH_BUFFER_BIT);

            var defaultShadowMaterial = this._getDepthMaterial(light);
            var passConfig = {
                getMaterial: function (renderable) {
                    return renderable.shadowDepthMaterial || defaultShadowMaterial;
                },
                ifRender: function (renderable) {
                    return renderable.castShadow;
                },
                sortCompare: Renderer.opaqueSortCompare
            };

            var renderList = scene.updateRenderList(lightCamera);
            renderer.renderPass(renderList.opaque, lightCamera, passConfig);

            this._frameBuffer.unbind(renderer);

            // Filter for VSM
            if (this.softShadow === ShadowMapPass.VSM) {
                this._gaussianFilter(renderer, texture, texture.width);
            }

            var matrix = new Matrix4();
            matrix.copy(lightCamera.worldTransform)
                .invert()
                .multiplyLeft(lightCamera.projectionMatrix);

            spotLightShadowMaps.push(texture);
            spotLightMatrices.push(matrix.array);
        },

        renderPointLightShadow: function (renderer, scene, light, pointLightShadowMaps) {
            var texture = this._getTexture(light);
            var _gl = renderer.gl;
            pointLightShadowMaps.push(texture);

            var defaultShadowMaterial = this._getDepthMaterial(light);
            var passConfig = {
                getMaterial: function (renderable) {
                    return renderable.shadowDepthMaterial || defaultShadowMaterial;
                },
                sortCompare: Renderer.opaqueSortCompare
            };

            var renderListEachSide = {
                px: [], py: [], pz: [], nx: [], ny: [], nz: []
            };
            var bbox = new BoundingBox();
            var lightWorldPosition = light.getWorldPosition().array;
            var lightBBox = new BoundingBox();
            var range = light.range;
            lightBBox.min.setArray(lightWorldPosition);
            lightBBox.max.setArray(lightWorldPosition);
            var extent = new Vector3(range, range, range);
            lightBBox.max.add(extent);
            lightBBox.min.sub(extent);

            var targetsNeedRender = { px: false, py: false, pz: false, nx: false, ny: false, nz: false };
            scene.traverse(function (renderable) {
                if (renderable.isRenderable() && renderable.castShadow) {
                    var geometry = renderable.geometry;
                    Iif (!geometry.boundingBox) {
                        for (var i = 0; i < targets.length; i++) {
                            renderListEachSide[targets[i]].push(renderable);
                        }
                        return;
                    }
                    bbox.transformFrom(geometry.boundingBox, renderable.worldTransform);
                    Iif (!bbox.intersectBoundingBox(lightBBox)) {
                        return;
                    }

                    bbox.updateVertices();
                    for (var i = 0; i < targets.length; i++) {
                        targetsNeedRender[targets[i]] = false;
                    }
                    for (var i = 0; i < 8; i++) {
                        var vtx = bbox.vertices[i];
                        var x = vtx[0] - lightWorldPosition[0];
                        var y = vtx[1] - lightWorldPosition[1];
                        var z = vtx[2] - lightWorldPosition[2];
                        var absx = Math.abs(x);
                        var absy = Math.abs(y);
                        var absz = Math.abs(z);
                        Eif (absx > absy) {
                            Eif (absx > absz) {
                                targetsNeedRender[x > 0 ? 'px' : 'nx'] = true;
                            }
                            else {
                                targetsNeedRender[z > 0 ? 'pz' : 'nz'] = true;
                            }
                        }
                        else {
                            if (absy > absz) {
                                targetsNeedRender[y > 0 ? 'py' : 'ny'] = true;
                            }
                            else {
                                targetsNeedRender[z > 0 ? 'pz' : 'nz'] = true;
                            }
                        }
                    }
                    for (var i = 0; i < targets.length; i++) {
                        if (targetsNeedRender[targets[i]]) {
                            renderListEachSide[targets[i]].push(renderable);
                        }
                    }
                }
            });

            for (var i = 0; i < 6; i++) {
                var target = targets[i];
                var camera = this._getPointLightCamera(light, target);

                this._frameBuffer.attach(texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
                this._frameBuffer.bind(renderer);
                _gl.clear(_gl.COLOR_BUFFER_BIT | _gl.DEPTH_BUFFER_BIT);

                renderer.renderPass(renderListEachSide[target], camera, passConfig);
            }

            this._frameBuffer.unbind(renderer);
        },

        _getDepthMaterial: function (light) {
            var shadowMaterial = this._lightMaterials[light.__uid__];
            var isPointLight = light.type === 'POINT_LIGHT';
            Eif (!shadowMaterial) {
                var shaderPrefix = isPointLight ? 'clay.sm.distance.' : 'clay.sm.depth.';
                shadowMaterial = new Material({
                    precision: this.precision,
                    shader: new Shader(Shader.source(shaderPrefix + 'vertex'), Shader.source(shaderPrefix + 'fragment'))
                });

                this._lightMaterials[light.__uid__] = shadowMaterial;
            }
            if (light.shadowSlopeScale != null) {
                shadowMaterial.setUniform('slopeScale', light.shadowSlopeScale);
            }
            if (light.shadowBias != null) {
                shadowMaterial.setUniform('shadowBias', light.shadowBias);
            }
            Iif (this.softShadow === ShadowMapPass.VSM) {
                shadowMaterial.define('fragment', 'USE_VSM');
            }
            else {
                shadowMaterial.undefine('fragment', 'USE_VSM');
            }

            if (isPointLight) {
                shadowMaterial.set('lightPosition', light.getWorldPosition().array);
                shadowMaterial.set('range', light.range);
            }

            return shadowMaterial;
        },

        _gaussianFilter: function (renderer, texture, size) {
            var parameter = {
                width: size,
                height: size,
                type: Texture.FLOAT
            };
            var tmpTexture = this._texturePool.get(parameter);

            this._frameBuffer.attach(tmpTexture);
            this._frameBuffer.bind(renderer);
            this._gaussianPassH.setUniform('texture', texture);
            this._gaussianPassH.setUniform('textureWidth', size);
            this._gaussianPassH.render(renderer);

            this._frameBuffer.attach(texture);
            this._gaussianPassV.setUniform('texture', tmpTexture);
            this._gaussianPassV.setUniform('textureHeight', size);
            this._gaussianPassV.render(renderer);
            this._frameBuffer.unbind(renderer);

            this._texturePool.put(tmpTexture);
        },

        _getTexture: function (light, cascade) {
            var key = light.__uid__;
            var texture = this._textures[key];
            var resolution = light.shadowResolution || 512;
            cascade = cascade || 1;
            Eif (!texture) {
                if (light.type === 'POINT_LIGHT') {
                    texture = new TextureCube();
                }
                else {
                    texture = new Texture2D();
                }
                // At most 4 cascade
                // TODO share with height ?
                texture.width = resolution * cascade;
                texture.height = resolution;
                Iif (this.softShadow === ShadowMapPass.VSM) {
                    texture.type = Texture.FLOAT;
                    texture.anisotropic = 4;
                }
                else {
                    texture.minFilter = glenum.NEAREST;
                    texture.magFilter = glenum.NEAREST;
                    texture.useMipmap = false;
                }
                this._textures[key] = texture;
            }

            return texture;
        },

        _getPointLightCamera: function (light, target) {
            if (!this._lightCameras.point) {
                this._lightCameras.point = {
                    px: new PerspectiveCamera(),
                    nx: new PerspectiveCamera(),
                    py: new PerspectiveCamera(),
                    ny: new PerspectiveCamera(),
                    pz: new PerspectiveCamera(),
                    nz: new PerspectiveCamera()
                };
            }
            var camera = this._lightCameras.point[target];

            camera.far = light.range;
            camera.fov = 90;
            camera.position.set(0, 0, 0);
            switch (target) {
                case 'px':
                    camera.lookAt(Vector3.POSITIVE_X, Vector3.NEGATIVE_Y);
                    break;
                case 'nx':
                    camera.lookAt(Vector3.NEGATIVE_X, Vector3.NEGATIVE_Y);
                    break;
                case 'py':
                    camera.lookAt(Vector3.POSITIVE_Y, Vector3.POSITIVE_Z);
                    break;
                case 'ny':
                    camera.lookAt(Vector3.NEGATIVE_Y, Vector3.NEGATIVE_Z);
                    break;
                case 'pz':
                    camera.lookAt(Vector3.POSITIVE_Z, Vector3.NEGATIVE_Y);
                    break;
                case 'nz':
                    camera.lookAt(Vector3.NEGATIVE_Z, Vector3.NEGATIVE_Y);
                    break;
            }
            light.getWorldPosition(camera.position);
            camera.update();

            return camera;
        },

        _getDirectionalLightCamera: (function () {
            var lightViewMatrix = new Matrix4();
            var sceneViewBoundingBox = new BoundingBox();
            var lightViewBBox = new BoundingBox();
            // Camera of directional light will be adjusted
            // to contain the view frustum and scene bounding box as tightly as possible
            return function (light, scene, sceneCamera) {
                Eif (!this._lightCameras.directional) {
                    this._lightCameras.directional = new OrthoCamera();
                }
                var camera = this._lightCameras.directional;

                sceneViewBoundingBox.copy(scene.viewBoundingBoxLastFrame);
                sceneViewBoundingBox.intersection(sceneCamera.frustum.boundingBox);
                // Move to the center of frustum(in world space)
                camera.position
                    .copy(sceneViewBoundingBox.min)
                    .add(sceneViewBoundingBox.max)
                    .scale(0.5)
                    .transformMat4(sceneCamera.worldTransform);
                camera.rotation.copy(light.rotation);
                camera.scale.copy(light.scale);
                camera.updateWorldTransform();

                // Transform to light view space
                Matrix4.invert(lightViewMatrix, camera.worldTransform);
                Matrix4.multiply(lightViewMatrix, lightViewMatrix, sceneCamera.worldTransform);

                lightViewBBox.copy(sceneViewBoundingBox).applyTransform(lightViewMatrix);

                var min = lightViewBBox.min.array;
                var max = lightViewBBox.max.array;

                // Move camera to adjust the near to 0
                camera.position.set((min[0] + max[0]) / 2, (min[1] + max[1]) / 2, max[2])
                    .transformMat4(camera.worldTransform);
                camera.near = 0;
                camera.far = -min[2] + max[2];
                // Make sure receivers not in the frustum will stil receive the shadow.
                Eif (isNaN(this.lightFrustumBias)) {
                    camera.far *= 4;
                }
                else {
                    camera.far += this.lightFrustumBias;
                }
                camera.left = min[0];
                camera.right = max[0];
                camera.top = max[1];
                camera.bottom = min[1];
                camera.update(true);

                return camera;
            };
        })(),

        _getSpotLightCamera: function (light) {
            if (!this._lightCameras.spot) {
                this._lightCameras.spot = new PerspectiveCamera();
            }
            var camera = this._lightCameras.spot;
            // Update properties
            camera.fov = light.penumbraAngle * 2;
            camera.far = light.range;
            camera.worldTransform.copy(light.worldTransform);
            camera.updateProjectionMatrix();
            mat4.invert(camera.viewMatrix.array, camera.worldTransform.array);

            return camera;
        },

        /**
         * @param  {clay.Renderer|WebGLRenderingContext} [renderer]
         * @memberOf clay.prePass.ShadowMap.prototype
         */
        // PENDING Renderer or WebGLRenderingContext
        dispose: function (renderer) {
            var _gl = renderer.gl || renderer;

            if (this._frameBuffer) {
                this._frameBuffer.dispose(_gl);
            }

            for (var name in this._textures) {
                this._textures[name].dispose(_gl);
            }

            this._texturePool.clear(renderer.gl);

            this._depthMaterials = {};
            this._distanceMaterials = {};
            this._textures = {};
            this._lightCameras = {};
            this._shadowMapNumber = {
                'POINT_LIGHT': 0,
                'DIRECTIONAL_LIGHT': 0,
                'SPOT_LIGHT': 0
            };
            this._meshMaterials = {};

            for (var i = 0; i < this._receivers.length; i++) {
                var mesh = this._receivers[i];
                // Mesh may be disposed
                if (mesh.material) {
                    var material = mesh.material;
                    material.undefine('fragment', 'POINT_LIGHT_SHADOW_COUNT');
                    material.undefine('fragment', 'DIRECTIONAL_LIGHT_SHADOW_COUNT');
                    material.undefine('fragment', 'AMBIENT_LIGHT_SHADOW_COUNT');
                    material.set('shadowEnabled', 0);
                }
            }

            this._receivers = [];
            this._lightsCastShadow = [];
        }
    });

    /**
     * @name clay.prePass.ShadowMap.VSM
     * @type {number}
     */
    ShadowMapPass.VSM = 1;

    /**
     * @name clay.prePass.ShadowMap.PCF
     * @type {number}
     */
    ShadowMapPass.PCF = 2;

    export default ShadowMapPass;