/
material.js
1439 lines (1387 loc) · 56.5 KB
/
material.js
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
/*!
* New BSD License
*
* Copyright (c) 2011, Morten Nobel-Joergensen, Kickstart Games ( http://www.kickstartgames.com/ )
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var KICK = KICK || {};
KICK.namespace = function (ns_string) {
"use strict"; // force strict ECMAScript 5
var parts = ns_string.split("."),
parent = window,
i;
for (i = 0; i < parts.length; i += 1) {
// create property if it doesn't exist
if (typeof parent[parts[i]] === "undefined") {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
};
(function () {
"use strict"; // force strict ECMAScript 5
var material = KICK.namespace("KICK.material"),
math = KICK.namespace("KICK.math"),
mat3 = math.mat3,
mat4 = math.mat4,
vec4 = math.vec4,
core = KICK.namespace("KICK.core"),
applyConfig = core.Util.applyConfig,
c = KICK.core.Constants,
ASSERT = c._ASSERT,
fail = core.Util.fail,
uint32ToVec4 = KICK.core.Util.uint32ToVec4,
tempMat4 = mat4.create(),
tempMat3 = mat3.create(),
tmpVec4 = vec4.create(),
vec3Zero = math.vec3.create(),
isMaterialUniformName = function (name) {return name.charAt(0) !== "_"; },
/*
* If the uniform value is not in a valid format, the
* @param {Number} type
* @param {Object} uniformValue
* @param {KICK.core.Engine} engine
*/
convertUniformValue = function (type, uniformValue, engine) {
if (type === c.GL_SAMPLER_2D || type === c.GL_SAMPLER_CUBE) {
if (uniformValue && typeof uniformValue.ref === 'number') {
return engine.project.load(uniformValue.ref);
}
}
if (Array.isArray(uniformValue) || typeof uniformValue === 'number') {
var array = uniformValue;
if (typeof array === 'number') {
array = [array];
}
if (type === c.GL_INT || type === c.GL_INT_VEC2 || type === c.GL_INT_VEC3 || type === c.GL_INT_VEC4) {
return new Int32Array(array);
} else {
return new Float32Array(array);
}
}
return uniformValue;
};
/**
* @class UniformDescriptor
* @namespace KICK.material
* @constructor
* @param {String} name
* @param {Number} type the WebGL Uniform type
* @param {Number} size
* @param {WebGLUniformLocation} location
*/
material.UniformDescriptor = function (name, type, size, location) {
/**
* @property name
* @type String
*/
this.name = name;
/**
* the WebGL Uniform type
* @property type
* @type Number
*/
this.type = type;
/**
* @property size
* @type Number
*/
this.size = size;
/**
* @property location
* @type WebGLUniformLocation
*/
this.location = location;
Object.freeze(this);
};
/**
* GLSL Shader object<br>
* The shader basically encapsulates a GLSL shader programs, but makes sure that the correct
* WebGL settings are set when the shader is bound (such as if blending is enabled or not).<br>
* The Shader extend the default WebGL GLSL in the following way:
* <ul>
* <li>
* <code>#pragma include <filename></code> includes of the following KickJS file as a string:
* <ul>
* <li>light.glsl</li>
* <li>shadowmap.glsl</li>
* </ul>
* </li>
* <li>Auto binds the following uniform variables:
* <ul>
* <li><code>_mvProj</code> (mat4) Model view projection matrix</li>
* <li><code>_m</code> (mat4) Model matrix</li>
* <li><code>_mv</code> (mat4) Model view matrix</li>
* <li><code>_norm</code> (mat3) Normal matrix (the inverse transpose of the upper 3x3 model view matrix - needed when scaling is scaling is non-uniform)</li>
* <li><code>_time</code> (float) Run time of engine</li>
* <li><code>_ambient</code> (vec3) Ambient light</li>
* <li><code>_dLight.lDir</code> (vec3) Directional light direction</li>
* <li><code>_dLight.colInt</code> (vec3) Directional light color intensity</li>
* <li><code>_dLight.halfV</code> (vec3) Directional light half vector</li>
* </ul>
* </li>
* <li>Defines <code>SHADOW</code> (Boolean) and <code>LIGHTS</code> (Integer) based on the current configuration of the engine (cannot be modified runtime). </li>
* </ul>
* @class Shader
* @namespace KICK.material
* @constructor
* @param {KICK.core.Engine} engine
* @param {Object} config
* @extends KICK.core.ProjectAsset
*/
material.Shader = function (engine, config) {
var gl = engine.gl,
thisObj = this,
_shaderProgramId = -1,
_depthMask = true,
_faceCulling = core.Constants.GL_BACK,
_zTest = core.Constants.GL_LESS,
_blend = false,
_blendSFactor = core.Constants.GL_SRC_ALPHA,
_blendDFactor = core.Constants.GL_ONE_MINUS_SRC_ALPHA,
_polygonOffsetEnabled = false,
_polygonOffsetFactor = 2.5,
_polygonOffsetUnits = 10.0,
_renderOrder = 1000,
_dataURI = "memory://void",
_name = "",
blendKey,
_activeUniforms = [],
_engineUniforms = [],
_materialUniforms = [],
_lookupUniform = {},
glslConstants = material.GLSLConstants,
_vertexShaderSrc = glslConstants["__error_vs.glsl"],
_fragmentShaderSrc = glslConstants["__error_fs.glsl"],
_defaultUniforms,
_errorLog = KICK.core.Util.fail,
/**
* Updates the blend key that identifies blend+blendSFactor+blendDFactor<br>
* The key is used to fast determine if the blend settings needs to be updated
* @method getBlendKey
*/
updateBlendKey = function () {
blendKey = (_blendSFactor + _blendDFactor * 10000) * (_blend ? -1 : 1);
},
/**
* Invoke shader compilation
* @method compileShader
* @param {String} str
* @param {Boolean} isFragmentShader
* @private
*/
compileShader = function (str, isFragmentShader) {
var shader,
infoLog,
c = KICK.core.Constants;
str = material.Shader.getPrecompiledSource(engine, str);
if (isFragmentShader) {
shader = gl.createShader(c.GL_FRAGMENT_SHADER);
} else {
shader = gl.createShader(c.GL_VERTEX_SHADER);
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, c.GL_COMPILE_STATUS)) {
infoLog = gl.getShaderInfoLog(shader);
if (typeof _errorLog === "function") {
_errorLog(infoLog);
}
return null;
}
return shader;
},
updateCullFace = function () {
var currentFaceCulling = gl.faceCulling;
if (currentFaceCulling !== _faceCulling) {
if (_faceCulling === core.Constants.GL_NONE) {
gl.disable(c.GL_CULL_FACE);
} else {
if (!currentFaceCulling || currentFaceCulling === core.Constants.GL_NONE) {
gl.enable(c.GL_CULL_FACE);
}
gl.cullFace(_faceCulling);
}
gl.faceCulling = _faceCulling;
}
},
updateDepthProperties = function () {
if (gl.zTest !== _zTest) {
gl.depthFunc(_zTest);
gl.zTest = _zTest;
}
if (gl.depthMaskCache !== _depthMask) {
gl.depthMask(_depthMask);
gl.depthMaskCache = _depthMask;
}
},
updateBlending = function () {
if (gl.blendKey !== blendKey) {
gl.blendKey = blendKey;
if (_blend) {
gl.enable(KICK.core.Constants.GL_BLEND);
} else {
gl.disable(KICK.core.Constants.GL_BLEND);
}
gl.blendFunc(_blendSFactor, _blendDFactor);
}
},
updatePolygonOffset = function () {
if (gl.polygonOffsetEnabled !== _polygonOffsetEnabled) {
gl.polygonOffsetEnabled = _polygonOffsetEnabled;
if (_polygonOffsetEnabled) {
gl.enable(KICK.core.Constants.GL_POLYGON_OFFSET_FILL);
} else {
gl.disable(KICK.core.Constants.GL_POLYGON_OFFSET_FILL);
}
}
if (_polygonOffsetEnabled) {
gl.polygonOffset(_polygonOffsetFactor, _polygonOffsetUnits);
}
},
getDefaultUniform = function (type, size) {
switch (type) {
case c.GL_FLOAT:
return new Float32Array(size);
case c.GL_FLOAT_MAT2:
return new Float32Array(4 * size);
case c.GL_FLOAT_MAT3:
return new Float32Array(9 * size);
case c.GL_FLOAT_MAT4:
return new Float32Array(16 * size);
case c.GL_FLOAT_VEC2:
return new Float32Array(2 * size);
case c.GL_FLOAT_VEC3:
return new Float32Array(3 * size);
case c.GL_FLOAT_VEC4:
return new Float32Array(4 * size);
case c.GL_INT:
return new Int32Array(size);
case c.GL_INT_VEC2:
return new Int32Array(2 * size);
case c.GL_INT_VEC3:
return new Int32Array(3 * size);
case c.GL_INT_VEC4:
return new Int32Array(4 * size);
case c.GL_SAMPLER_CUBE:
if (size !== 1) {
fail("Texture arrays not currently supported");
}
return engine.project.load(engine.project.ENGINE_TEXTURE_CUBEMAP_WHITE);
case c.GL_SAMPLER_2D:
if (size !== 1) {
fail("Texture arrays not currently supported");
}
return engine.project.load(engine.project.ENGINE_TEXTURE_WHITE);
default:
fail("Unknown type");
}
},
updateActiveUniforms = function (numberOfActiveUniforms) {
var uniform,
uniformDescriptor,
uniformLocation,
oldDefaultUniforms = _defaultUniforms,
i,
defaultValue;
_activeUniforms = [];
_lookupUniform = {};
_defaultUniforms = {};
_materialUniforms.length = 0;
_engineUniforms.length = 0;
for (i = 0; i < numberOfActiveUniforms; i++) {
uniform = gl.getActiveUniform(_shaderProgramId, i);
uniformLocation = gl.getUniformLocation(_shaderProgramId, uniform.name);
uniformDescriptor = new material.UniformDescriptor(uniform.name, uniform.type, uniform.size, uniformLocation);
Object.freeze(uniformDescriptor);
_activeUniforms[i] = uniformDescriptor;
_lookupUniform[uniform.name] = uniformDescriptor;
if (isMaterialUniformName(uniform.name)) {
defaultValue = getDefaultUniform(uniform.type, uniform.size);
_defaultUniforms[uniform.name] = defaultValue;
_materialUniforms.push(uniformDescriptor);
} else {
_engineUniforms.push(uniformDescriptor);
}
}
// restore the old default uniforms (if any)
if (oldDefaultUniforms) {
thisObj.defaultUniforms = oldDefaultUniforms;
}
};
Object.defineProperties(this, {
/**
* Lookup of uniform based on name.
* for each name a KICK.material.UniformDescriptor object exist
* @property lookupUniform
* @type Object
*/
lookupUniform: {
get: function () { return _lookupUniform; }
},
/**
* Array of Object with size,type, name and index properties
* @property activeUniforms
* @type Array_KICK.material.UniformDescriptor
*/
activeUniforms: {
get: function () { return _activeUniforms; }
},
/**
* Array of Object with size,type, name and index properties
* @property engineUniforms
* @type Array Array_KICK.material.UniformDescriptor
*/
engineUniforms: {
get: function () { return _engineUniforms; }
},
/**
* Array of Object with size,type, name and index properties
* @property materialUniforms
* @type Array Array_KICK.material.UniformDescriptor
*/
materialUniforms: {
get: function () { return _materialUniforms; }
},
/**
* @property name
* @type String
*/
name: {
get: function () { return _name; },
set: function (newValue) { _name = newValue; }
},
/**
* When dataURI is specified the shader is expected to have its content from the dataURI.
* This means when serializing the object only dataURI and name will be saved
* @property dataURI
* @type String
*/
dataURI: {
get: function () { return _dataURI; },
set: function (newValue) {
if (_dataURI !== newValue) {
_dataURI = newValue;
if (_dataURI) { // load resource if not null
engine.resourceLoader.getShaderData(_dataURI, thisObj);
}
}
}
},
/**
* Get the gl context of the shader
* @property gl
* @type Object
*/
gl: {
value: gl
},
/**
* Get default configuration of shader uniforms
* @property defaultUniforms
* @type Object
*/
defaultUniforms: {
get: function () { return _defaultUniforms; },
set: function (value) {
var name, type;
for (name in _defaultUniforms ) {
if (_defaultUniforms.hasOwnProperty(name) && value.hasOwnProperty(name)) {
type = _lookupUniform[name].type;
_defaultUniforms[name] = convertUniformValue(type, value[name], engine);
}
}
}
},
/**
* @property vertexShaderSrc
* @type string
*/
vertexShaderSrc: {
get: function () { return _vertexShaderSrc; },
set: function (value) {
if (typeof value !== "string") {
KICK.core.Util.fail("Shader.vertexShaderSrc must be a string");
}
_vertexShaderSrc = value;
}
},
/**
* @property fragmentShaderSrc
* @type string
*/
fragmentShaderSrc: {
get: function () { return _fragmentShaderSrc; },
set: function (value) {
if (typeof value !== "string") {
KICK.core.Util.fail("Shader.fragmentShaderSrc must be a string");
}
_fragmentShaderSrc = value;
}
},
/**
* Render order. Default value 1000. The following ranges are predefined:<br>
* 0-999: Background. Mainly for skyboxes etc<br>
* 1000-1999 Opaque geometry (default)<br>
* 2000-2999 Transparent. This queue is sorted in a back to front order before rendering.<br>
* 3000-3999 Overlay
* @property renderOrder
* @type Number
*/
renderOrder: {
get: function () { return _renderOrder; },
set: function (value) {
if (typeof value !== "number") {
KICK.core.Util.fail("Shader.renderOrder must be a number");
}
_renderOrder = value;
}
},
/**
* Function that will be invoked in case of error
* @property errorLog
* @type Function
*/
errorLog: {
get: function () {
return _errorLog;
},
set: function (value) {
if (KICK.core.Constants._ASSERT) {
if (value && typeof value !== 'function') {
KICK.core.Util.fail("Shader.errorLog should be a function (or null)");
}
}
_errorLog = value;
}
},
/**
* A reference to the engine object
* @property engine
* @type KICK.core.Engine
*/
engine: {
value: engine
},
/**
* @property shaderProgramId
* @type ShaderProgram
*/
shaderProgramId: {
get: function () { return _shaderProgramId; }
},
/**
* (From http://www.opengl.org/)<br>
* When GL_POLYGON_OFFSET_FILL, GL_POLYGON_OFFSET_LINE, or GL_POLYGON_OFFSET_POINT is enabled, each
* fragment's depth value will be offset after it is interpolated from the depth values of the appropriate
* vertices. The value of the offset is factor × DZ + r × units , where DZ is a measurement of the change
* in depth relative to the screen area of the polygon, and r is the smallest value that is guaranteed to
* produce a resolvable offset for a given implementation. The offset is added before the depth test is
* performed and before the value is written into the depth buffer.<br><br>
*
* glPolygonOffset is useful for rendering hidden-line images, for applying decals to surfaces, and for
* rendering solids with highlighted edges.<br><br>
* Possible values:<br>
* true or false<br>
* Default false
* @property polygonOffsetEnabled
* @type boolean
*/
polygonOffsetEnabled: {
get: function () {
return _polygonOffsetEnabled;
},
set: function (value) {
_polygonOffsetEnabled = value;
}
},
/**
* Default 2.5
* @property polygonOffsetFactor
* @type Number
*/
polygonOffsetFactor: {
get: function () {
return _polygonOffsetFactor;
},
set: function (value){
_polygonOffsetFactor = value;
}
},
/**
* Default 10.0
* @property polygonOffsetUnits
* @type Number
*/
polygonOffsetUnits:{
get:function(){
return _polygonOffsetUnits;
},
set:function(value){
_polygonOffsetUnits = value;
}
},
/**
* Must be set to KICK.core.Constants.GL_FRONT, KICK.core.Constants.GL_BACK (default),
* KICK.core.Constants.GL_FRONT_AND_BACK, KICK.core.Constants.NONE<br>
* Note that in faceCulling = GL_FRONT, GL_BACK or GL_FRONT_AND_BACK with face culling enabled<br>
* faceCulling = GL_NONE means face culling disabled
* @property faceCulling
* @type Object
*/
faceCulling: {
get: function () { return _faceCulling; },
set: function (newValue) {
if (KICK.core.Constants._ASSERT) {
if (newValue !== core.Constants.GL_FRONT &&
newValue !== core.Constants.GL_FRONT_AND_BACK &&
newValue !== core.Constants.GL_BACK &&
newValue !== core.Constants.GL_NONE ) {
KICK.core.Util.fail("Shader.faceCulling must be KICK.material.Shader.FRONT, " +
"KICK.material.Shader.BACK (default), KICK.material.Shader.NONE");
}
}
_faceCulling = newValue;
}
},
/**
* Enable or disable writing into the depth buffer
* @property depthMask
* @type Boolean
*/
depthMask: {
get: function () { return _depthMask; },
set: function (newValue) {
if (KICK.core.Constants._ASSERT) {
if (typeof newValue !== 'boolean') {
KICK.core.Util.fail("Shader.depthMask must be a boolean. Was " + (typeof newValue));
}
}
_depthMask = newValue;
}
},
/**
* The depth test function. Must be one of
* KICK.core.Constants.GL_NEVER,
* KICK.core.Constants.GL_LESS,
* KICK.core.Constants.GL_EQUAL,
* KICK.core.Constants.GL_LEQUAL,
* KICK.core.Constants.GL_GREATER,
* KICK.core.Constants.GL_NOTEQUAL,
* KICK.core.Constants.GL_GEQUAL,
* KICK.core.Constants.GL_ALWAYS
* @property zTest
* @type Object
*/
zTest: {
get: function () { return _zTest; },
set: function (newValue) {
if (KICK.core.Constants._ASSERT) {
if (newValue !== core.Constants.GL_NEVER &&
newValue !== core.Constants.GL_LESS &&
newValue !== core.Constants.GL_EQUAL &&
newValue !== core.Constants.GL_LEQUAL &&
newValue !== core.Constants.GL_GREATER &&
newValue !== core.Constants.GL_NOTEQUAL &&
newValue !== core.Constants.GL_GEQUAL &&
newValue !== core.Constants.GL_ALWAYS){
KICK.core.Util.fail("Shader.zTest must be KICK.core.Constants.GL_NEVER, " +
"KICK.core.Constants.GL_LESS,KICK.core.Constants.GL_EQUAL,KICK.core.Constants.GL_LEQUAL," +
"KICK.core.Constants.GL_GREATER,KICK.core.Constants.GL_NOTEQUAL,KICK.core.Constants.GL_GEQUAL, " +
"or KICK.core.Constants.GL_ALWAYS");
}
}
_zTest = newValue;
}
},
/**
* Enables/disables blending (default is false).<br>
* "In RGBA mode, pixels can be drawn using a function that blends the incoming (source) RGBA values with the
* RGBA values that are already in the frame buffer (the destination values)"
* (From <a href="http://www.opengl.org/sdk/docs/man/xhtml/glBlendFunc.xml">www.Opengl.org</a>)
* @property blend
* @type Boolean
*/
blend: {
get: function () { return _blend; },
set: function (value) {
if (KICK.core.Constants._ASSERT) {
if (typeof value !== 'boolean') {
KICK.core.Util.fail("Shader.blend must be a boolean");
}
}
_blend = value;
updateBlendKey();
}
},
/**
* Specifies the blend s-factor<br>
* Initial value GL_SRC_ALPHA
* Must be set to one of: GL_ZERO, GL_ONE, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_DST_COLOR,
* GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA,
* GL_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, and
* GL_SRC_ALPHA_SATURATE.<br>
* See <a href="http://www.opengl.org/sdk/docs/man/xhtml/glBlendFunc.xml">glBlendFunc on opengl.org</a>
* @property blendSFactor
* @type Number
*/
blendSFactor: {
get: function () { return _blendSFactor; },
set: function (value) {
if (KICK.core.Constants._ASSERT) {
var c = KICK.core.Constants;
if (value !== c.GL_ZERO &&
value !== c.GL_ONE &&
value !== c.GL_SRC_COLOR &&
value !== c.GL_ONE_MINUS_SRC_COLOR &&
value !== c.GL_DST_COLOR &&
value !== c.GL_ONE_MINUS_DST_COLOR &&
value !== c.GL_SRC_ALPHA &&
value !== c.GL_ONE_MINUS_SRC_ALPHA &&
value !== c.GL_DST_ALPHA &&
value !== c.GL_ONE_MINUS_DST_ALPHA &&
value !== c.GL_CONSTANT_COLOR &&
value !== c.GL_ONE_MINUS_CONSTANT_COLOR &&
value !== c.GL_CONSTANT_ALPHA &&
value !== c.GL_ONE_MINUS_CONSTANT_ALPHA &&
value !== c.GL_SRC_ALPHA_SATURATE) {
KICK.core.Util.fail("Shader.blendSFactor must be a one of GL_ZERO, GL_ONE, GL_SRC_COLOR, " +
"GL_ONE_MINUS_SRC_COLOR, GL_DST_COLOR, GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA, " +
"GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_CONSTANT_COLOR, " +
"GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, and " +
"GL_SRC_ALPHA_SATURATE.");
}
}
_blendSFactor = value;
updateBlendKey();
}
},
/**
* Specifies the blend d-factor<br>
* Initial value GL_SRC_ALPHA
* Must be set to one of: GL_ZERO, GL_ONE, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_DST_COLOR,
* GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA,
* GL_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, and
* GL_ONE_MINUS_SRC_ALPHA.<br>
* See <a href="http://www.opengl.org/sdk/docs/man/xhtml/glBlendFunc.xml">glBlendFunc on opengl.org</a>
* @property blendDFactor
* @type Number
*/
blendDFactor: {
get: function () { return _blendDFactor; },
set: function (value) {
if (KICK.core.Constants._ASSERT) {
var c = KICK.core.Constants;
if (value !== c.GL_ZERO &&
value !== c.GL_ONE &&
value !== c.GL_SRC_COLOR &&
value !== c.GL_ONE_MINUS_SRC_COLOR &&
value !== c.GL_DST_COLOR &&
value !== c.GL_ONE_MINUS_DST_COLOR &&
value !== c.GL_SRC_ALPHA &&
value !== c.GL_ONE_MINUS_SRC_ALPHA &&
value !== c.GL_DST_ALPHA &&
value !== c.GL_ONE_MINUS_DST_ALPHA &&
value !== c.GL_CONSTANT_COLOR &&
value !== c.GL_ONE_MINUS_CONSTANT_COLOR &&
value !== c.GL_CONSTANT_ALPHA &&
value !== c.GL_ONE_MINUS_CONSTANT_ALPHA) {
KICK.core.Util.fail("Shader.blendSFactor must be a one of GL_ZERO, GL_ONE, GL_SRC_COLOR, " +
"GL_ONE_MINUS_SRC_COLOR, GL_DST_COLOR, GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA, " +
"GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_CONSTANT_COLOR, " +
"GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_ALPHA, and GL_ONE_MINUS_CONSTANT_ALPHA.");
}
}
_blendDFactor = value;
updateBlendKey();
}
}
});
/**
* Flush the current shader bound - this force the shader to be reloaded (and its uniforms and vertex attributes
* are reassigned)
* @method markUniformUpdated
*/
this.markUniformUpdated = function () {
gl.boundShader = -1;
gl.meshShader = -1;
};
/**
* Updates the shader (must be called after any shader state is changed to apply changes)
* @method apply
* @return {Boolean} shader created successfully
*/
this.apply = function () {
var errorLog = _errorLog || console.log,
vertexShader = compileShader(_vertexShaderSrc, false, errorLog),
fragmentShader = compileShader(_fragmentShaderSrc, true, errorLog),
compileError = fragmentShader === null || vertexShader === null,
i,
c = KICK.core.Constants,
numberOfActiveUniforms,
activeAttributes,
attribute;
if (compileError) {
vertexShader = compileShader(glslConstants["__error_vs.glsl"], false, errorLog);
fragmentShader = compileShader(glslConstants["__error_fs.glsl"], true, errorLog);
}
_shaderProgramId = gl.createProgram();
gl.attachShader(_shaderProgramId, vertexShader);
gl.attachShader(_shaderProgramId, fragmentShader);
gl.linkProgram(_shaderProgramId);
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
if (!gl.getProgramParameter(_shaderProgramId, c.GL_LINK_STATUS)) {
errorLog("Could not initialise shaders");
return false;
}
gl.useProgram(_shaderProgramId);
gl.boundShader = _shaderProgramId;
numberOfActiveUniforms = gl.getProgramParameter(_shaderProgramId, c.GL_ACTIVE_UNIFORMS);
updateActiveUniforms(numberOfActiveUniforms);
activeAttributes = gl.getProgramParameter( _shaderProgramId, c.GL_ACTIVE_ATTRIBUTES);
/**
* Array of JSON data with size,type and name
* @property activeAttributes
* @type Array_Object
*/
this.activeAttributes = [];
/**
* Lookup of attribute location based on name.
* @property lookupAttribute
* @type Object
*/
this.lookupAttribute = {};
for (i = 0; i < activeAttributes; i++) {
attribute = gl.getActiveAttrib(_shaderProgramId, i);
this.activeAttributes[i] = {
size: attribute.size,
type: attribute.type,
name: attribute.name
};
this.lookupAttribute[attribute.name] = i;
}
thisObj.markUniformUpdated();
return !compileError;
};
/**
* Deletes the shader program from memory.
* A destroyed shader can be used again if update shader is called
* @method destroy
*/
this.destroy = function () {
if (_shaderProgramId !== -1) {
gl.deleteProgram(_shaderProgramId);
_shaderProgramId = -1;
engine.project.removeResourceDescriptor(thisObj.uid);
}
};
/**
* Return true if the shader compiled successfully and is not destroyed
* @method isValid
* @return {Boolean} is shader valid
*/
this.isValid = function () {
return _shaderProgramId !== -1;
};
/**
* @method bind
*/
this.bind = function () {
if (KICK.core.Constants._ASSERT) {
if (!(thisObj.isValid)) {
KICK.core.Util.fail("Cannot bind a shader that is not valid");
}
}
if (gl.boundShader !== _shaderProgramId) {
gl.boundShader = _shaderProgramId;
gl.useProgram(_shaderProgramId);
updateCullFace();
updateDepthProperties();
updateBlending();
updatePolygonOffset();
}
};
/**
* Serializes the data into a JSON object (that can be used as a config parameter in the constructor)<br>
* Note errorLog are not serialized
* @method toJSON
* @return {Object} config element
*/
this.toJSON = function () {
if (_dataURI) {
return {
uid: thisObj.uid,
name: _name,
dataURI: _dataURI
};
}
return {
uid: thisObj.uid,
name: _name,
blend: _blend,
blendSFactor: _blendSFactor,
blendDFactor: _blendDFactor,
dataURI: _dataURI,
depthMask: _depthMask,
faceCulling: _faceCulling,
fragmentShaderSrc: _fragmentShaderSrc,
vertexShaderSrc: _vertexShaderSrc,
polygonOffsetEnabled: _polygonOffsetEnabled,
polygonOffsetFactor: _polygonOffsetFactor,
polygonOffsetUnits: _polygonOffsetUnits,
renderOrder: _renderOrder,
zTest: _zTest,
defaultUniforms: _defaultUniforms
};
};
(function init() {
applyConfig(thisObj, config);
engine.project.registerObject(thisObj, "KICK.material.Shader");
if (_dataURI && _dataURI.indexOf("memory://") !== 0) {
engine.resourceLoader.getShaderData(_dataURI, thisObj);
} else {
updateBlendKey();
thisObj.apply();
}
}());
};
/**
* @method getPrecompiledSource
* @param {KICK.core.Engine} engine
* @param {String} sourcecode
* @return {String} sourcecode after precompiler
* @static
*/
material.Shader.getPrecompiledSource = function (engine, sourcecode) {
var name,
source,
version = "#version 100",
lineOffset = 1,
indexOfNewline;
if (c._DEBUG) {
// insert #line nn after each #pragma include to give meaning full lines in error console
var linebreakPosition = [],
position = sourcecode.indexOf('\n'),
i;
while (position !== -1) {
position++;
linebreakPosition.push(position);
position = sourcecode.indexOf('\n', position);
}
for (i = linebreakPosition.length - 2; i >= 0; i--) {
position = linebreakPosition[i];
var nextPosition = linebreakPosition[i + 1];
if (sourcecode.substring(position).indexOf("#pragma include") === 0) {
sourcecode = sourcecode.substring(0, nextPosition) + ("#line " + (i + 2) + "\n") + sourcecode.substring(nextPosition);
}
}
}
for (name in material.GLSLConstants) {
if (material.GLSLConstants.hasOwnProperty(name)) {
if (typeof (name) === "string") {
source = material.GLSLConstants[name];
sourcecode = sourcecode.replace("#pragma include \"" + name + "\"", source);
sourcecode = sourcecode.replace("#pragma include \'" + name + "\'", source);
}
}
}
// if shader already contain version tag, then reuse this version information
if (sourcecode.indexOf("#version ") === 0) {
indexOfNewline = sourcecode.indexOf('\n');
version = sourcecode.substring(0, indexOfNewline); // save version info
sourcecode = sourcecode.substring(indexOfNewline + 1); // strip version info
lineOffset = 2;
}
sourcecode =
version + "\n" +
"#define SHADOWS " + (engine.config.shadows === true) + "\n" +
"#define LIGHTS " + (engine.config.maxNumerOfLights) + "\n" +
"#line " + lineOffset + "\n" +
sourcecode;
return sourcecode;
};
/**
* Update the material uniform
* @method bindMaterialUniform
* @param material
* @param engineUniforms
*/
material.Shader.prototype.bindMaterialUniform = function (material, engineUniforms) {
// lookup uniforms
var gl = this.gl,
timeObj,
sceneLights = engineUniforms.sceneLights,
ambientLight = sceneLights.ambientLight,
directionalLightData = sceneLights.directionalLightData,
pointLightData = sceneLights.pointLightData,
lookupUniforms = this.lookupUniform,
proj = lookupUniforms._proj,
directionalLightUniform = lookupUniforms._dLight,
pointLightUniform = lookupUniforms["_pLights[0]"],
time = lookupUniforms._time,
viewport = lookupUniforms._viewport,
lightUniformAmbient = lookupUniforms._ambient,
currentTexture = 0,
ambientLlightValue;
currentTexture = material.bind(currentTexture);
if (proj) {
gl.uniformMatrix4fv(proj.location, false, engineUniforms.projectionMatrix);
}
if (lightUniformAmbient) {
ambientLlightValue = ambientLight !== null ? ambientLight.colorIntensity : vec3Zero;
gl.uniform3fv(lightUniformAmbient.location, ambientLlightValue);
}
if (directionalLightUniform) {
gl.uniformMatrix3fv(directionalLightUniform.location, false, directionalLightData);
}
if (pointLightUniform) {
gl.uniformMatrix3fv(pointLightUniform.location, false, pointLightData);
}
if (time) {
timeObj = this.engine.time;
gl.uniform1f(time.location, timeObj.time);
}
if (viewport) {
gl.uniform2fv(viewport.location, gl.viewportSize);
}
return currentTexture;
};
/**
* Binds the uniforms to the current shader.