This repository has been archived by the owner on Jan 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
twgl-full.js
10579 lines (9401 loc) · 355 KB
/
twgl-full.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
/*!
* @license twgl.js 4.14.0 Copyright (c) 2015, Gregg Tavares All Rights Reserved.
* Available via the MIT license.
* see: http://github.com/greggman/twgl.js for details
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["twgl"] = factory();
else
root["twgl"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/twgl-full.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./src/attributes.js":
/*!***************************!*\
!*** ./src/attributes.js ***!
\***************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.createAttribsFromArrays = createAttribsFromArrays;
exports.createBuffersFromArrays = createBuffersFromArrays;
exports.createBufferFromArray = createBufferFromArray;
exports.createBufferFromTypedArray = createBufferFromTypedArray;
exports.createBufferInfoFromArrays = createBufferInfoFromArrays;
exports.setAttribInfoBufferFromArray = setAttribInfoBufferFromArray;
exports.setAttributePrefix = setAttributePrefix;
exports.setAttributeDefaults_ = setDefaults;
exports.getNumComponents_ = getNumComponents;
exports.getArray_ = getArray;
var typedArrays = _interopRequireWildcard(__webpack_require__(/*! ./typedarrays.js */ "./src/typedarrays.js"));
var helper = _interopRequireWildcard(__webpack_require__(/*! ./helper.js */ "./src/helper.js"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
* Copyright 2019 Gregg Tavares
*
* 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.
*/
var STATIC_DRAW = 0x88e4;
var ARRAY_BUFFER = 0x8892;
var ELEMENT_ARRAY_BUFFER = 0x8893;
var BUFFER_SIZE = 0x8764;
var BYTE = 0x1400;
var UNSIGNED_BYTE = 0x1401;
var SHORT = 0x1402;
var UNSIGNED_SHORT = 0x1403;
var INT = 0x1404;
var UNSIGNED_INT = 0x1405;
var FLOAT = 0x1406;
/**
* Low level attribute and buffer 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 compatibility they are available at both `twgl.attributes` and `twgl`
* itself
*
* See {@link module:twgl} for core functions
*
* @module twgl/attributes
*/
// make sure we don't see a global gl
var gl = undefined;
/* eslint-disable-line */
/* lgtm [js/unused-local-variable] */
var defaults = {
attribPrefix: ""
};
/**
* Sets the default attrib prefix
*
* When writing shaders I prefer to name attributes with `a_`, uniforms with `u_` and varyings with `v_`
* as it makes it clear where they came from. But, when building geometry I prefer using un-prefixed names.
*
* In other words I'll create arrays of geometry like this
*
* var arrays = {
* position: ...
* normal: ...
* texcoord: ...
* };
*
* But need those mapped to attributes and my attributes start with `a_`.
*
* @deprecated see {@link module:twgl.setDefaults}
* @param {string} prefix prefix for attribs
* @memberOf module:twgl/attributes
*/
function setAttributePrefix(prefix) {
defaults.attribPrefix = prefix;
}
function setDefaults(newDefaults) {
helper.copyExistingProperties(newDefaults, defaults);
}
function setBufferFromTypedArray(gl, type, buffer, array, drawType) {
gl.bindBuffer(type, buffer);
gl.bufferData(type, array, drawType || STATIC_DRAW);
}
/**
* Given typed array creates a WebGLBuffer and copies the typed array
* into it.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView|WebGLBuffer} typedArray the typed array. Note: If a WebGLBuffer is passed in it will just be returned. No action will be taken
* @param {number} [type] the GL bind type for the buffer. Default = `gl.ARRAY_BUFFER`.
* @param {number} [drawType] the GL draw type for the buffer. Default = 'gl.STATIC_DRAW`.
* @return {WebGLBuffer} the created WebGLBuffer
* @memberOf module:twgl/attributes
*/
function createBufferFromTypedArray(gl, typedArray, type, drawType) {
if (helper.isBuffer(gl, typedArray)) {
return typedArray;
}
type = type || ARRAY_BUFFER;
var buffer = gl.createBuffer();
setBufferFromTypedArray(gl, type, buffer, typedArray, drawType);
return buffer;
}
function isIndices(name) {
return name === "indices";
} // This is really just a guess. Though I can't really imagine using
// anything else? Maybe for some compression?
function getNormalizationForTypedArray(typedArray) {
if (typedArray instanceof Int8Array) {
return true;
} // eslint-disable-line
if (typedArray instanceof Uint8Array) {
return true;
} // eslint-disable-line
return false;
} // This is really just a guess. Though I can't really imagine using
// anything else? Maybe for some compression?
function getNormalizationForTypedArrayType(typedArrayType) {
if (typedArrayType === Int8Array) {
return true;
} // eslint-disable-line
if (typedArrayType === Uint8Array) {
return true;
} // eslint-disable-line
return false;
}
function getArray(array) {
return array.length ? array : array.data;
}
var texcoordRE = /coord|texture/i;
var colorRE = /color|colour/i;
function guessNumComponentsFromName(name, length) {
var numComponents;
if (texcoordRE.test(name)) {
numComponents = 2;
} else if (colorRE.test(name)) {
numComponents = 4;
} else {
numComponents = 3; // position, normals, indices ...
}
if (length % numComponents > 0) {
throw new Error("Can not guess numComponents for attribute '".concat(name, "'. Tried ").concat(numComponents, " but ").concat(length, " values is not evenly divisible by ").concat(numComponents, ". You should specify it."));
}
return numComponents;
}
function getNumComponents(array, arrayName) {
return array.numComponents || array.size || guessNumComponentsFromName(arrayName, getArray(array).length);
}
function makeTypedArray(array, name) {
if (typedArrays.isArrayBuffer(array)) {
return array;
}
if (typedArrays.isArrayBuffer(array.data)) {
return array.data;
}
if (Array.isArray(array)) {
array = {
data: array
};
}
var Type = array.type;
if (!Type) {
if (isIndices(name)) {
Type = Uint16Array;
} else {
Type = Float32Array;
}
}
return new Type(array.data);
}
/**
* The info for an attribute. This is effectively just the arguments to `gl.vertexAttribPointer` plus the WebGLBuffer
* for the attribute.
*
* @typedef {Object} AttribInfo
* @property {number[]|ArrayBufferView} [value] a constant value for the attribute. Note: if this is set the attribute will be
* disabled and set to this constant value and all other values will be ignored.
* @property {number} [numComponents] the number of components for this attribute.
* @property {number} [size] synonym for `numComponents`.
* @property {number} [type] the type of the attribute (eg. `gl.FLOAT`, `gl.UNSIGNED_BYTE`, etc...) Default = `gl.FLOAT`
* @property {boolean} [normalize] whether or not to normalize the data. Default = false
* @property {number} [offset] offset into buffer in bytes. Default = 0
* @property {number} [stride] the stride in bytes per element. Default = 0
* @property {number} [divisor] the divisor in instances. Default = undefined. Note: undefined = don't call gl.vertexAttribDivisor
* where as anything else = do call it with this value
* @property {WebGLBuffer} buffer the buffer that contains the data for this attribute
* @property {number} [drawType] the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW
* @memberOf module:twgl
*/
/**
* Use this type of array spec when TWGL can't guess the type or number of components of an array
* @typedef {Object} FullArraySpec
* @property {number[]|ArrayBufferView} [value] a constant value for the attribute. Note: if this is set the attribute will be
* disabled and set to this constant value and all other values will be ignored.
* @property {(number|number[]|ArrayBufferView)} data The data of the array. A number alone becomes the number of elements of type.
* @property {number} [numComponents] number of components for `vertexAttribPointer`. Default is based on the name of the array.
* If `coord` is in the name assumes `numComponents = 2`.
* If `color` is in the name assumes `numComponents = 4`.
* otherwise assumes `numComponents = 3`
* @property {constructor} [type] type. This is only used if `data` is a JavaScript array. It is the constructor for the typedarray. (eg. `Uint8Array`).
* For example if you want colors in a `Uint8Array` you might have a `FullArraySpec` like `{ type: Uint8Array, data: [255,0,255,255, ...], }`.
* @property {number} [size] synonym for `numComponents`.
* @property {boolean} [normalize] normalize for `vertexAttribPointer`. Default is true if type is `Int8Array` or `Uint8Array` otherwise false.
* @property {number} [stride] stride for `vertexAttribPointer`. Default = 0
* @property {number} [offset] offset for `vertexAttribPointer`. Default = 0
* @property {number} [divisor] divisor for `vertexAttribDivisor`. Default = undefined. Note: undefined = don't call gl.vertexAttribDivisor
* where as anything else = do call it with this value
* @property {string} [attrib] name of attribute this array maps to. Defaults to same name as array prefixed by the default attribPrefix.
* @property {string} [name] synonym for `attrib`.
* @property {string} [attribName] synonym for `attrib`.
* @property {WebGLBuffer} [buffer] Buffer to use for this attribute. This lets you use your own buffer
* but you will need to supply `numComponents` and `type`. You can effectively pass an `AttribInfo`
* to provide this. Example:
*
* const bufferInfo1 = twgl.createBufferInfoFromArrays(gl, {
* position: [1, 2, 3, ... ],
* });
* const bufferInfo2 = twgl.createBufferInfoFromArrays(gl, {
* position: bufferInfo1.attribs.position, // use the same buffer from bufferInfo1
* });
*
* @memberOf module:twgl
*/
/**
* An individual array in {@link module:twgl.Arrays}
*
* When passed to {@link module:twgl.createBufferInfoFromArrays} if an ArraySpec is `number[]` or `ArrayBufferView`
* the types will be guessed based on the name. `indices` will be `Uint16Array`, everything else will
* be `Float32Array`. If an ArraySpec is a number it's the number of floats for an empty (zeroed) buffer.
*
* @typedef {(number|number[]|ArrayBufferView|module:twgl.FullArraySpec)} ArraySpec
* @memberOf module:twgl
*/
/**
* This is a JavaScript object of arrays by name. The names should match your shader's attributes. If your
* attributes have a common prefix you can specify it by calling {@link module:twgl.setAttributePrefix}.
*
* Bare JavaScript Arrays
*
* var arrays = {
* position: [-1, 1, 0],
* normal: [0, 1, 0],
* ...
* }
*
* Bare TypedArrays
*
* var arrays = {
* position: new Float32Array([-1, 1, 0]),
* color: new Uint8Array([255, 128, 64, 255]),
* ...
* }
*
* * Will guess at `numComponents` if not specified based on name.
*
* If `coord` is in the name assumes `numComponents = 2`
*
* If `color` is in the name assumes `numComponents = 4`
*
* otherwise assumes `numComponents = 3`
*
* Objects with various fields. See {@link module:twgl.FullArraySpec}.
*
* var arrays = {
* position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
* texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },
* normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },
* indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },
* };
*
* @typedef {Object.<string, module:twgl.ArraySpec>} Arrays
* @memberOf module:twgl
*/
/**
* Creates a set of attribute data and WebGLBuffers from set of arrays
*
* Given
*
* var arrays = {
* position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
* texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },
* normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },
* color: { numComponents: 4, data: [255, 255, 255, 255, 255, 0, 0, 255, 0, 0, 255, 255], type: Uint8Array, },
* indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },
* };
*
* returns something like
*
* var attribs = {
* position: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },
* texcoord: { numComponents: 2, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },
* normal: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, },
* color: { numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true, buffer: WebGLBuffer, },
* };
*
* notes:
*
* * Arrays can take various forms
*
* Bare JavaScript Arrays
*
* var arrays = {
* position: [-1, 1, 0],
* normal: [0, 1, 0],
* ...
* }
*
* Bare TypedArrays
*
* var arrays = {
* position: new Float32Array([-1, 1, 0]),
* color: new Uint8Array([255, 128, 64, 255]),
* ...
* }
*
* * Will guess at `numComponents` if not specified based on name.
*
* If `coord` is in the name assumes `numComponents = 2`
*
* If `color` is in the name assumes `numComponents = 4`
*
* otherwise assumes `numComponents = 3`
*
* @param {WebGLRenderingContext} gl The webgl rendering context.
* @param {module:twgl.Arrays} arrays The arrays
* @param {module:twgl.BufferInfo} [srcBufferInfo] a BufferInfo to copy from
* This lets you share buffers. Any arrays you supply will override
* the buffers from srcBufferInfo.
* @return {Object.<string, module:twgl.AttribInfo>} the attribs
* @memberOf module:twgl/attributes
*/
function createAttribsFromArrays(gl, arrays) {
var attribs = {};
Object.keys(arrays).forEach(function (arrayName) {
if (!isIndices(arrayName)) {
var array = arrays[arrayName];
var attribName = array.attrib || array.name || array.attribName || defaults.attribPrefix + arrayName;
if (array.value) {
if (!Array.isArray(array.value) && !typedArrays.isArrayBuffer(array.value)) {
throw new Error('array.value is not array or typedarray');
}
attribs[attribName] = {
value: array.value
};
} else {
var buffer;
var type;
var normalization;
var numComponents;
if (array.buffer && array.buffer instanceof WebGLBuffer) {
buffer = array.buffer;
numComponents = array.numComponents || array.size;
type = array.type;
normalization = array.normalize;
} else if (typeof array === "number" || typeof array.data === "number") {
var numValues = array.data || array;
var arrayType = array.type || Float32Array;
var numBytes = numValues * arrayType.BYTES_PER_ELEMENT;
type = typedArrays.getGLTypeForTypedArrayType(arrayType);
normalization = array.normalize !== undefined ? array.normalize : getNormalizationForTypedArrayType(arrayType);
numComponents = array.numComponents || array.size || guessNumComponentsFromName(arrayName, numValues);
buffer = gl.createBuffer();
gl.bindBuffer(ARRAY_BUFFER, buffer);
gl.bufferData(ARRAY_BUFFER, numBytes, array.drawType || STATIC_DRAW);
} else {
var typedArray = makeTypedArray(array, arrayName);
buffer = createBufferFromTypedArray(gl, typedArray, undefined, array.drawType);
type = typedArrays.getGLTypeForTypedArray(typedArray);
normalization = array.normalize !== undefined ? array.normalize : getNormalizationForTypedArray(typedArray);
numComponents = getNumComponents(array, arrayName);
}
attribs[attribName] = {
buffer: buffer,
numComponents: numComponents,
type: type,
normalize: normalization,
stride: array.stride || 0,
offset: array.offset || 0,
divisor: array.divisor === undefined ? undefined : array.divisor,
drawType: array.drawType
};
}
}
});
gl.bindBuffer(ARRAY_BUFFER, null);
return attribs;
}
/**
* Sets the contents of a buffer attached to an attribInfo
*
* This is helper function to dynamically update a buffer.
*
* Let's say you make a bufferInfo
*
* var arrays = {
* position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),
* texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),
* normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
* indices: new Uint16Array([0, 1, 2, 1, 2, 3]),
* };
* var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);
*
* And you want to dynamically update the positions. You could do this
*
* // assuming arrays.position has already been updated with new data.
* twgl.setAttribInfoBufferFromArray(gl, bufferInfo.attribs.position, arrays.position);
*
* @param {WebGLRenderingContext} gl
* @param {AttribInfo} attribInfo The attribInfo who's buffer contents to set. NOTE: If you have an attribute prefix
* the name of the attribute will include the prefix.
* @param {ArraySpec} array Note: it is arguably inefficient to pass in anything but a typed array because anything
* else will have to be converted to a typed array before it can be used by WebGL. During init time that
* inefficiency is usually not important but if you're updating data dynamically best to be efficient.
* @param {number} [offset] an optional offset into the buffer. This is only an offset into the WebGL buffer
* not the array. To pass in an offset into the array itself use a typed array and create an `ArrayBufferView`
* for the portion of the array you want to use.
*
* var someArray = new Float32Array(1000); // an array with 1000 floats
* var someSubArray = new Float32Array(someArray.buffer, offsetInBytes, sizeInUnits); // a view into someArray
*
* Now you can pass `someSubArray` into setAttribInfoBufferFromArray`
* @memberOf module:twgl/attributes
*/
function setAttribInfoBufferFromArray(gl, attribInfo, array, offset) {
array = makeTypedArray(array);
if (offset !== undefined) {
gl.bindBuffer(ARRAY_BUFFER, attribInfo.buffer);
gl.bufferSubData(ARRAY_BUFFER, offset, array);
} else {
setBufferFromTypedArray(gl, ARRAY_BUFFER, attribInfo.buffer, array, attribInfo.drawType);
}
}
function getBytesPerValueForGLType(gl, type) {
if (type === BYTE) return 1; // eslint-disable-line
if (type === UNSIGNED_BYTE) return 1; // eslint-disable-line
if (type === SHORT) return 2; // eslint-disable-line
if (type === UNSIGNED_SHORT) return 2; // eslint-disable-line
if (type === INT) return 4; // eslint-disable-line
if (type === UNSIGNED_INT) return 4; // eslint-disable-line
if (type === FLOAT) return 4; // eslint-disable-line
return 0;
} // Tries to get the number of elements from a set of arrays.
var positionKeys = ['position', 'positions', 'a_position'];
function getNumElementsFromNonIndexedArrays(arrays) {
var key;
var ii;
for (ii = 0; ii < positionKeys.length; ++ii) {
key = positionKeys[ii];
if (key in arrays) {
break;
}
}
if (ii === positionKeys.length) {
key = Object.keys(arrays)[0];
}
var array = arrays[key];
var length = getArray(array).length;
var numComponents = getNumComponents(array, key);
var numElements = length / numComponents;
if (length % numComponents > 0) {
throw new Error("numComponents ".concat(numComponents, " not correct for length ").concat(length));
}
return numElements;
}
function getNumElementsFromAttributes(gl, attribs) {
var key;
var ii;
for (ii = 0; ii < positionKeys.length; ++ii) {
key = positionKeys[ii];
if (key in attribs) {
break;
}
key = defaults.attribPrefix + key;
if (key in attribs) {
break;
}
}
if (ii === positionKeys.length) {
key = Object.keys(attribs)[0];
}
var attrib = attribs[key];
gl.bindBuffer(ARRAY_BUFFER, attrib.buffer);
var numBytes = gl.getBufferParameter(ARRAY_BUFFER, BUFFER_SIZE);
gl.bindBuffer(ARRAY_BUFFER, null);
var bytesPerValue = getBytesPerValueForGLType(gl, attrib.type);
var totalElements = numBytes / bytesPerValue;
var numComponents = attrib.numComponents || attrib.size; // TODO: check stride
var numElements = totalElements / numComponents;
if (numElements % 1 !== 0) {
throw new Error("numComponents ".concat(numComponents, " not correct for length ").concat(length));
}
return numElements;
}
/**
* @typedef {Object} BufferInfo
* @property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.
* @property {number} [elementType] The type of indices `UNSIGNED_BYTE`, `UNSIGNED_SHORT` etc..
* @property {WebGLBuffer} [indices] The indices `ELEMENT_ARRAY_BUFFER` if any indices exist.
* @property {Object.<string, module:twgl.AttribInfo>} [attribs] The attribs appropriate to call `setAttributes`
* @memberOf module:twgl
*/
/**
* Creates a BufferInfo from an object of arrays.
*
* This can be passed to {@link module:twgl.setBuffersAndAttributes} and to
* {@link module:twgl:drawBufferInfo}.
*
* Given an object like
*
* var arrays = {
* position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
* texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], },
* normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], },
* indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], },
* };
*
* Creates an BufferInfo like this
*
* bufferInfo = {
* numElements: 4, // or whatever the number of elements is
* indices: WebGLBuffer, // this property will not exist if there are no indices
* attribs: {
* position: { buffer: WebGLBuffer, numComponents: 3, },
* normal: { buffer: WebGLBuffer, numComponents: 3, },
* texcoord: { buffer: WebGLBuffer, numComponents: 2, },
* },
* };
*
* The properties of arrays can be JavaScript arrays in which case the number of components
* will be guessed.
*
* var arrays = {
* position: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0],
* texcoord: [0, 0, 0, 1, 1, 0, 1, 1],
* normal: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
* indices: [0, 1, 2, 1, 2, 3],
* };
*
* They can also be TypedArrays
*
* var arrays = {
* position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),
* texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),
* normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
* indices: new Uint16Array([0, 1, 2, 1, 2, 3]),
* };
*
* Or AugmentedTypedArrays
*
* var positions = createAugmentedTypedArray(3, 4);
* var texcoords = createAugmentedTypedArray(2, 4);
* var normals = createAugmentedTypedArray(3, 4);
* var indices = createAugmentedTypedArray(3, 2, Uint16Array);
*
* positions.push([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]);
* texcoords.push([0, 0, 0, 1, 1, 0, 1, 1]);
* normals.push([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]);
* indices.push([0, 1, 2, 1, 2, 3]);
*
* var arrays = {
* position: positions,
* texcoord: texcoords,
* normal: normals,
* indices: indices,
* };
*
* For the last example it is equivalent to
*
* var bufferInfo = {
* attribs: {
* position: { numComponents: 3, buffer: gl.createBuffer(), },
* texcoord: { numComponents: 2, buffer: gl.createBuffer(), },
* normal: { numComponents: 3, buffer: gl.createBuffer(), },
* },
* indices: gl.createBuffer(),
* numElements: 6,
* };
*
* gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.position.buffer);
* gl.bufferData(gl.ARRAY_BUFFER, arrays.position, gl.STATIC_DRAW);
* gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.texcoord.buffer);
* gl.bufferData(gl.ARRAY_BUFFER, arrays.texcoord, gl.STATIC_DRAW);
* gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.normal.buffer);
* gl.bufferData(gl.ARRAY_BUFFER, arrays.normal, gl.STATIC_DRAW);
* gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferInfo.indices);
* gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, arrays.indices, gl.STATIC_DRAW);
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {module:twgl.Arrays} arrays Your data
* @param {module:twgl.BufferInfo} [srcBufferInfo] An existing
* buffer info to start from. WebGLBuffers etc specified
* in the srcBufferInfo will be used in a new BufferInfo
* with any arrays specified overriding the ones in
* srcBufferInfo.
* @return {module:twgl.BufferInfo} A BufferInfo
* @memberOf module:twgl/attributes
*/
function createBufferInfoFromArrays(gl, arrays, srcBufferInfo) {
var newAttribs = createAttribsFromArrays(gl, arrays);
var bufferInfo = Object.assign({}, srcBufferInfo ? srcBufferInfo : {});
bufferInfo.attribs = Object.assign({}, srcBufferInfo ? srcBufferInfo.attribs : {}, newAttribs);
var indices = arrays.indices;
if (indices) {
var newIndices = makeTypedArray(indices, "indices");
bufferInfo.indices = createBufferFromTypedArray(gl, newIndices, ELEMENT_ARRAY_BUFFER);
bufferInfo.numElements = newIndices.length;
bufferInfo.elementType = typedArrays.getGLTypeForTypedArray(newIndices);
} else if (!bufferInfo.numElements) {
bufferInfo.numElements = getNumElementsFromAttributes(gl, bufferInfo.attribs);
}
return bufferInfo;
}
/**
* Creates a buffer from an array, typed array, or array spec
*
* Given something like this
*
* [1, 2, 3],
*
* or
*
* new Uint16Array([1,2,3]);
*
* or
*
* {
* data: [1, 2, 3],
* type: Uint8Array,
* }
*
* returns a WebGLBuffer that contains the given data.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext.
* @param {module:twgl.ArraySpec} array an array, typed array, or array spec.
* @param {string} arrayName name of array. Used to guess the type if type can not be derived otherwise.
* @return {WebGLBuffer} a WebGLBuffer containing the data in array.
* @memberOf module:twgl/attributes
*/
function createBufferFromArray(gl, array, arrayName) {
var type = arrayName === "indices" ? ELEMENT_ARRAY_BUFFER : ARRAY_BUFFER;
var typedArray = makeTypedArray(array, arrayName);
return createBufferFromTypedArray(gl, typedArray, type);
}
/**
* Creates buffers from arrays or typed arrays
*
* Given something like this
*
* var arrays = {
* positions: [1, 2, 3],
* normals: [0, 0, 1],
* }
*
* returns something like
*
* buffers = {
* positions: WebGLBuffer,
* normals: WebGLBuffer,
* }
*
* If the buffer is named 'indices' it will be made an ELEMENT_ARRAY_BUFFER.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext.
* @param {module:twgl.Arrays} arrays
* @return {Object<string, WebGLBuffer>} returns an object with one WebGLBuffer per array
* @memberOf module:twgl/attributes
*/
function createBuffersFromArrays(gl, arrays) {
var buffers = {};
Object.keys(arrays).forEach(function (key) {
buffers[key] = createBufferFromArray(gl, arrays[key], key);
}); // Ugh!
if (arrays.indices) {
buffers.numElements = arrays.indices.length;
buffers.elementType = typedArrays.getGLTypeForTypedArray(makeTypedArray(arrays.indices), 'indices');
} else {
buffers.numElements = getNumElementsFromNonIndexedArrays(arrays);
}
return buffers;
}
/***/ }),
/***/ "./src/draw.js":
/*!*********************!*\
!*** ./src/draw.js ***!
\*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.drawBufferInfo = drawBufferInfo;
exports.drawObjectList = drawObjectList;
var programs = _interopRequireWildcard(__webpack_require__(/*! ./programs.js */ "./src/programs.js"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
* Copyright 2019 Gregg Tavares
*
* 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.
*/
var TRIANGLES = 0x0004;
var UNSIGNED_SHORT = 0x1403;
/**
* Drawing related functions
*
* For backward compatibility they are available at both `twgl.draw` and `twgl`
* itself
*
* See {@link module:twgl} for core functions
*
* @module twgl/draw
*/
/**
* Calls `gl.drawElements` or `gl.drawArrays`, whichever is appropriate
*
* normally you'd call `gl.drawElements` or `gl.drawArrays` yourself
* but calling this means if you switch from indexed data to non-indexed
* data you don't have to remember to update your draw call.
*
* @param {WebGLRenderingContext} gl A WebGLRenderingContext
* @param {(module:twgl.BufferInfo|module:twgl.VertexArrayInfo)} bufferInfo A BufferInfo as returned from {@link module:twgl.createBufferInfoFromArrays} or
* a VertexArrayInfo as returned from {@link module:twgl.createVertexArrayInfo}
* @param {number} [type] eg (gl.TRIANGLES, gl.LINES, gl.POINTS, gl.TRIANGLE_STRIP, ...). Defaults to `gl.TRIANGLES`
* @param {number} [count] An optional count. Defaults to bufferInfo.numElements
* @param {number} [offset] An optional offset. Defaults to 0.
* @param {number} [instanceCount] An optional instanceCount. if set then `drawArraysInstanced` or `drawElementsInstanced` will be called
* @memberOf module:twgl/draw
*/
function drawBufferInfo(gl, bufferInfo, type, count, offset, instanceCount) {
type = type === undefined ? TRIANGLES : type;
var indices = bufferInfo.indices;
var elementType = bufferInfo.elementType;
var numElements = count === undefined ? bufferInfo.numElements : count;
offset = offset === undefined ? 0 : offset;
if (elementType || indices) {
if (instanceCount !== undefined) {
gl.drawElementsInstanced(type, numElements, elementType === undefined ? UNSIGNED_SHORT : bufferInfo.elementType, offset, instanceCount);
} else {
gl.drawElements(type, numElements, elementType === undefined ? UNSIGNED_SHORT : bufferInfo.elementType, offset);
}
} else {
if (instanceCount !== undefined) {
gl.drawArraysInstanced(type, offset, numElements, instanceCount);
} else {
gl.drawArrays(type, offset, numElements);
}
}
}
/**
* A DrawObject is useful for putting objects in to an array and passing them to {@link module:twgl.drawObjectList}.
*
* You need either a `BufferInfo` or a `VertexArrayInfo`.
*
* @typedef {Object} DrawObject