-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathStageGL.js
More file actions
2974 lines (2641 loc) · 104 KB
/
StageGL.js
File metadata and controls
2974 lines (2641 loc) · 104 KB
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
/*
* StageGL
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @module EaselJS
*/
this.createjs = this.createjs||{};
/*
* README IF EDITING:
*
* - Terminology for developers:
* Vertex: a point that help defines a shape, 3 per triangle. Usually has an x,y,z but can have more/less info.
* Vertex Property: a piece of information attached to the vertex like a vector3 containing x,y,z
* Index/Indices: used in groups of 3 to define a triangle, points to vertices by their index in an array (some render
* modes do not use these)
* Card: a group of 2 triangles used to display a rectangular image
* UV: common names for the [0-1] texture co-ordinates on an image
* Batch: a single call to the renderer, best done as little as possible. Multiple cards are batched for this reason
* Program/Shader: For every vertex we run the Vertex shader. The results are used per pixel by the Fragment shader. When
* combined and paired these are a "shader program"
* Texture: WebGL representation of image data and associated extra information, separate from a DOM Image
* Slot: A space on the GPU into which textures can be loaded for use in a batch, i.e. using "ActiveTexture" switches texture slot.
* Render___: actual WebGL draw call
* Buffer: WebGL array data
* Cover: A card that covers the entire viewport
* Dst: The existing drawing surface in the shader
* Src: The new data being provided in the shader
*
* - Notes:
* WebGL treats 0,0 as the bottom left, as such there's a lot of co-ordinate space flipping to make regular canvas
* numbers make sense to users and WebGL simultaneously. This extends to textures stored in memory too. If writing
* code that deals with x/y, be aware your y may be flipped.
* Older versions had distinct internal paths for filters and regular draws, these have been merged.
* Draws are slowly assembled out of found content. Overflowing things like shaders, object/texture count will cause
* an early draw before continuing. Lookout for the things that force a draw. Marked with <------------------------
*/
(function () {
"use strict";
/**
* A StageGL instance is the root level {{#crossLink "Container"}}{{/crossLink}} for a WebGL-optimized display list,
* which can be used in place of the usual {{#crossLink "Stage"}}{{/crossLink}}. This class should behave identically
* to a {{#crossLink "Stage"}}{{/crossLink}} except for WebGL-specific functionality.
*
* Each time the {{#crossLink "Stage/tick"}}{{/crossLink}} method is called, the display list is rendered to the
* target <canvas/> instance, ignoring non-WebGL-compatible display objects. On devices and browsers that don't
* support WebGL, content will automatically be rendered to canvas 2D context instead.
*
* <h4>Limitations</h4>
* - {{#crossLink "Shape"}}{{/crossLink}}, {{#crossLink "Shadow"}}{{/crossLink}}, and {{#crossLink "Text"}}{{/crossLink}}
* are not rendered when added to the display list.
* - To display something StageGL cannot render, {{#crossLink "displayObject/cache"}}{{/crossLink}} the object.
* Caches can be rendered regardless of source.
* - Images are wrapped as a webGL "Texture". Each graphics card has a limit to its concurrent Textures, too many
* Textures will noticeably slow performance.
* - Each cache counts as an individual Texture. As such {{#crossLink "SpriteSheet"}}{{/crossLink}} and
* {{#crossLink "SpriteSheetBuilder"}}{{/crossLink}} are recommended practices to help keep texture counts low.
* - To use any image node (DOM Image/Canvas Element) between multiple StageGL instances it must be a
* {{#crossLink "Bitmap/clone"}}{{/crossLink}}, otherwise the GPU texture loading and tracking will get confused.
* - to avoid an up/down scaled render you must call {{#crossLink "StageGL/updateViewport"}}{{/crossLink}} if you
* resize your canvas after making a StageGL instance, this will properly size the WebGL context stored in memory.
* - Best performance in demanding scenarios will come from manual management of texture memory, but it is handled
* automatically by default. See {{#crossLink "StageGL/releaseTexture"}}{{/crossLink}} for details.
* - Disable `directDraw` to get access to cacheless filters and composite oeprations!
*
* <h4>Example</h4>
* This example creates a StageGL instance, adds a child to it, then uses the EaselJS {{#crossLink "Ticker"}}{{/crossLink}}
* to update the child and redraw the stage.
*
* var stage = new createjs.StageGL("canvasElementId");
*
* var image = new createjs.Bitmap("imagePath.png");
* stage.addChild(image);
*
* createjs.Ticker.on("tick", handleTick);
*
* function handleTick(event) {
* image.x += 10;
* stage.update();
* }
*
* @class StageGL
* @extends Stage
* @constructor
* @param {HTMLCanvasElement | String | Object} canvas A canvas object that StageGL will render to, or the string id
* of a canvas object in the current DOM.
* @param {Object} options All the option parameters in a reference object, some are not supported by some browsers.
* @param {Boolean} [options.preserveBuffer=false] If `true`, the canvas is NOT auto-cleared by WebGL (the spec
* discourages setting this to `true`). This is useful if you want persistent draw effects and has also fixed device
* specific bugs due to mis-timed clear commands.
* @param {Boolean} [options.antialias=false] Specifies whether or not the browser's WebGL implementation should try
* to perform anti-aliasing. This will also enable linear pixel sampling on power-of-two textures (smoother images).
* @param {Boolean} [options.transparent=false] If `true`, the canvas is transparent. This is <strong>very</strong>
* expensive, and should be used with caution.
* @param {Boolean} [options.directDraw=true] If `true`, this will bypass intermediary render-textures when possible
* resulting in reduced memory and increased performance, this disables some features. Cache-less filters and some
* {{#crossLink "DisplayObject/compositeOperation:property"}}{{/crossLink}} values rely on this being false.
* @param (Boolean} [options.premultiply] @deprecated Upgraded colour & transparency handling have fixed the issue
* this flag was trying to solve rendering it unnecessary.
* @param {int} [options.autoPurge=1200] How often the system should automatically dump unused textures. Calls
* `purgeTextures(autoPurge)` every `autoPurge/2` draws. See {{#crossLink "StageGL/purgeTextures"}}{{/crossLink}}
* for more information on texture purging.
* @param {String|int} [options.clearColor=undefined] Automatically calls {{#crossLink "StageGL/setClearColor"}}{{/crossLink}}
* after init is complete, can be overridden and changed manually later.
* @param {String|int} [options.batchSize=DEFAULT_MAX_BATCH_SIZE] The size of the buffer used to retain a batch.
* Making it smaller reduces GPU load, but making it too small adds extra GPU calls. Figure out your maximum batch
* count and set it to a small buffer above that per-project. Check src/utils/WebGLInspector to track.
*/
function StageGL(canvas, options) {
this.Stage_constructor(canvas);
var transparent, antialias, preserveBuffer, autoPurge, directDraw, batchSize;
if (options !== undefined) {
if (typeof options !== "object"){ throw("Invalid options object"); }
transparent = options.transparent;
antialias = options.antialias;
preserveBuffer = options.preserveBuffer;
autoPurge = options.autoPurge;
directDraw = options.directDraw;
batchSize = options.batchSize;
}
// public properties:
/**
* Console log potential issues and problems. This is designed to have <em>minimal</em> performance impact, so
* if extensive debugging information is required, this may be inadequate. See {{#crossLink "WebGLInspector"}}{{/crossLink}}
* @property vocalDebug
* @type {Boolean}
* @default false
*/
this.vocalDebug = false;
/**
* Specifies whether this instance is slaved to a {{#crossLink "BitmapCache"}}{{/crossLink}} or draws independantly.
* Necessary to control texture outputs and behaviours when caching. StageGL cache outputs will only render
* properly for the StageGL that made them. See the {{#crossLink "cache"}}{{/crossLink}} function documentation
* for more information. Enabled by default when BitmapCache's `useGL` is true.
* NOTE: This property is mainly for internal use, though it may be useful for advanced uses.
* @property isCacheControlled
* @type {Boolean}
* @default false
*/
this.isCacheControlled = false;
// private properties:
/**
* Specifies whether or not the canvas is auto-cleared by WebGL. The WebGL spec discourages `true`.
* If true, the canvas is NOT auto-cleared by WebGL. Used when the canvas context is created and requires
* context re-creation to update.
* @property _preserveBuffer
* @protected
* @type {Boolean}
* @default false
*/
this._preserveBuffer = preserveBuffer||false;
/**
* Specifies whether or not the browser's WebGL implementation should try to perform anti-aliasing.
* @property _antialias
* @protected
* @type {Boolean}
* @default false
*/
this._antialias = antialias||false;
/**
* Specifies whether or not the browser's WebGL implementation should be transparent.
* @property _transparent
* @protected
* @type {Boolean}
* @default false
*/
this._transparent = transparent||false;
/**
* Internal value of {{#crossLink "StageGL/autoPurge"}}{{/crossLink}}
* @property _autoPurge
* @protected
* @type {int}
* @default null
*/
this._autoPurge = undefined;
this.autoPurge = autoPurge; //getter/setter handles setting the real value and validating and documentation
/**
* See directDraw
* @property _directDraw
* @protected
* @type {Boolean}
* @default false
*/
this._directDraw = directDraw === undefined ? true : (!!directDraw);
/**
* The width in px of the drawing surface saved in memory.
* @property _viewportWidth
* @protected
* @type {Number}
* @default 0
*/
this._viewportWidth = 0;
/**
* The height in px of the drawing surface saved in memory.
* @property _viewportHeight
* @protected
* @type {Number}
* @default 0
*/
this._viewportHeight = 0;
/**
* A 2D projection matrix used to convert WebGL's viewspace into canvas co-ordinates. Regular canvas display
* uses Top-Left values of [0,0] where WebGL uses a Center [0,0] Top-Right [1,1] (euclidean) system.
* @property _projectionMatrix
* @protected
* @type {Float32Array}
* @default null
*/
this._projectionMatrix = null;
/**
* The current WebGL canvas context. Often shorthanded to just "gl" in many parts of the code.
* @property _webGLContext
* @protected
* @type {WebGLRenderingContext}
* @default null
*/
this._webGLContext = null;
/**
* Reduce API logic by allowing stage to behave as a renderTexture target, should always be null as null is canvas.
* @type {null}
* @protected
*/
this._frameBuffer = null;
/**
* The color to use when the WebGL canvas has been cleared. May appear as a background color. Defaults to grey.
* @property _clearColor
* @protected
* @type {Object}
* @default {r: 0.50, g: 0.50, b: 0.50, a: 0.00}
*/
this._clearColor = {r: 0.50, g: 0.50, b: 0.50, a: 0.00};
/**
* The maximum number of verticies (6 make a single sprite) that can be drawn in one draw call. Use constructor props
* to modify otherwise internal buffers may be invalid sizes.
* @property _maxBatchVertexCount
* @protected
* @type {Number}
* @default StageGL.DEFAULT_MAX_BATCH_SIZE * StageGL.INDICIES_PER_CARD
*/
this._maxBatchVertexCount = Math.max(
Math.min(
Number(batchSize) || StageGL.DEFAULT_MAX_BATCH_SIZE,
StageGL.DEFAULT_MAX_BATCH_SIZE)
, StageGL.DEFAULT_MIN_BATCH_SIZE) * StageGL.INDICIES_PER_CARD;
/**
* The shader program used to draw the current batch.
* @property _activeShader
* @protected
* @type {WebGLProgram}
* @default null
*/
this._activeShader = null;
/**
* The non cover, per object shader used for most rendering actions.
* @type {WebGLProgram}
* @protected
*/
this._mainShader = null;
/**
* All the different vertex attribute sets that can be used with the render buffer. Currently only internal,
* if/when alternate main shaders are possible, they'll register themselves here.
* @property _attributeConfig
* @protected
* @type {Object}
*/
this._attributeConfig = {};
/**
* Which of the configs in {{#crossLink "StageGL/_attributeConfig:property"}}{{/crossLink}} is currently active.
* @property _activeConfig
* @protected
* @type {Object}
*/
this._activeConfig = null;
/**
* One of the major render buffers used in composite blending drawing. Do not expect this to always be the same object.
* "What you're drawing to", object occasionally swaps with concat.
* @property _bufferTextureOutput
* @protected
* @type {WebGLTexture}
*/
this._bufferTextureOutput = null;
/**
* One of the major render buffers used in composite blending drawing. Do not expect this to always be the same object.
* "What you've draw before now", object occasionally swaps with output.
* @property _bufferTextureConcat
* @protected
* @type {WebGLTexture}
*/
this._bufferTextureConcat = null;
/**
* One of the major render buffers used in composite blending drawing.
* "Temporary mixing surface"
* @property _bufferTextureTemp
* @protected
* @type {WebGLTexture}
*/
this._bufferTextureTemp = null;
/**
* The current render buffer being targeted, usually targets internal buffers, but may be set to cache's buffer during a cache render.
* @property _batchTextureOutput
* @protected
* @type {WebGLTexture | StageGL}
*/
this._batchTextureOutput = this;
/**
* The current render buffer being targeted, usually targets internal buffers, but may be set to cache's buffer during a cache render.
* @property _batchTextureConcat
* @protected
* @type {WebGLTexture}
*/
this._batchTextureConcat = null;
/**
* The current render buffer being targeted, usually targets internal buffers, but may be set to cache's buffer during a cache render.
* @property _batchTextureTemp
* @protected
* @type {WebGLTexture}
*/
this._batchTextureTemp = null;
/**
* Internal library of the shaders that have been compiled and created along with their parameters. Should contain
* compiled `gl.ShaderProgram` and settings for `gl.blendFunc` and `gl.blendEquation`. Populated as requested.
*
* See {{#crossLink "StageGL/_updateRenderMode:method"}}{{/crossLink}} for exact details.
* @type {Object}
* @private
*/
this._builtShaders = {};
/**
* An index based lookup of every WebGL Texture currently in use.
* @property _drawTexture
* @protected
* @type {Array}
*/
this._textureDictionary = [];
/**
* A string based lookup hash of which index a texture is stored at in the dictionary. The lookup string is
* often the src url.
* @property _textureIDs
* @protected
* @type {Object}
*/
this._textureIDs = {};
/**
* An array of all the textures currently loaded into the GPU. The index in the array matches the GPU index.
* @property _batchTextures
* @protected
* @type {Array}
*/
this._batchTextures = [];
/**
* An array of all the simple filler textures used to prevent issues with missing textures in a batch.
* @property _baseTextures
* @protected
* @type {Array}
*/
this._baseTextures = [];
/**
* Texture slots for a draw
* @property _gpuTextureCount
* @protected
* @type {uint}
*/
this._gpuTextureCount = 8;
/**
* Texture slots on the hardware
* @property _gpuTextureMax
* @protected
* @type {uint}
*/
this._gpuTextureMax = 8;
/**
* Texture slots in a batch for User textures
* @property _batchTextureCount
* @protected
* @type {uint}
*/
this._batchTextureCount = 0;
/**
* The location at which the last texture was inserted into a GPU slot
*/
this._lastTextureInsert = -1;
/**
* The current string name of the render mode being employed per Context2D spec.
* Must start invalid to trigger default shader into being built during init.
* https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
* @type {string}
* @private
*/
this._renderMode = "";
/**
* Flag indicating that the content being batched in `appendToBatch` must be drawn now and not follow batch logic.
* Used for effects that are compounding in nature and cannot be applied in a single pass.
* Should be enabled with extreme care due to massive performance implications.
* @type {boolean}
* @private
*/
this._immediateRender = false;
/**
* Vertices drawn into the batch so far.
* @type {number}
* @private
*/
this._batchVertexCount = 0;
/**
* The current batch being drawn, A batch consists of a call to `drawElements` on the GPU. Many of these calls
* can occur per draw.
* @property _batchId
* @protected
* @type {Number}
* @default 0
*/
this._batchID = 0;
/**
* The current draw being performed, may contain multiple batches. Comparing to {{#crossLink "StageGL/_batchID:property"}}{{/crossLink}}
* can reveal batching efficiency.
* @property _drawID
* @protected
* @type {Number}
* @default 0
*/
this._drawID = 0;
/**
* Tracks how many renders have occurred this draw, used for performance monitoring and empty draw avoidance.
* @property _renderPerDraw
* @protected
* @type {Number}
* @default 0
*/
this._renderPerDraw = 0;
/**
* Used to prevent textures in certain GPU slots from being replaced by an insert.
* @property _slotBlackList
* @protected
* @type {Array}
*/
this._slotBlacklist = [];
/**
* Used to ensure every canvas used as a texture source has a unique ID.
* @property _lastTrackedCanvas
* @protected
* @type {Number}
* @default 0
*/
this._lastTrackedCanvas = -1;
/**
* Used to counter-position the object being cached so it aligns with the cache surface. Additionally ensures
* that all rendering starts with a top level container.
* @property _cacheContainer
* @protected
* @type {Container}
* @default An instance of an EaselJS Container.
*/
this._cacheContainer = new createjs.Container();
// and begin
this._initializeWebGL();
// these settings require everything to be ready
if (options !== undefined) {
options.clearColor !== undefined && this.setClearColor(options.clearColor);
options.premultiply !== undefined && (createjs.deprecate(null, "options.premultiply")());
}
}
var p = createjs.extend(StageGL, createjs.Stage);
// static methods:
/**
* Calculate the UV co-ordinate based info for sprite frames. Instead of pixel count it uses a 0-1 space. Also includes
* the ability to get info back for a specific frame, or only calculate that one frame.
*
* //generate UV rects for all entries
* StageGL.buildUVRects( spriteSheetA );
* //generate all, fetch the first
* var firstFrame = StageGL.buildUVRects( spriteSheetB, 0 );
* //generate the rect for just a single frame for performance's sake
* var newFrame = StageGL.buildUVRects( dynamicSpriteSheet, newFrameIndex, true );
*
* NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
* @method buildUVRects
* @param {SpriteSheet} spritesheet The spritesheet to find the frames on
* @param {int} [target=-1] The index of the frame to return
* @param {Boolean} [onlyTarget=false] Whether "target" is the only frame that gets calculated
* @static
* @return {Object} the target frame if supplied and present or a generic frame {t, l, b, r}
*/
StageGL.buildUVRects = function (spritesheet, target, onlyTarget) {
if (!spritesheet || !spritesheet._frames) { return null; }
if (target === undefined) { target = -1; }
if (onlyTarget === undefined) { onlyTarget = false; }
var start = (target !== -1 && onlyTarget)?(target):(0);
var end = (target !== -1 && onlyTarget)?(target+1):(spritesheet._frames.length);
for (var i=start; i<end; i++) {
var f = spritesheet._frames[i];
if (f.uvRect || f.image.width <= 0 || f.image.height <= 0) { continue; }
var r = f.rect;
f.uvRect = {
t: 1 - (r.y / f.image.height),
l: r.x / f.image.width,
b: 1 - ((r.y + r.height) / f.image.height),
r: (r.x + r.width) / f.image.width
};
}
return spritesheet._frames[(target !== -1) ? target : 0].uvRect || {t:0, l:0, b:1, r:1};
};
/**
* Test a context to see if it has WebGL enabled on it.
* @method isWebGLActive
* @param {CanvasRenderingContext2D | WebGLRenderingContext} ctx The context to test
* @static
* @return {Boolean} Whether WebGL is enabled
*/
StageGL.isWebGLActive = function (ctx) {
return ctx &&
ctx instanceof WebGLRenderingContext &&
typeof WebGLRenderingContext !== 'undefined';
};
/**
* Utility used to convert the colour values the Context2D API accepts into WebGL color values.
* @param {String | Number} color
* @static
* @return {Object} Object with r, g, b, a in 0-1 values of the color.
*/
StageGL.colorToObj = function (color) {
var r, g, b, a;
if (typeof color === "string") {
if (color.indexOf("#") === 0) {
if (color.length === 4) {
color = "#" + color.charAt(1)+color.charAt(1) + color.charAt(2)+color.charAt(2) + color.charAt(3)+color.charAt(3)
}
r = Number("0x"+color.slice(1, 3))/255;
g = Number("0x"+color.slice(3, 5))/255;
b = Number("0x"+color.slice(5, 7))/255;
a = color.length > 7 ? Number("0x"+color.slice(7, 9))/255 : 1;
} else if (color.indexOf("rgba(") === 0) {
var output = color.slice(5, -1).split(",");
r = Number(output[0])/255;
g = Number(output[1])/255;
b = Number(output[2])/255;
a = Number(output[3]);
}
} else { // >>> is an unsigned shift which is what we want as 0x80000000 and up are negative values
r = ((color & 0xFF000000) >>> 24)/255;
g = ((color & 0x00FF0000) >>> 16)/255;
b = ((color & 0x0000FF00) >>> 8)/255;
a = (color & 0x000000FF)/255;
}
return {
r: Math.min(Math.max(0, r), 1),
g: Math.min(Math.max(0, g), 1),
b: Math.min(Math.max(0, b), 1),
a: Math.min(Math.max(0, a), 1)
}
};
// static properties:
/**
* The number of properties defined per vertex (x, y, textureU, textureV, textureIndex, alpha)
* @property VERTEX_PROPERTY_COUNT
* @protected
* @static
* @final
* @type {Number}
* @default 6
* @readonly
*/
StageGL.VERTEX_PROPERTY_COUNT = 6;
/**
* The number of triangle indices it takes to form a Card. 3 per triangle, 2 triangles.
* @property INDICIES_PER_CARD
* @protected
* @static
* @final
* @type {Number}
* @default 6
* @readonly
*/
StageGL.INDICIES_PER_CARD = 6;
/**
* The default value for the maximum number of cards we want to process in a batch. See
* {{#crossLink "StageGL/WEBGL_MAX_INDEX_NUM:property"}}{{/crossLink}} for a hard limit.
* this value comes is designed to sneak under that limit.
* @property DEFAULT_MAX_BATCH_SIZE
* @static
* @final
* @type {Number}
* @default 10920
* @readonly
*/
StageGL.DEFAULT_MAX_BATCH_SIZE = 10920;
/**
* The default value for the minimum number of cards we want to process in a batch. Less
* max cards can mean better performance, but anything below this is probably not worth it.
* @property DEFAULT_MIN_BATCH_SIZE
* @static
* @final
* @type {Number}
* @default 170
* @readonly
*/
StageGL.DEFAULT_MIN_BATCH_SIZE = 170;
/**
* The maximum size WebGL allows for element index numbers. Uses a 16 bit unsigned integer. It takes 6 indices to
* make a unique card.
* @property WEBGL_MAX_INDEX_NUM
* @static
* @final
* @type {Number}
* @default 65536
* @readonly
*/
StageGL.WEBGL_MAX_INDEX_NUM = Math.pow(2, 16);
/**
* Default UV rect for dealing with full coverage from an image source.
* @property UV_RECT
* @protected
* @static
* @final
* @type {Object}
* @default {t:0, l:0, b:1, r:1}
* @readonly
*/
StageGL.UV_RECT = {t:1, l:0, b:0, r:1};
try {
/**
* Vertex positions for a card that covers the entire render. Used with render targets primarily.
* @property COVER_VERT
* @static
* @final
* @type {Float32Array}
* @readonly
*/
StageGL.COVER_VERT = new Float32Array([
-1, 1, //TL
1, 1, //TR
-1, -1, //BL
1, 1, //TR
1, -1, //BR
-1, -1 //BL
]);
/**
* UV for {{#crossLink "StageGL/COVER_VERT:property"}}{{/crossLink}}.
* @property COVER_UV
* @static
* @final
* @type {Float32Array}
* @readonly
*/
StageGL.COVER_UV = new Float32Array([
0, 1, //TL
1, 1, //TR
0, 0, //BL
1, 1, //TR
1, 0, //BR
0, 0 //BL
]);
} catch(e) { /* Breaking in older browsers, but those browsers wont run StageGL so no recovery or warning needed */ }
/**
* Portion of the shader that contains the "varying" properties required in both vertex and fragment shaders. The
* regular shader is designed to render all expected objects. Shader code may contain templates that are replaced
* pre-compile.
* @property REGULAR_VARYING_HEADER
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.REGULAR_VARYING_HEADER = (
"precision highp float;" +
"varying vec2 vTextureCoord;" +
"varying lowp float indexPicker;" +
"varying lowp float alphaValue;"
);
/**
* Actual full header for the vertex shader. Includes the varying header. The regular shader is designed to render
* all expected objects. Shader code may contain templates that are replaced pre-compile.
* @property REGULAR_VERTEX_HEADER
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.REGULAR_VERTEX_HEADER = (
StageGL.REGULAR_VARYING_HEADER +
"attribute vec2 vertexPosition;" +
"attribute vec2 uvPosition;" +
"attribute lowp float textureIndex;" +
"attribute lowp float objectAlpha;" +
"uniform mat4 pMatrix;"
);
/**
* Actual full header for the fragment shader. Includes the varying header. The regular shader is designed to render
* all expected objects. Shader code may contain templates that are replaced pre-compile.
* @property REGULAR_FRAGMENT_HEADER
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.REGULAR_FRAGMENT_HEADER = (
StageGL.REGULAR_VARYING_HEADER +
"uniform sampler2D uSampler[{{count}}];"
);
/**
* Body of the vertex shader. The regular shader is designed to render all expected objects. Shader code may contain
* templates that are replaced pre-compile.
* @property REGULAR_VERTEX_BODY
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.REGULAR_VERTEX_BODY = (
"void main(void) {" +
"gl_Position = pMatrix * vec4(vertexPosition.x, vertexPosition.y, 0.0, 1.0);" +
"alphaValue = objectAlpha;" +
"indexPicker = textureIndex;" +
"vTextureCoord = uvPosition;" +
"}"
);
/**
* Body of the fragment shader. The regular shader is designed to render all expected objects. Shader code may
* contain templates that are replaced pre-compile.
* @property REGULAR_FRAGMENT_BODY
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.REGULAR_FRAGMENT_BODY = (
"void main(void) {" +
"vec4 color = vec4(1.0, 0.0, 0.0, 1.0);" +
"if (indexPicker <= 0.5) {" +
"color = texture2D(uSampler[0], vTextureCoord);" +
"{{alternates}}" +
"}" +
"gl_FragColor = vec4(color.rgb * alphaValue, color.a * alphaValue);" +
"}"
);
/**
* Portion of the shader that contains the "varying" properties required in both vertex and fragment shaders. The
* cover shader is designed to be a simple vertex/uv only texture render that covers the render surface. Shader
* code may contain templates that are replaced pre-compile.
* @property COVER_VARYING_HEADER
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.COVER_VARYING_HEADER = (
"precision highp float;" + //this is usually essential for filter math
"varying vec2 vTextureCoord;"
);
/**
* Actual full header for the vertex shader. Includes the varying header. The cover shader is designed to be a
* simple vertex/uv only texture render that covers the render surface. Shader code may contain templates that are
* replaced pre-compile.
* @property COVER_VERTEX_HEADER
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.COVER_VERTEX_HEADER = (
StageGL.COVER_VARYING_HEADER +
"attribute vec2 vertexPosition;" +
"attribute vec2 uvPosition;"
);
/**
* Actual full header for the fragment shader. Includes the varying header. The cover shader is designed to be a
* simple vertex/uv only texture render that covers the render surface. Shader code may contain templates that are
* replaced pre-compile.
* @property COVER_FRAGMENT_HEADER
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.COVER_FRAGMENT_HEADER = (
StageGL.COVER_VARYING_HEADER +
"uniform sampler2D uSampler;"
);
/**
* Body of the vertex shader. The cover shader is designed to be a simple vertex/uv only texture render that covers
* the render surface. Shader code may contain templates that are replaced pre-compile.
* @property COVER_VERTEX_BODY
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.COVER_VERTEX_BODY = (
"void main(void) {" +
"gl_Position = vec4(vertexPosition.x, vertexPosition.y, 0.0, 1.0);" +
"vTextureCoord = uvPosition;" +
"}"
);
/**
* Body of the fragment shader. The cover shader is designed to be a simple vertex/uv only texture render that
* covers the render surface. Shader code may contain templates that are replaced pre-compile.
* @property COVER_FRAGMENT_BODY
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.COVER_FRAGMENT_BODY = (
"void main(void) {" +
"gl_FragColor = texture2D(uSampler, vTextureCoord);" +
"}"
);
/**
* The starting template of a cover fragment shader with simple blending equations
* @property BLEND_FRAGMENT_SIMPLE
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.BLEND_FRAGMENT_SIMPLE = (
"uniform sampler2D uMixSampler;"+
"void main(void) {" +
"vec4 src = texture2D(uMixSampler, vTextureCoord);" +
"vec4 dst = texture2D(uSampler, vTextureCoord);"
// note this is an open bracket on main!
);
/**
* The starting template of a cover fragment shader which has complex blending equations
* @property BLEND_FRAGMENT_COMPLEX
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.BLEND_FRAGMENT_COMPLEX = (
StageGL.BLEND_FRAGMENT_SIMPLE +
"vec3 srcClr = min(src.rgb/src.a, 1.0);" +
"vec3 dstClr = min(dst.rgb/dst.a, 1.0);" +
"float totalAlpha = min(1.0 - (1.0-dst.a) * (1.0-src.a), 1.0);" +
"float srcFactor = min(max(src.a - dst.a, 0.0) / totalAlpha, 1.0);" +
"float dstFactor = min(max(dst.a - src.a, 0.0) / totalAlpha, 1.0);" +
"float mixFactor = max(max(1.0 - srcFactor, 0.0) - dstFactor, 0.0);" +
"gl_FragColor = vec4(" +
"(" +
"srcFactor * srcClr +" +
"dstFactor * dstClr +" +
"mixFactor * vec3("
// this should be closed with the cap!
);
/**
* The closing portion of a template for a cover fragment shader which has complex blending equations
* @property BLEND_FRAGMENT_COMPLEX_CAP
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.BLEND_FRAGMENT_COMPLEX_CAP = (
")" +
") * totalAlpha, totalAlpha" +
");" +
"}"
);
/**
* A shader utility function, used to calculate the "overlay" blend of two elements
* @property BLEND_FRAGMENT_OVERLAY_UTIL
* @protected
* @static
* @final
* @type {String}
* @readonly
*/
StageGL.BLEND_FRAGMENT_OVERLAY_UTIL = (
"float overlay(float a, float b) {" +
"if(a < 0.5) { return 2.0 * a * b; }" +
"return 1.0 - 2.0 * (1.0-a) * (1.0-b);" +
"}"
);
/**
* A collection of shader utility functions, used to calculate HSL math. Taken from W3C spec
* https://www.w3.org/TR/compositing-1/#blendingnonseparable
* @property BLEND_FRAGMENT_HSL_UTIL