-
Notifications
You must be signed in to change notification settings - Fork 1
/
esper.js
3952 lines (3686 loc) · 364 KB
/
esper.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.esper = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function () {
'use strict';
var Texture2D = require('./Texture2D');
var ImageLoader = require('../util/ImageLoader');
var Util = require('../util/Util');
var MAG_FILTERS = {
NEAREST: true,
LINEAR: true
};
var MIN_FILTERS = {
NEAREST: true,
LINEAR: true,
NEAREST_MIPMAP_NEAREST: true,
LINEAR_MIPMAP_NEAREST: true,
NEAREST_MIPMAP_LINEAR: true,
LINEAR_MIPMAP_LINEAR: true
};
var WRAP_MODES = {
REPEAT: true,
MIRRORED_REPEAT: true,
CLAMP_TO_EDGE: true
};
var TYPES = {
UNSIGNED_BYTE: true,
FLOAT: true
};
var FORMATS = {
RGB: true,
RGBA: true
};
/**
* The default type for color textures.
*/
var DEFAULT_TYPE = 'UNSIGNED_BYTE';
/**
* The default format for color textures.
*/
var DEFAULT_FORMAT = 'RGBA';
/**
* The default wrap mode for color textures.
*/
var DEFAULT_WRAP = 'REPEAT';
/**
* The default min / mag filter for color textures.
*/
var DEFAULT_FILTER = 'LINEAR';
/**
* The default for whether alpha premultiplying is enabled.
*/
var DEFAULT_PREMULTIPLY_ALPHA = true;
/**
* The default for whether mipmapping is enabled.
*/
var DEFAULT_MIPMAP = true;
/**
* The default for whether invert-y is enabled.
*/
var DEFAULT_INVERT_Y = true;
/**
* Instantiates a ColorTexture2D object.
* @class ColorTexture2D
* @classdesc A texture class to represent a 2D color texture.
* @augments Texture2D
*
* @param {Object} spec - The specification arguments.
* @param {ImageData|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} spec.image - The HTMLImageElement to buffer.
* @param {String} spec.url - The HTMLImageElement URL to load and buffer.
* @param {Uint8Array|Float32Array} spec.src - The data to buffer.
* @param {number} width - The width of the texture.
* @param {number} height - The height of the texture.
* @param {String} spec.wrap - The wrapping type over both S and T dimension.
* @param {String} spec.wrapS - The wrapping type over the S dimension.
* @param {String} spec.wrapT - The wrapping type over the T dimension.
* @param {String} spec.filter - The min / mag filter used during scaling.
* @param {String} spec.minFilter - The minification filter used during scaling.
* @param {String} spec.magFilter - The magnification filter used during scaling.
* @param {bool} spec.mipMap - Whether or not mip-mapping is enabled.
* @param {bool} spec.invertY - Whether or not invert-y is enabled.
* @param {bool} spec.preMultiplyAlpha - Whether or not alpha premultiplying is enabled.
* @param {String} spec.format - The texture pixel format.
* @param {String} spec.type - The texture pixel component type.
* @param {Function} callback - The callback to be executed if the data is loaded asynchronously via a URL.
*/
function ColorTexture2D( spec, callback ) {
spec = spec || {};
// get specific params
spec.wrapS = spec.wrapS || spec.wrap;
spec.wrapT = spec.wrapT || spec.wrap;
spec.minFilter = spec.minFilter || spec.filter;
spec.magFilter = spec.magFilter || spec.filter;
// set texture params
spec.wrapS = WRAP_MODES[ spec.wrapS ] ? spec.wrapS : DEFAULT_WRAP;
spec.wrapT = WRAP_MODES[ spec.wrapT ] ? spec.wrapT : DEFAULT_WRAP;
spec.minFilter = MIN_FILTERS[ spec.minFilter ] ? spec.minFilter : DEFAULT_FILTER;
spec.magFilter = MAG_FILTERS[ spec.magFilter ] ? spec.magFilter : DEFAULT_FILTER;
// set other properties
spec.mipMap = spec.mipMap !== undefined ? spec.mipMap : DEFAULT_MIPMAP;
spec.invertY = spec.invertY !== undefined ? spec.invertY : DEFAULT_INVERT_Y;
spec.preMultiplyAlpha = spec.preMultiplyAlpha !== undefined ? spec.preMultiplyAlpha : DEFAULT_PREMULTIPLY_ALPHA;
// set format
spec.format = FORMATS[ spec.format ] ? spec.format : DEFAULT_FORMAT;
// buffer the texture based on argument type
if ( typeof spec.src === 'string' ) {
// request source from url
// TODO: put extension handling for arraybuffer / image / video differentiation
var that = this;
ImageLoader.load({
url: spec.src,
success: function( image ) {
// set to unsigned byte type
spec.type = 'UNSIGNED_BYTE';
spec.src = Util.resizeCanvas( spec, image );
Texture2D.call( that, spec );
if ( callback ) {
callback( null, that );
}
},
error: function( err ) {
if ( callback ) {
callback( err, null );
}
}
});
} else if ( Util.isCanvasType( spec.src ) ) {
// is image / canvas / video type
// set to unsigned byte type
spec.type = 'UNSIGNED_BYTE';
spec.src = Util.resizeCanvas( spec, spec.src );
Texture2D.call( this, spec );
} else {
// array, arraybuffer, or null
if ( spec.src === undefined ) {
// if no data is provided, assume this texture will be rendered
// to. In this case disable mipmapping, there is no need and it
// will only introduce very peculiar and difficult to discern
// rendering phenomena in which the texture 'transforms' at
// certain angles / distances to the mipmapped (empty) portions.
spec.mipMap = false;
}
// buffer from arg
spec.type = TYPES[ spec.type ] ? spec.type : DEFAULT_TYPE;
Texture2D.call( this, spec );
}
}
ColorTexture2D.prototype = Object.create( Texture2D.prototype );
module.exports = ColorTexture2D;
}());
},{"../util/ImageLoader":17,"../util/Util":20,"./Texture2D":8}],2:[function(require,module,exports){
(function () {
'use strict';
var Texture2D = require('./Texture2D');
var MAG_FILTERS = {
NEAREST: true,
LINEAR: true
};
var MIN_FILTERS = {
NEAREST: true,
LINEAR: true
};
var WRAP_MODES = {
REPEAT: true,
CLAMP_TO_EDGE: true,
MIRRORED_REPEAT: true
};
var DEPTH_TYPES = {
UNSIGNED_BYTE: true,
UNSIGNED_SHORT: true,
UNSIGNED_INT: true
};
var FORMATS = {
DEPTH_COMPONENT: true,
DEPTH_STENCIL: true
};
/**
* The default type for depth textures.
*/
var DEFAULT_TYPE = 'UNSIGNED_INT';
/**
* The default format for depth textures.
*/
var DEFAULT_FORMAT = 'DEPTH_COMPONENT';
/**
* The default wrap mode for depth textures.
*/
var DEFAULT_WRAP = 'CLAMP_TO_EDGE';
/**
* The default min / mag filter for depth textures.
*/
var DEFAULT_FILTER = 'LINEAR';
/**
* Instantiates a DepthTexture2D object.
* @class DepthTexture2D
* @classdesc A texture class to represent a 2D depth texture.
* @augments Texture2D
*
* @param {Object} spec - The specification arguments.
* @param {Uint8Array|Uint16Array|Uint32Array} spec.src - The data to buffer.
* @param {number} width - The width of the texture.
* @param {number} height - The height of the texture.
* @param {String} spec.wrap - The wrapping type over both S and T dimension.
* @param {String} spec.wrapS - The wrapping type over the S dimension.
* @param {String} spec.wrapT - The wrapping type over the T dimension.
* @param {String} spec.filter - The min / mag filter used during scaling.
* @param {String} spec.minFilter - The minification filter used during scaling.
* @param {String} spec.magFilter - The magnification filter used during scaling.
* @param {String} spec.format - The texture pixel format.
* @param {String} spec.type - The texture pixel component type.
* @param {Function} callback - The callback to be executed if the data is loaded asynchronously via a URL.
*/
function DepthTexture2D( spec ) {
spec = spec || {};
// get specific params
spec.wrapS = spec.wrapS || spec.wrap;
spec.wrapT = spec.wrapT || spec.wrap;
spec.minFilter = spec.minFilter || spec.filter;
spec.magFilter = spec.magFilter || spec.filter;
// set texture params
spec.wrapS = WRAP_MODES[ spec.wrapS ] ? spec.wrapS : DEFAULT_WRAP;
spec.wrapT = WRAP_MODES[ spec.wrapT ] ? spec.wrapT : DEFAULT_WRAP;
spec.minFilter = MIN_FILTERS[ spec.minFilter ] ? spec.minFilter : DEFAULT_FILTER;
spec.magFilter = MAG_FILTERS[ spec.magFilter ] ? spec.magFilter : DEFAULT_FILTER;
// set mip-mapping and format
spec.mipMap = false; // disable mip-mapping
spec.invertY = false; // no need to invert-y
spec.preMultiplyAlpha = false; // no alpha to pre-multiply
spec.format = FORMATS[ spec.format ] ? spec.format : DEFAULT_FORMAT;
// check if stencil-depth, or just depth
if ( spec.format === 'DEPTH_STENCIL' ) {
spec.type = 'UNSIGNED_INT_24_8_WEBGL';
} else {
spec.type = DEPTH_TYPES[ spec.type ] ? spec.type : DEFAULT_TYPE;
}
Texture2D.call( this, spec );
}
DepthTexture2D.prototype = Object.create( Texture2D.prototype );
module.exports = DepthTexture2D;
}());
},{"./Texture2D":8}],3:[function(require,module,exports){
(function () {
'use strict';
var WebGLContext = require('./WebGLContext');
var WebGLContextState = require('./WebGLContextState');
var TYPES = {
UNSIGNED_SHORT: true,
UNSIGNED_INT: true
};
var MODES = {
POINTS: true,
LINES: true,
LINE_STRIP: true,
LINE_LOOP: true,
TRIANGLES: true,
TRIANGLE_STRIP: true,
TRIANGLE_FAN: true
};
var BYTES_PER_TYPE = {
UNSIGNED_SHORT: 2,
UNSIGNED_INT: 4
};
/**
* The default component type.
*/
var DEFAULT_TYPE = 'UNSIGNED_SHORT';
/**
* The default render mode (primitive type).
*/
var DEFAULT_MODE = 'TRIANGLES';
/**
* The default byte offset to render from.
*/
var DEFAULT_BYTE_OFFSET = 0;
/**
* The default count of indices to render.
*/
var DEFAULT_COUNT = 0;
/**
* Instantiates an IndexBuffer object.
* @class IndexBuffer
* @classdesc An index buffer object.
*
* @param {Uint16Array|Uin32Array|Array} arg - The index data to buffer.
* @param {Object} options - The rendering options.
* @param {String} options.mode - The draw mode / primitive type.
* @param {String} options.byteOffset - The byte offset into the drawn buffer.
* @param {String} options.count - The number of vertices to draw.
*/
function IndexBuffer( arg, options ) {
options = options || {};
var gl = this.gl = WebGLContext.get();
this.state = WebGLContextState.get( gl );
this.buffer = gl.createBuffer();
this.type = TYPES[ options.type ] ? options.type : DEFAULT_TYPE;
// check if type is supported
if ( this.type === 'UNSIGNED_INT' && !WebGLContext.checkExtension( 'OES_element_index_uint' ) ) {
throw 'Cannot create IndexBuffer of type `UNSIGNED_INT` as extension `OES_element_index_uint` is not supported';
}
this.mode = MODES[ options.mode ] ? options.mode : DEFAULT_MODE;
this.count = ( options.count !== undefined ) ? options.count : DEFAULT_COUNT;
this.byteOffset = ( options.byteOffset !== undefined ) ? options.byteOffset : DEFAULT_BYTE_OFFSET;
this.byteLength = 0;
if ( arg ) {
if ( arg instanceof WebGLBuffer ) {
// WebGLBuffer argument
if ( options.byteLength === undefined ) {
throw 'Argument of type `WebGLBuffer` must be complimented with a corresponding `options.byteLength`';
}
this.byteLength = options.byteLength;
this.buffer = arg;
} else if ( typeof arg === 'number' ) {
// byte length argument
if ( options.type === undefined ) {
throw 'Argument of type `number` must be complimented with a corresponding `options.type`';
}
this.bufferData( arg );
} else if ( arg instanceof ArrayBuffer ) {
// ArrayBuffer arg
if ( options.type === undefined ) {
throw 'Argument of type `ArrayBuffer` must be complimented with a corresponding `options.type`';
}
this.bufferData( arg );
} else {
// Array or ArrayBufferView argument
this.bufferData( arg );
}
} else {
if ( options.type === undefined ) {
throw 'Empty buffer must be complimented with a corresponding `options.type`';
}
}
// ensure there isn't an overflow
if ( this.count * BYTES_PER_TYPE[ this.type ] + this.byteOffset > this.byteLength ) {
throw 'IndexBuffer `count` of ' + this.count + ' and `byteOffset` of ' + this.byteOffset + ' overflows the length of the buffer (' + this.byteLength + ')';
}
}
/**
* Upload index data to the GPU.
* @memberof IndexBuffer
*
* @param {Array|ArrayBuffer|ArrayBufferView|number} arg - The array of data to buffer.
*
* @returns {IndexBuffer} The index buffer object for chaining.
*/
IndexBuffer.prototype.bufferData = function( arg ) {
var gl = this.gl;
// cast array to ArrayBufferView based on provided type
if ( arg instanceof Array ) {
// check for type support
if ( this.type === 'UNSIGNED_INT' ) {
// uint32 is supported
arg = new Uint32Array( arg );
} else {
// buffer to uint16
arg = new Uint16Array( arg );
}
}
// set ensure type corresponds to data
if ( arg instanceof Uint16Array ) {
this.type = 'UNSIGNED_SHORT';
} else if ( arg instanceof Uint32Array ) {
this.type = 'UNSIGNED_INT';
} else if ( !( arg instanceof ArrayBuffer ) && typeof arg !== 'number' ) {
throw 'Argument must be of type `Array`, `ArrayBuffer`, `ArrayBufferView`, or `number`';
}
// don't overwrite the count if it is already set
if ( this.count === DEFAULT_COUNT ) {
if ( typeof arg === 'number' ) {
this.count = ( arg / BYTES_PER_TYPE[ this.type ] );
} else {
this.count = arg.length;
}
}
// set byte length
if ( typeof arg === 'number' ) {
if ( arg % BYTES_PER_TYPE[ this.type ] ) {
throw 'Byte length must be multiple of ' + BYTES_PER_TYPE[ this.type ];
}
this.byteLength = arg;
} else {
this.byteLength = arg.length * BYTES_PER_TYPE[ this.type ];
}
// buffer the data
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, this.buffer );
gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, arg, gl.STATIC_DRAW );
return this;
};
/**
* Upload partial index data to the GPU.
* @memberof IndexBuffer
*
* @param {Array|ArrayBuffer|ArrayBufferView} array - The array of data to buffer.
* @param {number} byteOffset - The byte offset at which to buffer.
*
* @returns {IndexBuffer} The vertex buffer object for chaining.
*/
IndexBuffer.prototype.bufferSubData = function( array, byteOffset ) {
var gl = this.gl;
if ( this.byteLength === 0 ) {
throw 'Buffer has not been allocated';
}
// cast array to ArrayBufferView based on provided type
if ( array instanceof Array ) {
// check for type support
if ( this.type === 'UNSIGNED_INT' ) {
// uint32 is supported
array = new Uint32Array( array );
} else {
// buffer to uint16
array = new Uint16Array( array );
}
} else if (
!( array instanceof Uint16Array ) &&
!( array instanceof Uint32Array ) &&
!( array instanceof ArrayBuffer ) ) {
throw 'Argument must be of type `Array`, `ArrayBuffer`, or `ArrayBufferView`';
}
byteOffset = ( byteOffset !== undefined ) ? byteOffset : DEFAULT_BYTE_OFFSET;
// get the total number of attribute components from pointers
var byteLength = array.length * BYTES_PER_TYPE[ this.type ];
if ( byteOffset + byteLength > this.byteLength ) {
throw 'Argument of length ' + byteLength + ' bytes and byte offset of ' + byteOffset + ' bytes overflows the buffer length of ' + this.byteLength + ' bytes';
}
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, this.buffer );
gl.bufferSubData( gl.ELEMENT_ARRAY_BUFFER, byteOffset, array );
return this;
};
/**
* Execute the draw command for the bound buffer.
* @memberof IndexBuffer
*
* @param {Object} options - The options to pass to 'drawElements'. Optional.
* @param {String} options.mode - The draw mode / primitive type.
* @param {String} options.byteOffset - The byteOffset into the drawn buffer.
* @param {String} options.count - The number of vertices to draw.
*
* @returns {IndexBuffer} Returns the index buffer object for chaining.
*/
IndexBuffer.prototype.draw = function( options ) {
options = options || {};
var gl = this.gl;
var mode = gl[ options.mode || this.mode ];
var type = gl[ this.type ];
var byteOffset = ( options.byteOffset !== undefined ) ? options.byteOffset : this.byteOffset;
var count = ( options.count !== undefined ) ? options.count : this.count;
if ( count === 0 ) {
throw 'Attempting to draw with a count of 0';
}
if ( byteOffset + count * BYTES_PER_TYPE[ this.type ] > this.byteLength ) {
throw 'Attempting to draw with `count` of ' + count + ' and `byteOffset` of ' + byteOffset + ' which overflows the total byte length of the buffer (' + this.byteLength + ')';
}
// if this buffer is already bound, exit early
if ( this.state.boundIndexBuffer !== this.buffer ) {
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, this.buffer );
this.state.boundIndexBuffer = this.buffer;
}
// draw elements
gl.drawElements( mode, count, type, byteOffset );
return this;
};
module.exports = IndexBuffer;
}());
},{"./WebGLContext":13,"./WebGLContextState":14}],4:[function(require,module,exports){
(function () {
'use strict';
var WebGLContext = require('./WebGLContext');
var WebGLContextState = require('./WebGLContextState');
var Util = require('../util/Util');
var TEXTURE_TARGETS = {
TEXTURE_2D: true,
TEXTURE_CUBE_MAP: true
};
var DEPTH_FORMATS = {
DEPTH_COMPONENT: true,
DEPTH_STENCIL: true
};
/**
* Instantiates a RenderTarget object.
* @class RenderTarget
* @classdesc A renderTarget class to allow rendering to textures.
*/
function RenderTarget() {
var gl = this.gl = WebGLContext.get();
this.state = WebGLContextState.get( gl );
this.framebuffer = gl.createFramebuffer();
this.textures = {};
}
/**
* Binds the renderTarget object and pushes it to the front of the stack.
* @memberof RenderTarget
*
* @returns {RenderTarget} The renderTarget object, for chaining.
*/
RenderTarget.prototype.push = function() {
if ( this.state.renderTargets.top() !== this ) {
var gl = this.gl;
gl.bindFramebuffer( gl.FRAMEBUFFER, this.framebuffer );
}
this.state.renderTargets.push( this );
return this;
};
/**
* Unbinds the renderTarget object and binds the renderTarget beneath it on this stack. If there is no underlying renderTarget, bind the backbuffer.
* @memberof RenderTarget
*
* @returns {RenderTarget} The renderTarget object, for chaining.
*/
RenderTarget.prototype.pop = function() {
var state = this.state;
// if there is no render target bound, exit early
if ( state.renderTargets.top() !== this ) {
throw 'The current render target is not the top most element on the stack';
}
state.renderTargets.pop();
var top = state.renderTargets.top();
var gl;
if ( top ) {
gl = top.gl;
gl.bindFramebuffer( gl.FRAMEBUFFER, top.framebuffer );
} else {
gl = this.gl;
gl.bindFramebuffer( gl.FRAMEBUFFER, null );
}
return this;
};
/**
* Attaches the provided texture to the provided attachment location.
* @memberof RenderTarget
*
* @param {Texture2D} texture - The texture to attach.
* @param {number} index - The attachment index. (optional)
* @param {String} target - The texture target type. (optional)
*
* @returns {RenderTarget} The renderTarget object, for chaining.
*/
RenderTarget.prototype.setColorTarget = function( texture, index, target ) {
var gl = this.gl;
if ( !texture ) {
throw 'Texture argument is missing';
}
if ( TEXTURE_TARGETS[ index ] && target === undefined ) {
target = index;
index = 0;
}
if ( index === undefined ) {
index = 0;
} else if ( !Util.isInteger( index ) || index < 0 ) {
throw 'Texture color attachment index is invalid';
}
if ( target && !TEXTURE_TARGETS[ target ] ) {
throw 'Texture target is invalid';
}
this.textures[ 'color' + index ] = texture;
this.push();
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl[ 'COLOR_ATTACHMENT' + index ],
gl[ target || 'TEXTURE_2D' ],
texture.texture,
0 );
this.pop();
return this;
};
/**
* Attaches the provided texture to the provided attachment location.
* @memberof RenderTarget
*
* @param {Texture2D} texture - The texture to attach.
*
* @returns {RenderTarget} The renderTarget object, for chaining.
*/
RenderTarget.prototype.setDepthTarget = function( texture ) {
if ( !texture ) {
throw 'Texture argument is missing';
}
if ( !DEPTH_FORMATS[ texture.format ] ) {
throw 'Provided texture is not of format `DEPTH_COMPONENT` or `DEPTH_STENCIL`';
}
var gl = this.gl;
this.textures.depth = texture;
this.push();
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.DEPTH_ATTACHMENT,
gl.TEXTURE_2D,
texture.texture,
0 );
this.pop();
return this;
};
/**
* Resizes the renderTarget and all attached textures by the provided height and width.
* @memberof RenderTarget
*
* @param {number} width - The new width of the renderTarget.
* @param {number} height - The new height of the renderTarget.
*
* @returns {RenderTarget} The renderTarget object, for chaining.
*/
RenderTarget.prototype.resize = function( width, height ) {
if ( typeof width !== 'number' || ( width <= 0 ) ) {
throw 'Provided `width` of ' + width + ' is invalid';
}
if ( typeof height !== 'number' || ( height <= 0 ) ) {
throw 'Provided `height` of ' + height + ' is invalid';
}
var textures = this.textures;
Object.keys( textures ).forEach( function( key ) {
textures[ key ].resize( width, height );
});
return this;
};
module.exports = RenderTarget;
}());
},{"../util/Util":20,"./WebGLContext":13,"./WebGLContextState":14}],5:[function(require,module,exports){
(function () {
'use strict';
var VertexPackage = require('../core/VertexPackage');
var VertexBuffer = require('../core/VertexBuffer');
var IndexBuffer = require('../core/IndexBuffer');
/**
* Iterates over all attribute pointers and throws an exception if an index
* occurs mroe than once.
* @private
*
* @param {Array} vertexBuffers - The array of vertexBuffers.
*/
function checkIndexCollisions( vertexBuffers ) {
var indices = {};
vertexBuffers.forEach( function( buffer ) {
Object.keys( buffer.pointers ).forEach( function( index ) {
indices[ index ] = indices[ index ] || 0;
indices[ index ]++;
});
});
Object.keys( indices ).forEach( function( index ) {
if ( indices[ index ] > 1 ) {
throw 'More than one attribute pointer exists for index ' + index;
}
});
}
/**
* Instantiates an Renderable object.
* @class Renderable
* @classdesc A container for one or more VertexBuffers and an optional IndexBuffer.
*
* @param {Object} spec - The renderable specification object.
* @param {Array|Float32Array} spec.vertices - The vertices to interleave and buffer.
* @param {VertexBuffer} spec.vertexBuffer - An existing vertex buffer to use.
* @param {VertexBuffer[]} spec.vertexBuffers - Multiple vertex buffers to use.
* @param {Array|Uint16Array|Uint32Array} spec.indices - The indices to buffer.
* @param {IndexBuffer} spec.indexbuffer - An existing index buffer to use.
* @param {String} spec.mode - The draw mode / primitive type.
* @param {String} spec.byteOffset - The byte offset into the drawn buffer.
* @param {String} spec.count - The number of vertices to draw.
*/
function Renderable( spec ) {
spec = spec || {};
if ( spec.vertexBuffer || spec.vertexBuffers ) {
// use existing vertex buffer
this.vertexBuffers = spec.vertexBuffers || [ spec.vertexBuffer ];
} else if ( spec.vertices ) {
// create vertex package
var vertexPackage = new VertexPackage( spec.vertices );
// create vertex buffer
this.vertexBuffers = [ new VertexBuffer( vertexPackage ) ];
} else {
this.vertexBuffers = [];
}
if ( spec.indexBuffer ) {
// use existing index buffer
this.indexBuffer = spec.indexBuffer;
} else if ( spec.indices ) {
// create index buffer
this.indexBuffer = new IndexBuffer( spec.indices );
} else {
this.indexBuffer = null;
}
// check that no attribute indices clash
checkIndexCollisions( this.vertexBuffers );
// store rendering options
this.options = {
mode: spec.mode,
byteOffset: spec.byteOffset,
count: spec.count
};
}
/**
* Execute the draw command for the underlying buffers.
* @memberof Renderable
*
* @param {Object} options - The options to pass to 'drawElements'. Optional.
* @param {String} options.mode - The draw mode / primitive type.
* @param {String} options.byteOffset - The byteOffset into the drawn buffer.
* @param {String} options.count - The number of vertices to draw.
*
* @returns {Renderable} Returns the renderable object for chaining.
*/
Renderable.prototype.draw = function( options ) {
var overrides = options || {};
// override options if provided
overrides.mode = overrides.mode || this.options.mode;
overrides.byteOffset = ( overrides.byteOffset !== undefined ) ? overrides.byteOffset : this.options.byteOffset;
overrides.count = ( overrides.count !== undefined ) ? overrides.count : this.options.count;
// draw the renderable
if ( this.indexBuffer ) {
// use index buffer to draw elements
// bind vertex buffers and enable attribute pointers
this.vertexBuffers.forEach( function( vertexBuffer ) {
vertexBuffer.bind();
});
// draw primitives using index buffer
this.indexBuffer.draw( overrides );
// disable attribute pointers
this.vertexBuffers.forEach( function( vertexBuffer ) {
vertexBuffer.unbind();
});
// no advantage to unbinding as there is no stack used
} else {
// no index buffer, use draw arrays
this.vertexBuffers.forEach( function( vertexBuffer ) {
vertexBuffer.bind();
vertexBuffer.draw( overrides );
vertexBuffer.unbind();
});
}
return this;
};
module.exports = Renderable;
}());
},{"../core/IndexBuffer":3,"../core/VertexBuffer":10,"../core/VertexPackage":11}],6:[function(require,module,exports){
(function () {
'use strict';
var WebGLContext = require('./WebGLContext');
var ShaderParser = require('./ShaderParser');
var WebGLContextState = require('./WebGLContextState');
var Async = require('../util/Async');
var XHRLoader = require('../util/XHRLoader');
var UNIFORM_FUNCTIONS = {
'bool': 'uniform1i',
'bool[]': 'uniform1iv',
'float': 'uniform1f',
'float[]': 'uniform1fv',
'int': 'uniform1i',
'int[]': 'uniform1iv',
'uint': 'uniform1i',
'uint[]': 'uniform1iv',
'vec2': 'uniform2fv',
'vec2[]': 'uniform2fv',
'ivec2': 'uniform2iv',
'ivec2[]': 'uniform2iv',
'vec3': 'uniform3fv',
'vec3[]': 'uniform3fv',
'ivec3': 'uniform3iv',
'ivec3[]': 'uniform3iv',
'vec4': 'uniform4fv',
'vec4[]': 'uniform4fv',
'ivec4': 'uniform4iv',
'ivec4[]': 'uniform4iv',
'mat2': 'uniformMatrix2fv',
'mat2[]': 'uniformMatrix2fv',
'mat3': 'uniformMatrix3fv',
'mat3[]': 'uniformMatrix3fv',
'mat4': 'uniformMatrix4fv',
'mat4[]': 'uniformMatrix4fv',
'sampler2D': 'uniform1i',
'samplerCube': 'uniform1i'
};
/**
* Given a map of existing attributes, find the lowest index that is not
* already used. If the attribute ordering was already provided, use that
* instead.
* @private
*
* @param {Object} attributes - The existing attributes object.
* @param {Object} declaration - The attribute declaration object.
*
* @returns {number} The attribute index.
*/
function getAttributeIndex( attributes, declaration ) {
// check if attribute is already declared, if so, use that index
if ( attributes[ declaration.name ] ) {
return attributes[ declaration.name ].index;
}
// return next available index
return Object.keys( attributes ).length;
}
/**
* Given vertex and fragment shader source, parses the declarations and appends information pertaining to the uniforms and attribtues declared.
* @private
*
* @param {Shader} shader - The shader object.
* @param {String} vertSource - The vertex shader source.
* @param {String} fragSource - The fragment shader source.
*
* @returns {Object} The attribute and uniform information.
*/
function setAttributesAndUniforms( shader, vertSource, fragSource ) {
var declarations = ShaderParser.parseDeclarations(
[ vertSource, fragSource ],
[ 'uniform', 'attribute' ]
);
// for each declaration in the shader
declarations.forEach( function( declaration ) {
// check if its an attribute or uniform
if ( declaration.qualifier === 'attribute' ) {
// if attribute, store type and index
var index = getAttributeIndex( shader.attributes, declaration );
shader.attributes[ declaration.name ] = {
type: declaration.type,
index: index
};
} else if ( declaration.qualifier === 'uniform' ) {
// if uniform, store type and buffer function name
shader.uniforms[ declaration.name ] = {
type: declaration.type,
func: UNIFORM_FUNCTIONS[ declaration.type + (declaration.count > 1 ? '[]' : '') ]
};
}
});
}
/**
* Given a shader source string and shader type, compiles the shader and returns the resulting WebGLShader object.
* @private
*
* @param {WebGLRenderingContext} gl - The webgl rendering context.
* @param {String} shaderSource - The shader source.
* @param {String} type - The shader type.
*
* @returns {WebGLShader} The compiled shader object.
*/
function compileShader( gl, shaderSource, type ) {
var shader = gl.createShader( gl[ type ] );
gl.shaderSource( shader, shaderSource );
gl.compileShader( shader );
if ( !gl.getShaderParameter( shader, gl.COMPILE_STATUS ) ) {
throw 'An error occurred compiling the shaders:\n' + gl.getShaderInfoLog( shader );
}
return shader;
}
/**
* Binds the attribute locations for the Shader object.
* @private
*
* @param {Shader} shader - The Shader object.
*/
function bindAttributeLocations( shader ) {
var gl = shader.gl;
var attributes = shader.attributes;
Object.keys( attributes ).forEach( function( key ) {
// bind the attribute location
gl.bindAttribLocation(
shader.program,
attributes[ key ].index,
key );
});
}
/**
* Queries the webgl rendering context for the uniform locations.
* @private
*
* @param {Shader} shader - The Shader object.
*/
function getUniformLocations( shader ) {
var gl = shader.gl;
var uniforms = shader.uniforms;
Object.keys( uniforms ).forEach( function( key ) {
// get the uniform location
uniforms[ key ].location = gl.getUniformLocation( shader.program, key );
});
}
/**
* Returns a function to load shader source from a url.
* @private
*
* @param {String} url - The url to load the resource from.
*
* @returns {Function} The function to load the shader source.
*/
function loadShaderSource( url ) {
return function( done ) {
XHRLoader.load({
url: url,
responseType: 'text',
success: function( res ) {
done( null, res );
},
error: function( err ) {
done( err, null );
}
});
};
}
/**
* Returns a function to pass through the shader source.
* @private
*
* @param {String} source - The source of the shader.
*
* @returns {Function} The function to pass through the shader source.
*/
function passThroughSource( source ) {
return function( done ) {
done( null, source );
};
}
/**
* Returns a function that takes an array of GLSL source strings and URLs, and resolves them into and array of GLSL source.
* @private
*
* @param {Array} sources - The shader sources.
*
* @returns - A function to resolve the shader sources.
*/
function resolveSources( sources ) {
return function( done ) {
var tasks = [];
sources = sources || [];
sources = ( !( sources instanceof Array ) ) ? [ sources ] : sources;
sources.forEach( function( source ) {
if ( ShaderParser.isGLSL( source ) ) {
tasks.push( passThroughSource( source ) );
} else {
tasks.push( loadShaderSource( source ) );
}
});
Async.parallel( tasks, done );
};
}
/**
* Creates the shader program object from source strings. This includes: