/
textures.js
1625 lines (1536 loc) · 72.4 KB
/
textures.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
/*
* Copyright 2015, Gregg Tavares.
* 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.
* * Neither the name of Gregg Tavares. nor the names of his
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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
* OWNER 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.
*/
define([
'./typedarrays',
'./utils',
], function(
typedArrays,
utils) {
"use strict";
/**
* Low level texture related functions
*
* You should generally not need to use these functions. They are provided
* for those cases where you're doing something out of the ordinary
* and you need lower level access.
*
* For backward compatibily they are available at both `twgl.textures` and `twgl`
* itself
*
* See {@link module:twgl} for core functions
*
* @module twgl/textures
*/
// make sure we don't see a global gl
var gl = undefined; // eslint-disable-line
var defaults = {
textureColor: new Uint8Array([128, 192, 255, 255]),
textureOptions: {},
crossOrigin: undefined,
};
var isArrayBuffer = typedArrays.isArrayBuffer;
// Should we make this on demand?
var ctx = document.createElement("canvas").getContext("2d");
/* PixelFormat */
var ALPHA = 0x1906;
var RGB = 0x1907;
var RGBA = 0x1908;
var LUMINANCE = 0x1909;
var LUMINANCE_ALPHA = 0x190A;
var DEPTH_COMPONENT = 0x1902;
var DEPTH_STENCIL = 0x84F9;
/* TextureWrapMode */
var REPEAT = 0x2901; // eslint-disable-line
var MIRRORED_REPEAT = 0x8370; // eslint-disable-line
/* TextureMagFilter */
var NEAREST = 0x2600; // eslint-disable-line
/* TextureMinFilter */
var NEAREST_MIPMAP_NEAREST = 0x2700; // eslint-disable-line
var LINEAR_MIPMAP_NEAREST = 0x2701; // eslint-disable-line
var NEAREST_MIPMAP_LINEAR = 0x2702; // eslint-disable-line
var LINEAR_MIPMAP_LINEAR = 0x2703; // eslint-disable-line
const R8 = 0x8229;
const R8_SNORM = 0x8F94;
const R16F = 0x822D;
const R32F = 0x822E;
const R8UI = 0x8232;
const R8I = 0x8231;
const RG16UI = 0x823A;
const RG16I = 0x8239;
const RG32UI = 0x823C;
const RG32I = 0x823B;
const RG8 = 0x822B;
const RG8_SNORM = 0x8F95;
const RG16F = 0x822F;
const RG32F = 0x8230;
const RG8UI = 0x8238;
const RG8I = 0x8237;
const R16UI = 0x8234;
const R16I = 0x8233;
const R32UI = 0x8236;
const R32I = 0x8235;
const RGB8 = 0x8051;
const SRGB8 = 0x8C41;
const RGB565 = 0x8D62;
const RGB8_SNORM = 0x8F96;
const R11F_G11F_B10F = 0x8C3A;
const RGB9_E5 = 0x8C3D;
const RGB16F = 0x881B;
const RGB32F = 0x8815;
const RGB8UI = 0x8D7D;
const RGB8I = 0x8D8F;
const RGB16UI = 0x8D77;
const RGB16I = 0x8D89;
const RGB32UI = 0x8D71;
const RGB32I = 0x8D83;
const RGBA8 = 0x8058;
const SRGB8_ALPHA8 = 0x8C43;
const RGBA8_SNORM = 0x8F97;
const RGB5_A1 = 0x8057;
const RGBA4 = 0x8056;
const RGB10_A2 = 0x8059;
const RGBA16F = 0x881A;
const RGBA32F = 0x8814;
const RGBA8UI = 0x8D7C;
const RGBA8I = 0x8D8E;
const RGB10_A2UI = 0x906F;
const RGBA16UI = 0x8D76;
const RGBA16I = 0x8D88;
const RGBA32I = 0x8D82;
const RGBA32UI = 0x8D70;
const DEPTH_COMPONENT16 = 0x81A5;
const DEPTH_COMPONENT24 = 0x81A6;
const DEPTH_COMPONENT32F = 0x8CAC;
const DEPTH32F_STENCIL8 = 0x8CAD;
const DEPTH24_STENCIL8 = 0x88F0;
/* DataType */
const BYTE = 0x1400;
const UNSIGNED_BYTE = 0x1401;
const SHORT = 0x1402;
const UNSIGNED_SHORT = 0x1403;
const INT = 0x1404;
const UNSIGNED_INT = 0x1405;
const FLOAT = 0x1406;
const UNSIGNED_SHORT_4_4_4_4 = 0x8033;
const UNSIGNED_SHORT_5_5_5_1 = 0x8034;
const UNSIGNED_SHORT_5_6_5 = 0x8363;
const HALF_FLOAT = 0x140B;
const UNSIGNED_INT_2_10_10_10_REV = 0x8368;
const UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B;
const UNSIGNED_INT_5_9_9_9_REV = 0x8C3E;
const FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD;
const UNSIGNED_INT_24_8 = 0x84FA;
const RG = 0x8227;
const RG_INTEGER = 0x8228;
const RED = 0x1903;
const RED_INTEGER = 0x8D94;
const RGB_INTEGER = 0x8D98;
const RGBA_INTEGER = 0x8D99;
const formatInfo = {};
{
// NOTE: this is named `numColorComponents` vs `numComponents` so we can let Uglify mangle
// the name.
const f = formatInfo;
f[ALPHA] = { numColorComponents: 1, };
f[LUMINANCE] = { numColorComponents: 1, };
f[LUMINANCE_ALPHA] = { numColorComponents: 2, };
f[RGB] = { numColorComponents: 3, };
f[RGBA] = { numColorComponents: 4, };
f[RED] = { numColorComponents: 1, };
f[RED_INTEGER] = { numColorComponents: 1, };
f[RG] = { numColorComponents: 2, };
f[RG_INTEGER] = { numColorComponents: 2, };
f[RGB] = { numColorComponents: 3, };
f[RGB_INTEGER] = { numColorComponents: 3, };
f[RGBA] = { numColorComponents: 4, };
f[RGBA_INTEGER] = { numColorComponents: 4, };
f[DEPTH_COMPONENT] = { numColorComponents: 1, };
f[DEPTH_STENCIL] = { numColorComponents: 2, };
}
const textureInternalFormatInfo = {};
{
// NOTE: these properties need unique names so we can let Uglify mangle the name.
const t = textureInternalFormatInfo;
// unsized formats
t[ALPHA] = { textureFormat: ALPHA, colorRenderable: true, textureFilterable: true, bytesPerElement: [1, 2, 4], type: [UNSIGNED_BYTE, HALF_FLOAT, FLOAT], };
t[LUMINANCE] = { textureFormat: LUMINANCE, colorRenderable: true, textureFilterable: true, bytesPerElement: [1, 2, 4], type: [UNSIGNED_BYTE, HALF_FLOAT, FLOAT], };
t[LUMINANCE_ALPHA] = { textureFormat: LUMINANCE_ALPHA, colorRenderable: true, textureFilterable: true, bytesPerElement: [2, 4, 8], type: [UNSIGNED_BYTE, HALF_FLOAT, FLOAT], };
t[RGB] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3, 6, 12, 2], type: [UNSIGNED_BYTE, HALF_FLOAT, FLOAT, UNSIGNED_SHORT_5_6_5], };
t[RGBA] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 8, 16, 2, 2], type: [UNSIGNED_BYTE, HALF_FLOAT, FLOAT, UNSIGNED_SHORT_4_4_4_4, UNSIGNED_SHORT_5_5_5_1], };
// sized formats
t[R8] = { textureFormat: RED, colorRenderable: true, textureFilterable: true, bytesPerElement: 1, type: UNSIGNED_BYTE, };
t[R8_SNORM] = { textureFormat: RED, colorRenderable: false, textureFilterable: true, bytesPerElement: 1, type: BYTE, };
t[R16F] = { textureFormat: RED, colorRenderable: false, textureFilterable: true, bytesPerElement: [4, 2], type: [FLOAT, HALF_FLOAT], };
t[R32F] = { textureFormat: RED, colorRenderable: false, textureFilterable: false, bytesPerElement: 4, type: FLOAT, };
t[R8UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 1, type: UNSIGNED_BYTE, };
t[R8I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 1, type: BYTE, };
t[R16UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 2, type: UNSIGNED_SHORT, };
t[R16I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 2, type: SHORT, };
t[R32UI] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_INT, };
t[R32I] = { textureFormat: RED_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: INT, };
t[RG8] = { textureFormat: RG, colorRenderable: true, textureFilterable: true, bytesPerElement: 2, type: UNSIGNED_BYTE, };
t[RG8_SNORM] = { textureFormat: RG, colorRenderable: false, textureFilterable: true, bytesPerElement: 2, type: BYTE, };
t[RG16F] = { textureFormat: RG, colorRenderable: false, textureFilterable: true, bytesPerElement: [8, 4], type: [FLOAT, HALF_FLOAT], };
t[RG32F] = { textureFormat: RG, colorRenderable: false, textureFilterable: false, bytesPerElement: 8, type: FLOAT, };
t[RG8UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 2, type: UNSIGNED_BYTE, };
t[RG8I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 2, type: BYTE, };
t[RG16UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_SHORT, };
t[RG16I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: SHORT, };
t[RG32UI] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 8, type: UNSIGNED_INT, };
t[RG32I] = { textureFormat: RG_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 8, type: INT, };
t[RGB8] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: 3, type: UNSIGNED_BYTE, };
t[SRGB8] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: 3, type: UNSIGNED_BYTE, };
t[RGB565] = { textureFormat: RGB, colorRenderable: true, textureFilterable: true, bytesPerElement: [3, 2], type: [UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5], };
t[RGB8_SNORM] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: 3, type: BYTE, };
t[R11F_G11F_B10F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6, 4], type: [FLOAT, HALF_FLOAT, UNSIGNED_INT_10F_11F_11F_REV], };
t[RGB9_E5] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6, 4], type: [FLOAT, HALF_FLOAT, UNSIGNED_INT_5_9_9_9_REV], };
t[RGB16F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: true, bytesPerElement: [12, 6], type: [FLOAT, HALF_FLOAT], };
t[RGB32F] = { textureFormat: RGB, colorRenderable: false, textureFilterable: false, bytesPerElement: 12, type: FLOAT, };
t[RGB8UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 3, type: UNSIGNED_BYTE, };
t[RGB8I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 3, type: BYTE, };
t[RGB16UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 6, type: UNSIGNED_SHORT, };
t[RGB16I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 6, type: SHORT, };
t[RGB32UI] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 12, type: UNSIGNED_INT, };
t[RGB32I] = { textureFormat: RGB_INTEGER, colorRenderable: false, textureFilterable: false, bytesPerElement: 12, type: INT, };
t[RGBA8] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: 4, type: UNSIGNED_BYTE, };
t[SRGB8_ALPHA8] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: 4, type: UNSIGNED_BYTE, };
t[RGBA8_SNORM] = { textureFormat: RGBA, colorRenderable: false, textureFilterable: true, bytesPerElement: 4, type: BYTE, };
t[RGB5_A1] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 2, 4], type: [UNSIGNED_BYTE, UNSIGNED_SHORT_5_5_5_1, UNSIGNED_INT_2_10_10_10_REV], };
t[RGBA4] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: [4, 2], type: [UNSIGNED_BYTE, UNSIGNED_SHORT_4_4_4_4], };
t[RGB10_A2] = { textureFormat: RGBA, colorRenderable: true, textureFilterable: true, bytesPerElement: 4, type: UNSIGNED_INT_2_10_10_10_REV, };
t[RGBA16F] = { textureFormat: RGBA, colorRenderable: false, textureFilterable: true, bytesPerElement: [16, 8], type: [FLOAT, HALF_FLOAT], };
t[RGBA32F] = { textureFormat: RGBA, colorRenderable: false, textureFilterable: false, bytesPerElement: 16, type: FLOAT, };
t[RGBA8UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_BYTE, };
t[RGBA8I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: BYTE, };
t[RGB10_A2UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_INT_2_10_10_10_REV, };
t[RGBA16UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 8, type: UNSIGNED_SHORT, };
t[RGBA16I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 8, type: SHORT, };
t[RGBA32I] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 16, type: INT, };
t[RGBA32UI] = { textureFormat: RGBA_INTEGER, colorRenderable: true, textureFilterable: false, bytesPerElement: 16, type: UNSIGNED_INT, };
// Sized Internal
t[DEPTH_COMPONENT16] = { textureFormat: DEPTH_COMPONENT, colorRenderable: true, textureFilterable: false, bytesPerElement: [2, 4], type: [UNSIGNED_SHORT, UNSIGNED_INT], };
t[DEPTH_COMPONENT24] = { textureFormat: DEPTH_COMPONENT, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_INT, };
t[DEPTH_COMPONENT32F] = { textureFormat: DEPTH_COMPONENT, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: FLOAT, };
t[DEPTH24_STENCIL8] = { textureFormat: DEPTH_STENCIL, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: UNSIGNED_INT_24_8, };
t[DEPTH32F_STENCIL8] = { textureFormat: DEPTH_STENCIL, colorRenderable: true, textureFilterable: false, bytesPerElement: 4, type: FLOAT_32_UNSIGNED_INT_24_8_REV, };
Object.keys(t).forEach(function(internalFormat) {
const info = t[internalFormat];
info.bytesPerElementMap = {};
if (Array.isArray(info.bytesPerElement)) {
info.bytesPerElement.forEach(function(bytesPerElement, ndx) {
const type = info.type[ndx];
info.bytesPerElementMap[type] = bytesPerElement;
});
} else {
const type = info.type;
info.bytesPerElementMap[type] = info.bytesPerElement;
}
});
}
/**
* Gets the number of bytes per element for a given internalFormat / type
* @param {number} internalFormat The internalFormat parameter from texImage2D etc..
* @param {number} type The type parameter for texImage2D etc..
* @return {number} the number of bytes per element for the given internalFormat, type combo
* @memberOf module:twgl/textures
*/
function getBytesPerElementForInternalFormat(internalFormat, type) {
const info = textureInternalFormatInfo[internalFormat];
if (!info) {
throw "unknown internal format";
}
const bytesPerElement = info.bytesPerElementMap[type];
if (bytesPerElement === undefined) {
throw "unknown internal format";
}
return bytesPerElement;
}
/**
* Gets the format for a given internalFormat
*
* @param {number} internalFormat The internal format
* @return {{format:number, type:number}} the corresponding format and type
*/
function getFormatAndTypeForInternalFormat(internalFormat) {
const info = textureInternalFormatInfo[internalFormat];
if (!info) {
throw "unknown internal format";
}
return {
format: info.textureFormat,
type: Array.isArray(info.type) ? info.type[0] : info.type,
};
}
/**
* Returns true if value is power of 2
* @param {number} value number to check.
* @return true if value is power of 2
*/
function isPowerOf2(value) {
return (value & (value - 1)) === 0;
}
/**
* Gets whether or not we can generate mips for the given format
* @param {number} internalFormat The internalFormat parameter from texImage2D etc..
* @param {number} type The type parameter for texImage2D etc..
* @return {boolean} true if we can generate mips
*/
function canGenerateMipmap(gl, width, height, internalFormat /*, type */) {
if (!utils.isWebGL2(gl)) {
return isPowerOf2(width) && isPowerOf2(height);
}
const info = textureInternalFormatInfo[internalFormat];
if (!info) {
throw "unknown internal format";
}
return info.colorRenderable && info.textureFilterable;
}
/**
* Gets whether or not we can generate mips for the given format
* @param {number} internalFormat The internalFormat parameter from texImage2D etc..
* @param {number} type The type parameter for texImage2D etc..
* @return {boolean} true if we can generate mips
*/
function canFilter(internalFormat /*, type */) {
const info = textureInternalFormatInfo[internalFormat];
if (!info) {
throw "unknown internal format";
}
return info.textureFilterable;
}
/**
* Gets the number of compontents for a given image format.
* @param {number} format the format.
* @return {number} the number of components for the format.
* @memberOf module:twgl/textures
*/
function getNumComponentsForFormat(format) {
const info = formatInfo[format];
if (!info) {
throw "unknown format: " + format;
}
return info.numColorComponents;
}
/**
* Gets the texture type for a given array type.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @return {number} the gl texture type
*/
function getTextureTypeForArrayType(gl, src, defaultType) {
if (isArrayBuffer(src)) {
return typedArrays.getGLTypeForTypedArray(src);
}
return defaultType || gl.UNSIGNED_BYTE;
}
function guessDimensions(gl, target, width, height, numElements) {
if (numElements % 1 !== 0) {
throw "can't guess dimensions";
}
if (!width && !height) {
var size = Math.sqrt(numElements / (target === gl.TEXTURE_CUBE_MAP ? 6 : 1));
if (size % 1 === 0) {
width = size;
height = size;
} else {
width = numElements;
height = 1;
}
} else if (!height) {
height = numElements / width;
if (height % 1) {
throw "can't guess dimensions";
}
} else if (!width) {
width = numElements / height;
if (width % 1) {
throw "can't guess dimensions";
}
}
return {
width: width,
height: height,
};
}
/**
* Sets the default texture color.
*
* The default texture color is used when loading textures from
* urls. Because the URL will be loaded async we'd like to be
* able to use the texture immediately. By putting a 1x1 pixel
* color in the texture we can start using the texture before
* the URL has loaded.
*
* @param {number[]} color Array of 4 values in the range 0 to 1
* @deprecated see {@link module:twgl.setDefaults}
* @memberOf module:twgl/textures
*/
function setDefaultTextureColor(color) {
defaults.textureColor = new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);
}
function setDefaults(newDefaults) {
utils.copyExistingProperties(newDefaults, defaults);
if (newDefaults.textureColor) {
setDefaultTextureColor(newDefaults.textureColor);
}
}
/**
* Gets a string for gl enum
*
* Note: Several enums are the same. Without more
* context (which function) it's impossible to always
* give the correct enum.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {number} value the value of the enum you want to look up.
*/
var glEnumToString = (function() {
var enums;
function init(gl) {
if (!enums) {
enums = {};
for (var key in gl) {
if (typeof gl[key] === 'number') {
enums[gl[key]] = key;
}
}
}
}
return function glEnumToString(gl, value) {
init(gl);
return enums[value] || ("0x" + value.toString(16));
};
}());
/**
* A function to generate the source for a texture.
* @callback TextureFunc
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {module:twgl.TextureOptions} options the texture options
* @return {*} Returns any of the things documentented for `src` for {@link module:twgl.TextureOptions}.
* @memberOf module:twgl
*/
/**
* Texture options passed to most texture functions. Each function will use whatever options
* are appropriate for its needs. This lets you pass the same options to all functions.
*
* @typedef {Object} TextureOptions
* @property {number} [target] the type of texture `gl.TEXTURE_2D` or `gl.TEXTURE_CUBE_MAP`. Defaults to `gl.TEXTURE_2D`.
* @property {number} [width] the width of the texture. Only used if src is an array or typed array or null.
* @property {number} [height] the height of a texture. Only used if src is an array or typed array or null.
* @property {number} [depth] the depth of a texture. Only used if src is an array or type array or null and target is `TEXTURE_3D` .
* @property {number} [min] the min filter setting (eg. `gl.LINEAR`). Defaults to `gl.NEAREST_MIPMAP_LINEAR`
* or if texture is not a power of 2 on both dimensions then defaults to `gl.LINEAR`.
* @property {number} [mag] the mag filter setting (eg. `gl.LINEAR`). Defaults to `gl.LINEAR`
* @property {number} [minMag] both the min and mag filter settings.
* @property {number} [internalFormat] internal format for texture. Defaults to `gl.RGBA`
* @property {number} [format] format for texture. Defaults to `gl.RGBA`.
* @property {number} [type] type for texture. Defaults to `gl.UNSIGNED_BYTE` unless `src` is ArrayBuffer. If `src`
* is ArrayBuffer defaults to type that matches ArrayBuffer type.
* @property {number} [wrap] Texture wrapping for both S and T (and R if TEXTURE_3D or WebGLSampler). Defaults to `gl.REPEAT` for 2D unless src is WebGL1 and src not npot and `gl.CLAMP_TO_EDGE` for cube
* @property {number} [wrapS] Texture wrapping for S. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.
* @property {number} [wrapT] Texture wrapping for T. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.
* @property {number} [wrapR] Texture wrapping for R. Defaults to `gl.REPEAT` and `gl.CLAMP_TO_EDGE` for cube. If set takes precedence over `wrap`.
* @property {number} [minLod] TEXTURE_MIN_LOD setting
* @property {number} [maxLod] TEXTURE_MAX_LOD setting
* @property {number} [baseLevel] TEXTURE_BASE_LEVEL setting
* @property {number} [maxLevel] TEXTURE_MAX_LEVEL setting
* @property {number} [unpackAlignment] The `gl.UNPACK_ALIGNMENT` used when uploading an array. Defaults to 1.
* @property {number} [premultiplyAlpha] Whether or not to premultiply alpha. Defaults to whatever the current setting is.
* This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override
* the current setting for specific textures.
* @property {number} [flipY] Whether or not to flip the texture vertically on upload. Defaults to whatever the current setting is.
* This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override
* the current setting for specific textures.
* @property {number} [colorspaceConversion] Whether or not to let the browser do colorspace conversion of the texture on upload. Defaults to whatever the current setting is.
* This lets you set it once before calling `twgl.createTexture` or `twgl.createTextures` and only override
* the current setting for specific textures.
* @property {(number[]|ArrayBuffer)} color color used as temporary 1x1 pixel color for textures loaded async when src is a string.
* If it's a JavaScript array assumes color is 0 to 1 like most GL colors as in `[1, 0, 0, 1] = red=1, green=0, blue=0, alpha=0`.
* Defaults to `[0.5, 0.75, 1, 1]`. See {@link module:twgl.setDefaultTextureColor}. If `false` texture is set. Can be used to re-load a texture
* @property {boolean} [auto] If not `false` then texture working filtering is set automatically for non-power of 2 images and
* mips are generated for power of 2 images.
* @property {number[]} [cubeFaceOrder] The order that cube faces are pulled out of an img or set of images. The default is
*
* [gl.TEXTURE_CUBE_MAP_POSITIVE_X,
* gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
* gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
* gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
* gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
* gl.TEXTURE_CUBE_MAP_NEGATIVE_Z]
*
* @property {(number[]|ArrayBuffer|HTMLCanvasElement|HTMLImageElement|HTMLVideoElement|string|string[]|module:twgl.TextureFunc)} [src] source for texture
*
* If `string` then it's assumed to be a URL to an image. The image will be downloaded async. A usable
* 1x1 pixel texture will be returned immediatley. The texture will be updated once the image has downloaded.
* If `target` is `gl.TEXTURE_CUBE_MAP` will attempt to divide image into 6 square pieces. 1x6, 6x1, 3x2, 2x3.
* The pieces will be uploaded in `cubeFaceOrder`
*
* If `string[]` then it must have 6 entries, one for each face of a cube map. Target must be `gl.TEXTURE_CUBE_MAP`.
*
* If `HTMLElement` then it wil be used immediately to create the contents of the texture. Examples `HTMLImageElement`,
* `HTMLCanvasElement`, `HTMLVideoElement`.
*
* If `number[]` or `ArrayBuffer` it's assumed to be data for a texture. If `width` or `height` is
* not specified it is guessed as follows. First the number of elements is computed by `src.length / numComponets`
* where `numComponents` is derived from `format`. If `target` is `gl.TEXTURE_CUBE_MAP` then `numElements` is divided
* by 6. Then
*
* * If neither `width` nor `height` are specified and `sqrt(numElements)` is an integer then width and height
* are set to `sqrt(numElements)`. Otherwise `width = numElements` and `height = 1`.
*
* * If only one of `width` or `height` is specified then the other equals `numElements / specifiedDimension`.
*
* If `number[]` will be converted to `type`.
*
* If `src` is a function it will be called with a `WebGLRenderingContext` and these options.
* Whatever it returns is subject to these rules. So it can return a string url, an `HTMLElement`
* an array etc...
*
* If `src` is undefined then an empty texture will be created of size `width` by `height`.
*
* @property {string} [crossOrigin] What to set the crossOrigin property of images when they are downloaded.
* default: undefined. Also see {@link module:twgl.setDefaults}.
*
* @memberOf module:twgl
*/
// NOTE: While querying GL is considered slow it's not remotely as slow
// as uploading a texture. On top of that you're unlikely to call this in
// a perf critical loop. Even if upload a texture every frame that's unlikely
// to be more than 1 or 2 textures a frame. In other words, the benefits of
// making the API easy to use outweigh any supposed perf benefits
var lastPackState = {};
/**
* Saves any packing state that will be set based on the options.
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
*/
function savePackState(gl, options) {
if (options.colorspaceConversion !== undefined) {
lastPackState.colorspaceConversion = gl.getParameter(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL);
gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, options.colorspaceConversion);
}
if (options.premultiplyAlpha !== undefined) {
lastPackState.premultiplyAlpha = gl.getParameter(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, options.premultiplyAlpha);
}
if (options.flipY !== undefined) {
lastPackState.flipY = gl.getParameter(gl.UNPACK_FLIP_Y_WEBGL);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, options.flipY);
}
}
/**
* Restores any packing state that was set based on the options.
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
*/
function restorePackState(gl, options) {
if (options.colorspaceConversion !== undefined) {
gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, lastPackState.colorspaceConversion);
}
if (options.premultiplyAlpha !== undefined) {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, lastPackState.premultiplyAlpha);
}
if (options.flipY !== undefined) {
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, lastPackState.flipY);
}
}
/**
* Sets the parameters of a texture or sampler
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {number|WebGLSampler} target texture target or sampler
* @param {function()} parameteriFn texParamteri or samplerParameteri fn
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
*/
function setTextureSamplerParameters(gl, target, parameteriFn, options) {
if (options.minMag) {
parameteriFn.call(gl, target, gl.TEXTURE_MIN_FILTER, options.minMag);
parameteriFn.call(gl, target, gl.TEXTURE_MAG_FILTER, options.minMag);
}
if (options.min) {
parameteriFn.call(gl, target, gl.TEXTURE_MIN_FILTER, options.min);
}
if (options.mag) {
parameteriFn.call(gl, target, gl.TEXTURE_MAG_FILTER, options.mag);
}
if (options.wrap) {
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_S, options.wrap);
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_T, options.wrap);
if (target === gl.TEXTURE_3D || target instanceof WebGLSampler) {
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_R, options.wrap);
}
}
if (options.wrapR) {
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_R, options.wrapR);
}
if (options.wrapS) {
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_S, options.wrapS);
}
if (options.wrapT) {
parameteriFn.call(gl, target, gl.TEXTURE_WRAP_T, options.wrapT);
}
if (options.minLod) {
parameteriFn.call(gl, target, gl.TEXTURE_MIN_LOD, options.minLod);
}
if (options.maxLod) {
parameteriFn.call(gl, target, gl.TEXTURE_MAX_LOD, options.maxLod);
}
if (options.baseLevel) {
parameteriFn.call(gl, target, gl.TEXTURE_BASE_LEVEL, options.baseLevel);
}
if (options.maxLevel) {
parameteriFn.call(gl, target, gl.TEXTURE_MAX_LEVEL, options.maxLevel);
}
}
/**
* Sets the texture parameters of a texture.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @memberOf module:twgl/textures
*/
function setTextureParameters(gl, tex, options) {
var target = options.target || gl.TEXTURE_2D;
gl.bindTexture(target, tex);
setTextureSamplerParameters(gl, target, gl.texParameteri, options);
}
/**
* Sets the sampler parameters of a sampler.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLSampler} sampler the WebGLSampler to set parameters for
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @memberOf module:twgl/textures
*/
function setSamplerParameters(gl, sampler, options) {
setTextureSamplerParameters(gl, sampler, gl.samplerParameteri, options);
}
/**
* Creates a new sampler object and sets parameters.
*
* Example:
*
* const sampler = twgl.createSampler(gl, {
* minMag: gl.NEAREST, // sets both TEXTURE_MIN_FILTER and TEXTURE_MAG_FILTER
* wrap: gl.CLAMP_TO_NEAREST, // sets both TEXTURE_WRAP_S and TEXTURE_WRAP_T and TEXTURE_WRAP_R
* });
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {Object.<string,module:twgl.TextureOptions>} options A object of TextureOptions one per sampler.
* @return {Object.<string,WebGLSampler>} the created samplers by name
*/
function createSampler(gl, options) {
const sampler = gl.createSampler();
setSamplerParameters(gl, sampler, options);
return sampler;
}
/**
* Creates a multiple sampler objects and sets parameters on each.
*
* Example:
*
* const samplers = twgl.createSamplers(gl, {
* nearest: {
* minMag: gl.NEAREST,
* },
* nearestClampS: {
* minMag: gl.NEAREST,
* wrapS: gl.CLAMP_TO_NEAREST,
* },
* linear: {
* minMag: gl.LINEAR,
* },
* nearestClamp: {
* minMag: gl.NEAREST,
* wrap: gl.CLAMP_TO_EDGE,
* },
* linearClamp: {
* minMag: gl.LINEAR,
* wrap: gl.CLAMP_TO_EDGE,
* },
* linearClampT: {
* minMag: gl.LINEAR,
* wrapT: gl.CLAMP_TO_EDGE,
* },
* });
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set on the sampler
*/
function createSamplers(gl, samplerOptions) {
const samplers = {};
Object.keys(samplerOptions).forEach(function(name) {
samplers[name] = createSampler(gl, samplerOptions[name]);
});
return samplers;
}
/**
* Makes a 1x1 pixel
* If no color is passed in uses the default color which can be set by calling `setDefaultTextureColor`.
* @param {(number[]|ArrayBuffer)} [color] The color using 0-1 values
* @return {Uint8Array} Unit8Array with color.
*/
function make1Pixel(color) {
color = color || defaults.textureColor;
if (isArrayBuffer(color)) {
return color;
}
return new Uint8Array([color[0] * 255, color[1] * 255, color[2] * 255, color[3] * 255]);
}
/**
* Sets filtering or generates mips for texture based on width or height
* If width or height is not passed in uses `options.width` and//or `options.height`
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @param {number} [width] width of texture
* @param {number} [height] height of texture
* @param {number} [internalFormat] The internalFormat parameter from texImage2D etc..
* @param {number} [type] The type parameter for texImage2D etc..
* @memberOf module:twgl/textures
*/
function setTextureFilteringForSize(gl, tex, options, width, height, internalFormat, type) {
options = options || defaults.textureOptions;
internalFormat = internalFormat || gl.RGBA;
type = type || gl.UNSIGNED_BYTE;
var target = options.target || gl.TEXTURE_2D;
width = width || options.width;
height = height || options.height;
gl.bindTexture(target, tex);
if (canGenerateMipmap(gl, width, height, internalFormat, type)) {
gl.generateMipmap(target);
} else {
const filtering = canFilter(internalFormat, type) ? gl.LINEAR : gl.NEAREST;
gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filtering);
gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filtering);
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
}
/**
* Gets an array of cubemap face enums
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @return {number[]} cubemap face enums
*/
function getCubeFaceOrder(gl, options) {
options = options || {};
return options.cubeFaceOrder || [
gl.TEXTURE_CUBE_MAP_POSITIVE_X,
gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,
];
}
/**
* @typedef {Object} FaceInfo
* @property {number} face gl enum for texImage2D
* @property {number} ndx face index (0 - 5) into source data
* @ignore
*/
/**
* Gets an array of FaceInfos
* There's a bug in some NVidia drivers that will crash the driver if
* `gl.TEXTURE_CUBE_MAP_POSITIVE_X` is not uploaded first. So, we take
* the user's desired order from his faces to WebGL and make sure we
* do the faces in WebGL order
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.TextureOptions} options A TextureOptions object with whatever parameters you want set.
* @return {FaceInfo[]} cubemap face infos. Arguably the `face` property of each element is redundent but
* it's needed internally to sort the array of `ndx` properties by `face`.
*/
function getCubeFacesWithNdx(gl, options) {
var faces = getCubeFaceOrder(gl, options);
// work around bug in NVidia drivers. We have to upload the first face first else the driver crashes :(
var facesWithNdx = faces.map(function(face, ndx) {
return { face: face, ndx: ndx };
});
facesWithNdx.sort(function(a, b) {
return a.face - b.face;
});
return facesWithNdx;
}
/**
* Set a texture from the contents of an element. Will also set
* texture filtering or generate mips based on the dimensions of the element
* unless `options.auto === false`. If `target === gl.TEXTURE_CUBE_MAP` will
* attempt to slice image into 1x6, 2x3, 3x2, or 6x1 images, one for each face.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {HTMLElement} element a canvas, img, or video element.
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @memberOf module:twgl/textures
* @kind function
*/
function setTextureFromElement(gl, tex, element, options) {
options = options || defaults.textureOptions;
var target = options.target || gl.TEXTURE_2D;
var width = element.width;
var height = element.height;
var internalFormat = options.internalFormat || options.format || gl.RGBA;
var formatType = getFormatAndTypeForInternalFormat(internalFormat);
var format = options.format || formatType.format;
var type = options.type || formatType.type;
savePackState(gl, options);
gl.bindTexture(target, tex);
if (target === gl.TEXTURE_CUBE_MAP) {
// guess the parts
var imgWidth = element.width;
var imgHeight = element.height;
var size;
var slices;
if (imgWidth / 6 === imgHeight) {
// It's 6x1
size = imgHeight;
slices = [0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0];
} else if (imgHeight / 6 === imgWidth) {
// It's 1x6
size = imgWidth;
slices = [0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5];
} else if (imgWidth / 3 === imgHeight / 2) {
// It's 3x2
size = imgWidth / 3;
slices = [0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 2, 1];
} else if (imgWidth / 2 === imgHeight / 3) {
// It's 2x3
size = imgWidth / 2;
slices = [0, 0, 1, 0, 0, 1, 1, 1, 0, 2, 1, 2];
} else {
throw "can't figure out cube map from element: " + (element.src ? element.src : element.nodeName);
}
ctx.canvas.width = size;
ctx.canvas.height = size;
width = size;
height = size;
getCubeFacesWithNdx(gl, options).forEach(function(f) {
var xOffset = slices[f.ndx * 2 + 0] * size;
var yOffset = slices[f.ndx * 2 + 1] * size;
ctx.drawImage(element, xOffset, yOffset, size, size, 0, 0, size, size);
gl.texImage2D(f.face, 0, internalFormat, format, type, ctx.canvas);
});
// Free up the canvas memory
ctx.canvas.width = 1;
ctx.canvas.height = 1;
} else if (target === gl.TEXTURE_3D) {
var smallest = Math.min(element.width, element.height);
var largest = Math.max(element.width, element.height);
var depth = largest / smallest;
if (depth % 1 !== 0) {
throw "can not compute 3D dimensions of element";
}
var xMult = element.width === largest ? 1 : 0;
var yMult = element.height === largest ? 1 : 0;
gl.texImage3D(target, 0, internalFormat, smallest, smallest, smallest, 0, format, type, null);
// remove this is texSubImage3D gets width and height arguments
ctx.canvas.width = smallest;
ctx.canvas.height = smallest;
for (var d = 0; d < depth; ++d) {
// gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, d * smallest);
// gl.texSubImage3D(target, 0, 0, 0, d, format, type, element);
var srcX = d * smallest * xMult;
var srcY = d * smallest * yMult;
var srcW = smallest;
var srcH = smallest;
var dstX = 0;
var dstY = 0;
var dstW = smallest;
var dstH = smallest;
ctx.drawImage(element, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH);
gl.texSubImage3D(target, 0, 0, 0, d, smallest, smallest, 1, format, type, ctx.canvas);
}
ctx.canvas.width = 0;
ctx.canvas.height = 0;
// FIX (save state)
// gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
} else {
gl.texImage2D(target, 0, internalFormat, format, type, element);
}
restorePackState(gl, options);
if (options.auto !== false) {
setTextureFilteringForSize(gl, tex, options, width, height, internalFormat, type);
}
setTextureParameters(gl, tex, options);
}
function noop() {
}
/**
* Loads an image
* @param {string} url url to image
* @param {function(err, img)} [callback] a callback that's passed an error and the image. The error will be non-null
* if there was an error
* @return {HTMLImageElement} the image being loaded.
*/
function loadImage(url, crossOrigin, callback) {
callback = callback || noop;
var img = new Image();
crossOrigin = crossOrigin !== undefined ? crossOrigin : defaults.crossOrigin;
if (crossOrigin !== undefined) {
img.crossOrigin = crossOrigin;
}
function clearEventHandlers() {
img.removeEventListener('error', onError); // eslint-disable-line
img.removeEventListener('load', onLoad); // eslint-disable-line
img = null;
}
function onError() {
var msg = "couldn't load image: " + url;
utils.error(msg);
callback(msg, img);
clearEventHandlers();
}
function onLoad() {
callback(null, img);
clearEventHandlers();
}
img.addEventListener('error', onError);
img.addEventListener('load', onLoad);
img.src = url;
return img;
}
/**
* Sets a texture to a 1x1 pixel color. If `options.color === false` is nothing happens. If it's not set
* the default texture color is used which can be set by calling `setDefaultTextureColor`.
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {WebGLTexture} tex the WebGLTexture to set parameters for
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.
* This is often the same options you passed in when you created the texture.
* @memberOf module:twgl/textures
*/
function setTextureTo1PixelColor(gl, tex, options) {
options = options || defaults.textureOptions;
var target = options.target || gl.TEXTURE_2D;
gl.bindTexture(target, tex);
if (options.color === false) {
return;
}
// Assume it's a URL
// Put 1x1 pixels in texture. That makes it renderable immediately regardless of filtering.
var color = make1Pixel(options.color);
if (target === gl.TEXTURE_CUBE_MAP) {
for (var ii = 0; ii < 6; ++ii) {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + ii, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, color);
}
} else if (target === gl.TEXTURE_3D || target === gl.TEXTURE_2D_ARRAY) {