1/******/ (() => { // webpackBootstrap 2/******/ // runtime can't be in strict mode because a global variable is assign and maybe created. 3/******/ var __webpack_modules__ = ({ 4
vendor: 2,154 bytes, lines 5-73
5/***/ "./node_modules/gl-matrix/esm/common.js": 6/*!**********************************************!*\ 7 !*** ./node_modules/gl-matrix/esm/common.js ***! 8 \**********************************************/ 9/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { 10 11"use strict"; 12__webpack_require__.r(__webpack_exports__); 13/* harmony export */ __webpack_require__.d(__webpack_exports__, { 14/* harmony export */ ARRAY_TYPE: () => (/* binding */ ARRAY_TYPE), 15/* harmony export */ EPSILON: () => (/* binding */ EPSILON), 16/* harmony export */ RANDOM: () => (/* binding */ RANDOM), 17/* harmony export */ equals: () => (/* binding */ equals), 18/* harmony export */ setMatrixArrayType: () => (/* binding */ setMatrixArrayType), 19/* harmony export */ toRadian: () => (/* binding */ toRadian) 20/* harmony export */ }); 21/** 22 * Common utilities 23 * @module glMatrix 24 */ 25// Configuration Constants 26var EPSILON = 0.000001; 27var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; 28var RANDOM = Math.random; 29/** 30 * Sets the type of array used when creating new vectors and matrices 31 * 32 * @param {Type} type Array type, such as Float32Array or Array 33 */ 34 35function setMatrixArrayType(type) { 36 ARRAY_TYPE = type; 37} 38var degree = Math.PI / 180; 39/** 40 * Convert Degree To Radian 41 * 42 * @param {Number} a Angle in Degrees 43 */ 44 45function toRadian(a) { 46 return a * degree; 47} 48/** 49 * Tests whether or not the arguments have approximately the same value, within an absolute 50 * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less 51 * than or equal to 1.0, and a relative tolerance is used for larger values) 52 * 53 * @param {Number} a The first number to test. 54 * @param {Number} b The second number to test. 55 * @returns {Boolean} True if the numbers are approximately equal, false otherwise. 56 */ 57 58function equals(a, b) { 59 return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); 60} 61if (!Math.hypot) Math.hypot = function () { 62 var y = 0, 63 i = arguments.length; 64 65 while (i--) { 66 y += arguments[i] * arguments[i]; 67 } 68 69 return Math.sqrt(y); 70}; 71 72/***/ }), 73
vendor: 12,213 bytes, lines 74-545
74/***/ "./node_modules/gl-matrix/esm/mat2.js": 75/*!********************************************!*\ 76 !*** ./node_modules/gl-matrix/esm/mat2.js ***! 77 \********************************************/ 78/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { 79 80"use strict"; 81__webpack_require__.r(__webpack_exports__); 82/* harmony export */ __webpack_require__.d(__webpack_exports__, { 83/* harmony export */ LDU: () => (/* binding */ LDU), 84/* harmony export */ add: () => (/* binding */ add), 85/* harmony export */ adjoint: () => (/* binding */ adjoint), 86/* harmony export */ clone: () => (/* binding */ clone), 87/* harmony export */ copy: () => (/* binding */ copy), 88/* harmony export */ create: () => (/* binding */ create), 89/* harmony export */ determinant: () => (/* binding */ determinant), 90/* harmony export */ equals: () => (/* binding */ equals), 91/* harmony export */ exactEquals: () => (/* binding */ exactEquals), 92/* harmony export */ frob: () => (/* binding */ frob), 93/* harmony export */ fromRotation: () => (/* binding */ fromRotation), 94/* harmony export */ fromScaling: () => (/* binding */ fromScaling), 95/* harmony export */ fromValues: () => (/* binding */ fromValues), 96/* harmony export */ identity: () => (/* binding */ identity), 97/* harmony export */ invert: () => (/* binding */ invert), 98/* harmony export */ mul: () => (/* binding */ mul), 99/* harmony export */ multiply: () => (/* binding */ multiply), 100/* harmony export */ multiplyScalar: () => (/* binding */ multiplyScalar), 101/* harmony export */ multiplyScalarAndAdd: () => (/* binding */ multiplyScalarAndAdd), 102/* harmony export */ rotate: () => (/* binding */ rotate), 103/* harmony export */ scale: () => (/* binding */ scale), 104/* harmony export */ set: () => (/* binding */ set), 105/* harmony export */ str: () => (/* binding */ str), 106/* harmony export */ sub: () => (/* binding */ sub), 107/* harmony export */ subtract: () => (/* binding */ subtract), 108/* harmony export */ transpose: () => (/* binding */ transpose) 109/* harmony export */ }); 110/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common.js */ "./node_modules/gl-matrix/esm/common.js"); 111 112/** 113 * 2x2 Matrix 114 * @module mat2 115 */ 116 117/** 118 * Creates a new identity mat2 119 * 120 * @returns {mat2} a new 2x2 matrix 121 */ 122 123function create() { 124 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(4); 125 126 if (_common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE != Float32Array) { 127 out[1] = 0; 128 out[2] = 0; 129 } 130 131 out[0] = 1; 132 out[3] = 1; 133 return out; 134} 135/** 136 * Creates a new mat2 initialized with values from an existing matrix 137 * 138 * @param {mat2} a matrix to clone 139 * @returns {mat2} a new 2x2 matrix 140 */ 141 142function clone(a) { 143 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(4); 144 out[0] = a[0]; 145 out[1] = a[1]; 146 out[2] = a[2]; 147 out[3] = a[3]; 148 return out; 149} 150/** 151 * Copy the values from one mat2 to another 152 * 153 * @param {mat2} out the receiving matrix 154 * @param {mat2} a the source matrix 155 * @returns {mat2} out 156 */ 157 158function copy(out, a) { 159 out[0] = a[0]; 160 out[1] = a[1]; 161 out[2] = a[2]; 162 out[3] = a[3]; 163 return out; 164} 165/** 166 * Set a mat2 to the identity matrix 167 * 168 * @param {mat2} out the receiving matrix 169 * @returns {mat2} out 170 */ 171 172function identity(out) { 173 out[0] = 1; 174 out[1] = 0; 175 out[2] = 0; 176 out[3] = 1; 177 return out; 178} 179/** 180 * Create a new mat2 with the given values 181 * 182 * @param {Number} m00 Component in column 0, row 0 position (index 0) 183 * @param {Number} m01 Component in column 0, row 1 position (index 1) 184 * @param {Number} m10 Component in column 1, row 0 position (index 2) 185 * @param {Number} m11 Component in column 1, row 1 position (index 3) 186 * @returns {mat2} out A new 2x2 matrix 187 */ 188 189function fromValues(m00, m01, m10, m11) { 190 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(4); 191 out[0] = m00; 192 out[1] = m01; 193 out[2] = m10; 194 out[3] = m11; 195 return out; 196} 197/** 198 * Set the components of a mat2 to the given values 199 * 200 * @param {mat2} out the receiving matrix 201 * @param {Number} m00 Component in column 0, row 0 position (index 0) 202 * @param {Number} m01 Component in column 0, row 1 position (index 1) 203 * @param {Number} m10 Component in column 1, row 0 position (index 2) 204 * @param {Number} m11 Component in column 1, row 1 position (index 3) 205 * @returns {mat2} out 206 */ 207 208function set(out, m00, m01, m10, m11) { 209 out[0] = m00; 210 out[1] = m01; 211 out[2] = m10; 212 out[3] = m11; 213 return out; 214} 215/** 216 * Transpose the values of a mat2 217 * 218 * @param {mat2} out the receiving matrix 219 * @param {mat2} a the source matrix 220 * @returns {mat2} out 221 */ 222 223function transpose(out, a) { 224 // If we are transposing ourselves we can skip a few steps but have to cache 225 // some values 226 if (out === a) { 227 var a1 = a[1]; 228 out[1] = a[2]; 229 out[2] = a1; 230 } else { 231 out[0] = a[0]; 232 out[1] = a[2]; 233 out[2] = a[1]; 234 out[3] = a[3]; 235 } 236 237 return out; 238} 239/** 240 * Inverts a mat2 241 * 242 * @param {mat2} out the receiving matrix 243 * @param {mat2} a the source matrix 244 * @returns {mat2} out 245 */ 246 247function invert(out, a) { 248 var a0 = a[0], 249 a1 = a[1], 250 a2 = a[2], 251 a3 = a[3]; // Calculate the determinant 252 253 var det = a0 * a3 - a2 * a1; 254 255 if (!det) { 256 return null; 257 } 258 259 det = 1.0 / det; 260 out[0] = a3 * det; 261 out[1] = -a1 * det; 262 out[2] = -a2 * det; 263 out[3] = a0 * det; 264 return out; 265} 266/** 267 * Calculates the adjugate of a mat2 268 * 269 * @param {mat2} out the receiving matrix 270 * @param {mat2} a the source matrix 271 * @returns {mat2} out 272 */ 273 274function adjoint(out, a) { 275 // Caching this value is nessecary if out == a 276 var a0 = a[0]; 277 out[0] = a[3]; 278 out[1] = -a[1]; 279 out[2] = -a[2]; 280 out[3] = a0; 281 return out; 282} 283/** 284 * Calculates the determinant of a mat2 285 * 286 * @param {mat2} a the source matrix 287 * @returns {Number} determinant of a 288 */ 289 290function determinant(a) { 291 return a[0] * a[3] - a[2] * a[1]; 292} 293/** 294 * Multiplies two mat2's 295 * 296 * @param {mat2} out the receiving matrix 297 * @param {mat2} a the first operand 298 * @param {mat2} b the second operand 299 * @returns {mat2} out 300 */ 301 302function multiply(out, a, b) { 303 var a0 = a[0], 304 a1 = a[1], 305 a2 = a[2], 306 a3 = a[3]; 307 var b0 = b[0], 308 b1 = b[1], 309 b2 = b[2], 310 b3 = b[3]; 311 out[0] = a0 * b0 + a2 * b1; 312 out[1] = a1 * b0 + a3 * b1; 313 out[2] = a0 * b2 + a2 * b3; 314 out[3] = a1 * b2 + a3 * b3; 315 return out; 316} 317/** 318 * Rotates a mat2 by the given angle 319 * 320 * @param {mat2} out the receiving matrix 321 * @param {mat2} a the matrix to rotate 322 * @param {Number} rad the angle to rotate the matrix by 323 * @returns {mat2} out 324 */ 325 326function rotate(out, a, rad) { 327 var a0 = a[0], 328 a1 = a[1], 329 a2 = a[2], 330 a3 = a[3]; 331 var s = Math.sin(rad); 332 var c = Math.cos(rad); 333 out[0] = a0 * c + a2 * s; 334 out[1] = a1 * c + a3 * s; 335 out[2] = a0 * -s + a2 * c; 336 out[3] = a1 * -s + a3 * c; 337 return out; 338} 339/** 340 * Scales the mat2 by the dimensions in the given vec2 341 * 342 * @param {mat2} out the receiving matrix 343 * @param {mat2} a the matrix to rotate 344 * @param {vec2} v the vec2 to scale the matrix by 345 * @returns {mat2} out 346 **/ 347 348function scale(out, a, v) { 349 var a0 = a[0], 350 a1 = a[1], 351 a2 = a[2], 352 a3 = a[3]; 353 var v0 = v[0], 354 v1 = v[1]; 355 out[0] = a0 * v0; 356 out[1] = a1 * v0; 357 out[2] = a2 * v1; 358 out[3] = a3 * v1; 359 return out; 360} 361/** 362 * Creates a matrix from a given angle 363 * This is equivalent to (but much faster than): 364 * 365 * mat2.identity(dest); 366 * mat2.rotate(dest, dest, rad); 367 * 368 * @param {mat2} out mat2 receiving operation result 369 * @param {Number} rad the angle to rotate the matrix by 370 * @returns {mat2} out 371 */ 372 373function fromRotation(out, rad) { 374 var s = Math.sin(rad); 375 var c = Math.cos(rad); 376 out[0] = c; 377 out[1] = s; 378 out[2] = -s; 379 out[3] = c; 380 return out; 381} 382/** 383 * Creates a matrix from a vector scaling 384 * This is equivalent to (but much faster than): 385 * 386 * mat2.identity(dest); 387 * mat2.scale(dest, dest, vec); 388 * 389 * @param {mat2} out mat2 receiving operation result 390 * @param {vec2} v Scaling vector 391 * @returns {mat2} out 392 */ 393 394function fromScaling(out, v) { 395 out[0] = v[0]; 396 out[1] = 0; 397 out[2] = 0; 398 out[3] = v[1]; 399 return out; 400} 401/** 402 * Returns a string representation of a mat2 403 * 404 * @param {mat2} a matrix to represent as a string 405 * @returns {String} string representation of the matrix 406 */ 407 408function str(a) { 409 return 'mat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')'; 410} 411/** 412 * Returns Frobenius norm of a mat2 413 * 414 * @param {mat2} a the matrix to calculate Frobenius norm of 415 * @returns {Number} Frobenius norm 416 */ 417 418function frob(a) { 419 return Math.hypot(a[0], a[1], a[2], a[3]); 420} 421/** 422 * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix 423 * @param {mat2} L the lower triangular matrix 424 * @param {mat2} D the diagonal matrix 425 * @param {mat2} U the upper triangular matrix 426 * @param {mat2} a the input matrix to factorize 427 */ 428 429function LDU(L, D, U, a) { 430 L[2] = a[2] / a[0]; 431 U[0] = a[0]; 432 U[1] = a[1]; 433 U[3] = a[3] - L[2] * U[1]; 434 return [L, D, U]; 435} 436/** 437 * Adds two mat2's 438 * 439 * @param {mat2} out the receiving matrix 440 * @param {mat2} a the first operand 441 * @param {mat2} b the second operand 442 * @returns {mat2} out 443 */ 444 445function add(out, a, b) { 446 out[0] = a[0] + b[0]; 447 out[1] = a[1] + b[1]; 448 out[2] = a[2] + b[2]; 449 out[3] = a[3] + b[3]; 450 return out; 451} 452/** 453 * Subtracts matrix b from matrix a 454 * 455 * @param {mat2} out the receiving matrix 456 * @param {mat2} a the first operand 457 * @param {mat2} b the second operand 458 * @returns {mat2} out 459 */ 460 461function subtract(out, a, b) { 462 out[0] = a[0] - b[0]; 463 out[1] = a[1] - b[1]; 464 out[2] = a[2] - b[2]; 465 out[3] = a[3] - b[3]; 466 return out; 467} 468/** 469 * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) 470 * 471 * @param {mat2} a The first matrix. 472 * @param {mat2} b The second matrix. 473 * @returns {Boolean} True if the matrices are equal, false otherwise. 474 */ 475 476function exactEquals(a, b) { 477 return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; 478} 479/** 480 * Returns whether or not the matrices have approximately the same elements in the same position. 481 * 482 * @param {mat2} a The first matrix. 483 * @param {mat2} b The second matrix. 484 * @returns {Boolean} True if the matrices are equal, false otherwise. 485 */ 486 487function equals(a, b) { 488 var a0 = a[0], 489 a1 = a[1], 490 a2 = a[2], 491 a3 = a[3]; 492 var b0 = b[0], 493 b1 = b[1], 494 b2 = b[2], 495 b3 = b[3]; 496 return Math.abs(a0 - b0) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)); 497} 498/** 499 * Multiply each element of the matrix by a scalar. 500 * 501 * @param {mat2} out the receiving matrix 502 * @param {mat2} a the matrix to scale 503 * @param {Number} b amount to scale the matrix's elements by 504 * @returns {mat2} out 505 */ 506 507function multiplyScalar(out, a, b) { 508 out[0] = a[0] * b; 509 out[1] = a[1] * b; 510 out[2] = a[2] * b; 511 out[3] = a[3] * b; 512 return out; 513} 514/** 515 * Adds two mat2's after multiplying each element of the second operand by a scalar value. 516 * 517 * @param {mat2} out the receiving vector 518 * @param {mat2} a the first operand 519 * @param {mat2} b the second operand 520 * @param {Number} scale the amount to scale b's elements by before adding 521 * @returns {mat2} out 522 */ 523 524function multiplyScalarAndAdd(out, a, b, scale) { 525 out[0] = a[0] + b[0] * scale; 526 out[1] = a[1] + b[1] * scale; 527 out[2] = a[2] + b[2] * scale; 528 out[3] = a[3] + b[3] * scale; 529 return out; 530} 531/** 532 * Alias for {@link mat2.multiply} 533 * @function 534 */ 535 536var mul = multiply; 537/** 538 * Alias for {@link mat2.subtract} 539 * @function 540 */ 541 542var sub = subtract; 543 544/***/ }), 545
vendor: 13,449 bytes, lines 546-1070
546/***/ "./node_modules/gl-matrix/esm/mat2d.js": 547/*!*********************************************!*\ 548 !*** ./node_modules/gl-matrix/esm/mat2d.js ***! 549 \*********************************************/ 550/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { 551 552"use strict"; 553__webpack_require__.r(__webpack_exports__); 554/* harmony export */ __webpack_require__.d(__webpack_exports__, { 555/* harmony export */ add: () => (/* binding */ add), 556/* harmony export */ clone: () => (/* binding */ clone), 557/* harmony export */ copy: () => (/* binding */ copy), 558/* harmony export */ create: () => (/* binding */ create), 559/* harmony export */ determinant: () => (/* binding */ determinant), 560/* harmony export */ equals: () => (/* binding */ equals), 561/* harmony export */ exactEquals: () => (/* binding */ exactEquals), 562/* harmony export */ frob: () => (/* binding */ frob), 563/* harmony export */ fromRotation: () => (/* binding */ fromRotation), 564/* harmony export */ fromScaling: () => (/* binding */ fromScaling), 565/* harmony export */ fromTranslation: () => (/* binding */ fromTranslation), 566/* harmony export */ fromValues: () => (/* binding */ fromValues), 567/* harmony export */ identity: () => (/* binding */ identity), 568/* harmony export */ invert: () => (/* binding */ invert), 569/* harmony export */ mul: () => (/* binding */ mul), 570/* harmony export */ multiply: () => (/* binding */ multiply), 571/* harmony export */ multiplyScalar: () => (/* binding */ multiplyScalar), 572/* harmony export */ multiplyScalarAndAdd: () => (/* binding */ multiplyScalarAndAdd), 573/* harmony export */ rotate: () => (/* binding */ rotate), 574/* harmony export */ scale: () => (/* binding */ scale), 575/* harmony export */ set: () => (/* binding */ set), 576/* harmony export */ str: () => (/* binding */ str), 577/* harmony export */ sub: () => (/* binding */ sub), 578/* harmony export */ subtract: () => (/* binding */ subtract), 579/* harmony export */ translate: () => (/* binding */ translate) 580/* harmony export */ }); 581/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common.js */ "./node_modules/gl-matrix/esm/common.js"); 582 583/** 584 * 2x3 Matrix 585 * @module mat2d 586 * 587 * @description 588 * A mat2d contains six elements defined as: 589 * <pre> 590 * [a, b, c, 591 * d, tx, ty] 592 * </pre> 593 * This is a short form for the 3x3 matrix: 594 * <pre> 595 * [a, b, 0, 596 * c, d, 0, 597 * tx, ty, 1] 598 * </pre> 599 * The last column is ignored so the array is shorter and operations are faster. 600 */ 601 602/** 603 * Creates a new identity mat2d 604 * 605 * @returns {mat2d} a new 2x3 matrix 606 */ 607 608function create() { 609 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(6); 610 611 if (_common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE != Float32Array) { 612 out[1] = 0; 613 out[2] = 0; 614 out[4] = 0; 615 out[5] = 0; 616 } 617 618 out[0] = 1; 619 out[3] = 1; 620 return out; 621} 622/** 623 * Creates a new mat2d initialized with values from an existing matrix 624 * 625 * @param {mat2d} a matrix to clone 626 * @returns {mat2d} a new 2x3 matrix 627 */ 628 629function clone(a) { 630 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(6); 631 out[0] = a[0]; 632 out[1] = a[1]; 633 out[2] = a[2]; 634 out[3] = a[3]; 635 out[4] = a[4]; 636 out[5] = a[5]; 637 return out; 638} 639/** 640 * Copy the values from one mat2d to another 641 * 642 * @param {mat2d} out the receiving matrix 643 * @param {mat2d} a the source matrix 644 * @returns {mat2d} out 645 */ 646 647function copy(out, a) { 648 out[0] = a[0]; 649 out[1] = a[1]; 650 out[2] = a[2]; 651 out[3] = a[3]; 652 out[4] = a[4]; 653 out[5] = a[5]; 654 return out; 655} 656/** 657 * Set a mat2d to the identity matrix 658 * 659 * @param {mat2d} out the receiving matrix 660 * @returns {mat2d} out 661 */ 662 663function identity(out) { 664 out[0] = 1; 665 out[1] = 0; 666 out[2] = 0; 667 out[3] = 1; 668 out[4] = 0; 669 out[5] = 0; 670 return out; 671} 672/** 673 * Create a new mat2d with the given values 674 * 675 * @param {Number} a Component A (index 0) 676 * @param {Number} b Component B (index 1) 677 * @param {Number} c Component C (index 2) 678 * @param {Number} d Component D (index 3) 679 * @param {Number} tx Component TX (index 4) 680 * @param {Number} ty Component TY (index 5) 681 * @returns {mat2d} A new mat2d 682 */ 683 684function fromValues(a, b, c, d, tx, ty) { 685 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(6); 686 out[0] = a; 687 out[1] = b; 688 out[2] = c; 689 out[3] = d; 690 out[4] = tx; 691 out[5] = ty; 692 return out; 693} 694/** 695 * Set the components of a mat2d to the given values 696 * 697 * @param {mat2d} out the receiving matrix 698 * @param {Number} a Component A (index 0) 699 * @param {Number} b Component B (index 1) 700 * @param {Number} c Component C (index 2) 701 * @param {Number} d Component D (index 3) 702 * @param {Number} tx Component TX (index 4) 703 * @param {Number} ty Component TY (index 5) 704 * @returns {mat2d} out 705 */ 706 707function set(out, a, b, c, d, tx, ty) { 708 out[0] = a; 709 out[1] = b; 710 out[2] = c; 711 out[3] = d; 712 out[4] = tx; 713 out[5] = ty; 714 return out; 715} 716/** 717 * Inverts a mat2d 718 * 719 * @param {mat2d} out the receiving matrix 720 * @param {mat2d} a the source matrix 721 * @returns {mat2d} out 722 */ 723 724function invert(out, a) { 725 var aa = a[0], 726 ab = a[1], 727 ac = a[2], 728 ad = a[3]; 729 var atx = a[4], 730 aty = a[5]; 731 var det = aa * ad - ab * ac; 732 733 if (!det) { 734 return null; 735 } 736 737 det = 1.0 / det; 738 out[0] = ad * det; 739 out[1] = -ab * det; 740 out[2] = -ac * det; 741 out[3] = aa * det; 742 out[4] = (ac * aty - ad * atx) * det; 743 out[5] = (ab * atx - aa * aty) * det; 744 return out; 745} 746/** 747 * Calculates the determinant of a mat2d 748 * 749 * @param {mat2d} a the source matrix 750 * @returns {Number} determinant of a 751 */ 752 753function determinant(a) { 754 return a[0] * a[3] - a[1] * a[2]; 755} 756/** 757 * Multiplies two mat2d's 758 * 759 * @param {mat2d} out the receiving matrix 760 * @param {mat2d} a the first operand 761 * @param {mat2d} b the second operand 762 * @returns {mat2d} out 763 */ 764 765function multiply(out, a, b) { 766 var a0 = a[0], 767 a1 = a[1], 768 a2 = a[2], 769 a3 = a[3], 770 a4 = a[4], 771 a5 = a[5]; 772 var b0 = b[0], 773 b1 = b[1], 774 b2 = b[2], 775 b3 = b[3], 776 b4 = b[4], 777 b5 = b[5]; 778 out[0] = a0 * b0 + a2 * b1; 779 out[1] = a1 * b0 + a3 * b1; 780 out[2] = a0 * b2 + a2 * b3; 781 out[3] = a1 * b2 + a3 * b3; 782 out[4] = a0 * b4 + a2 * b5 + a4; 783 out[5] = a1 * b4 + a3 * b5 + a5; 784 return out; 785} 786/** 787 * Rotates a mat2d by the given angle 788 * 789 * @param {mat2d} out the receiving matrix 790 * @param {mat2d} a the matrix to rotate 791 * @param {Number} rad the angle to rotate the matrix by 792 * @returns {mat2d} out 793 */ 794 795function rotate(out, a, rad) { 796 var a0 = a[0], 797 a1 = a[1], 798 a2 = a[2], 799 a3 = a[3], 800 a4 = a[4], 801 a5 = a[5]; 802 var s = Math.sin(rad); 803 var c = Math.cos(rad); 804 out[0] = a0 * c + a2 * s; 805 out[1] = a1 * c + a3 * s; 806 out[2] = a0 * -s + a2 * c; 807 out[3] = a1 * -s + a3 * c; 808 out[4] = a4; 809 out[5] = a5; 810 return out; 811} 812/** 813 * Scales the mat2d by the dimensions in the given vec2 814 * 815 * @param {mat2d} out the receiving matrix 816 * @param {mat2d} a the matrix to translate 817 * @param {vec2} v the vec2 to scale the matrix by 818 * @returns {mat2d} out 819 **/ 820 821function scale(out, a, v) { 822 var a0 = a[0], 823 a1 = a[1], 824 a2 = a[2], 825 a3 = a[3], 826 a4 = a[4], 827 a5 = a[5]; 828 var v0 = v[0], 829 v1 = v[1]; 830 out[0] = a0 * v0; 831 out[1] = a1 * v0; 832 out[2] = a2 * v1; 833 out[3] = a3 * v1; 834 out[4] = a4; 835 out[5] = a5; 836 return out; 837} 838/** 839 * Translates the mat2d by the dimensions in the given vec2 840 * 841 * @param {mat2d} out the receiving matrix 842 * @param {mat2d} a the matrix to translate 843 * @param {vec2} v the vec2 to translate the matrix by 844 * @returns {mat2d} out 845 **/ 846 847function translate(out, a, v) { 848 var a0 = a[0], 849 a1 = a[1], 850 a2 = a[2], 851 a3 = a[3], 852 a4 = a[4], 853 a5 = a[5]; 854 var v0 = v[0], 855 v1 = v[1]; 856 out[0] = a0; 857 out[1] = a1; 858 out[2] = a2; 859 out[3] = a3; 860 out[4] = a0 * v0 + a2 * v1 + a4; 861 out[5] = a1 * v0 + a3 * v1 + a5; 862 return out; 863} 864/** 865 * Creates a matrix from a given angle 866 * This is equivalent to (but much faster than): 867 * 868 * mat2d.identity(dest); 869 * mat2d.rotate(dest, dest, rad); 870 * 871 * @param {mat2d} out mat2d receiving operation result 872 * @param {Number} rad the angle to rotate the matrix by 873 * @returns {mat2d} out 874 */ 875 876function fromRotation(out, rad) { 877 var s = Math.sin(rad), 878 c = Math.cos(rad); 879 out[0] = c; 880 out[1] = s; 881 out[2] = -s; 882 out[3] = c; 883 out[4] = 0; 884 out[5] = 0; 885 return out; 886} 887/** 888 * Creates a matrix from a vector scaling 889 * This is equivalent to (but much faster than): 890 * 891 * mat2d.identity(dest); 892 * mat2d.scale(dest, dest, vec); 893 * 894 * @param {mat2d} out mat2d receiving operation result 895 * @param {vec2} v Scaling vector 896 * @returns {mat2d} out 897 */ 898 899function fromScaling(out, v) { 900 out[0] = v[0]; 901 out[1] = 0; 902 out[2] = 0; 903 out[3] = v[1]; 904 out[4] = 0; 905 out[5] = 0; 906 return out; 907} 908/** 909 * Creates a matrix from a vector translation 910 * This is equivalent to (but much faster than): 911 * 912 * mat2d.identity(dest); 913 * mat2d.translate(dest, dest, vec); 914 * 915 * @param {mat2d} out mat2d receiving operation result 916 * @param {vec2} v Translation vector 917 * @returns {mat2d} out 918 */ 919 920function fromTranslation(out, v) { 921 out[0] = 1; 922 out[1] = 0; 923 out[2] = 0; 924 out[3] = 1; 925 out[4] = v[0]; 926 out[5] = v[1]; 927 return out; 928} 929/** 930 * Returns a string representation of a mat2d 931 * 932 * @param {mat2d} a matrix to represent as a string 933 * @returns {String} string representation of the matrix 934 */ 935 936function str(a) { 937 return 'mat2d(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ')'; 938} 939/** 940 * Returns Frobenius norm of a mat2d 941 * 942 * @param {mat2d} a the matrix to calculate Frobenius norm of 943 * @returns {Number} Frobenius norm 944 */ 945 946function frob(a) { 947 return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], 1); 948} 949/** 950 * Adds two mat2d's 951 * 952 * @param {mat2d} out the receiving matrix 953 * @param {mat2d} a the first operand 954 * @param {mat2d} b the second operand 955 * @returns {mat2d} out 956 */ 957 958function add(out, a, b) { 959 out[0] = a[0] + b[0]; 960 out[1] = a[1] + b[1]; 961 out[2] = a[2] + b[2]; 962 out[3] = a[3] + b[3]; 963 out[4] = a[4] + b[4]; 964 out[5] = a[5] + b[5]; 965 return out; 966} 967/** 968 * Subtracts matrix b from matrix a 969 * 970 * @param {mat2d} out the receiving matrix 971 * @param {mat2d} a the first operand 972 * @param {mat2d} b the second operand 973 * @returns {mat2d} out 974 */ 975 976function subtract(out, a, b) { 977 out[0] = a[0] - b[0]; 978 out[1] = a[1] - b[1]; 979 out[2] = a[2] - b[2]; 980 out[3] = a[3] - b[3]; 981 out[4] = a[4] - b[4]; 982 out[5] = a[5] - b[5]; 983 return out; 984} 985/** 986 * Multiply each element of the matrix by a scalar. 987 * 988 * @param {mat2d} out the receiving matrix 989 * @param {mat2d} a the matrix to scale 990 * @param {Number} b amount to scale the matrix's elements by 991 * @returns {mat2d} out 992 */ 993 994function multiplyScalar(out, a, b) { 995 out[0] = a[0] * b; 996 out[1] = a[1] * b; 997 out[2] = a[2] * b; 998 out[3] = a[3] * b; 999 out[4] = a[4] * b; 1000 out[5] = a[5] * b; 1001 return out; 1002} 1003/** 1004 * Adds two mat2d's after multiplying each element of the second operand by a scalar value. 1005 * 1006 * @param {mat2d} out the receiving vector 1007 * @param {mat2d} a the first operand 1008 * @param {mat2d} b the second operand 1009 * @param {Number} scale the amount to scale b's elements by before adding 1010 * @returns {mat2d} out 1011 */ 1012 1013function multiplyScalarAndAdd(out, a, b, scale) { 1014 out[0] = a[0] + b[0] * scale; 1015 out[1] = a[1] + b[1] * scale; 1016 out[2] = a[2] + b[2] * scale; 1017 out[3] = a[3] + b[3] * scale; 1018 out[4] = a[4] + b[4] * scale; 1019 out[5] = a[5] + b[5] * scale; 1020 return out; 1021} 1022/** 1023 * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) 1024 * 1025 * @param {mat2d} a The first matrix. 1026 * @param {mat2d} b The second matrix. 1027 * @returns {Boolean} True if the matrices are equal, false otherwise. 1028 */ 1029 1030function exactEquals(a, b) { 1031 return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5]; 1032} 1033/** 1034 * Returns whether or not the matrices have approximately the same elements in the same position. 1035 * 1036 * @param {mat2d} a The first matrix. 1037 * @param {mat2d} b The second matrix. 1038 * @returns {Boolean} True if the matrices are equal, false otherwise. 1039 */ 1040 1041function equals(a, b) { 1042 var a0 = a[0], 1043 a1 = a[1], 1044 a2 = a[2], 1045 a3 = a[3], 1046 a4 = a[4], 1047 a5 = a[5]; 1048 var b0 = b[0], 1049 b1 = b[1], 1050 b2 = b[2], 1051 b3 = b[3], 1052 b4 = b[4], 1053 b5 = b[5]; 1054 return Math.abs(a0 - b0) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)); 1055} 1056/** 1057 * Alias for {@link mat2d.multiply} 1058 * @function 1059 */ 1060 1061var mul = multiply; 1062/** 1063 * Alias for {@link mat2d.subtract} 1064 * @function 1065 */ 1066 1067var sub = subtract; 1068 1069/***/ }), 1070
vendor: 21,673 bytes, lines 1071-1895
1071/***/ "./node_modules/gl-matrix/esm/mat3.js": 1072/*!********************************************!*\ 1073 !*** ./node_modules/gl-matrix/esm/mat3.js ***! 1074 \********************************************/ 1075/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { 1076 1077"use strict"; 1078__webpack_require__.r(__webpack_exports__); 1079/* harmony export */ __webpack_require__.d(__webpack_exports__, { 1080/* harmony export */ add: () => (/* binding */ add), 1081/* harmony export */ adjoint: () => (/* binding */ adjoint), 1082/* harmony export */ clone: () => (/* binding */ clone), 1083/* harmony export */ copy: () => (/* binding */ copy), 1084/* harmony export */ create: () => (/* binding */ create), 1085/* harmony export */ determinant: () => (/* binding */ determinant), 1086/* harmony export */ equals: () => (/* binding */ equals), 1087/* harmony export */ exactEquals: () => (/* binding */ exactEquals), 1088/* harmony export */ frob: () => (/* binding */ frob), 1089/* harmony export */ fromMat2d: () => (/* binding */ fromMat2d), 1090/* harmony export */ fromMat4: () => (/* binding */ fromMat4), 1091/* harmony export */ fromQuat: () => (/* binding */ fromQuat), 1092/* harmony export */ fromRotation: () => (/* binding */ fromRotation), 1093/* harmony export */ fromScaling: () => (/* binding */ fromScaling), 1094/* harmony export */ fromTranslation: () => (/* binding */ fromTranslation), 1095/* harmony export */ fromValues: () => (/* binding */ fromValues), 1096/* harmony export */ identity: () => (/* binding */ identity), 1097/* harmony export */ invert: () => (/* binding */ invert), 1098/* harmony export */ mul: () => (/* binding */ mul), 1099/* harmony export */ multiply: () => (/* binding */ multiply), 1100/* harmony export */ multiplyScalar: () => (/* binding */ multiplyScalar), 1101/* harmony export */ multiplyScalarAndAdd: () => (/* binding */ multiplyScalarAndAdd), 1102/* harmony export */ normalFromMat4: () => (/* binding */ normalFromMat4), 1103/* harmony export */ projection: () => (/* binding */ projection), 1104/* harmony export */ rotate: () => (/* binding */ rotate), 1105/* harmony export */ scale: () => (/* binding */ scale), 1106/* harmony export */ set: () => (/* binding */ set), 1107/* harmony export */ str: () => (/* binding */ str), 1108/* harmony export */ sub: () => (/* binding */ sub), 1109/* harmony export */ subtract: () => (/* binding */ subtract), 1110/* harmony export */ translate: () => (/* binding */ translate), 1111/* harmony export */ transpose: () => (/* binding */ transpose) 1112/* harmony export */ }); 1113/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common.js */ "./node_modules/gl-matrix/esm/common.js"); 1114 1115/** 1116 * 3x3 Matrix 1117 * @module mat3 1118 */ 1119 1120/** 1121 * Creates a new identity mat3 1122 * 1123 * @returns {mat3} a new 3x3 matrix 1124 */ 1125 1126function create() { 1127 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(9); 1128 1129 if (_common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE != Float32Array) { 1130 out[1] = 0; 1131 out[2] = 0; 1132 out[3] = 0; 1133 out[5] = 0; 1134 out[6] = 0; 1135 out[7] = 0; 1136 } 1137 1138 out[0] = 1; 1139 out[4] = 1; 1140 out[8] = 1; 1141 return out; 1142} 1143/** 1144 * Copies the upper-left 3x3 values into the given mat3. 1145 * 1146 * @param {mat3} out the receiving 3x3 matrix 1147 * @param {mat4} a the source 4x4 matrix 1148 * @returns {mat3} out 1149 */ 1150 1151function fromMat4(out, a) { 1152 out[0] = a[0]; 1153 out[1] = a[1]; 1154 out[2] = a[2]; 1155 out[3] = a[4]; 1156 out[4] = a[5]; 1157 out[5] = a[6]; 1158 out[6] = a[8]; 1159 out[7] = a[9]; 1160 out[8] = a[10]; 1161 return out; 1162} 1163/** 1164 * Creates a new mat3 initialized with values from an existing matrix 1165 * 1166 * @param {mat3} a matrix to clone 1167 * @returns {mat3} a new 3x3 matrix 1168 */ 1169 1170function clone(a) { 1171 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(9); 1172 out[0] = a[0]; 1173 out[1] = a[1]; 1174 out[2] = a[2]; 1175 out[3] = a[3]; 1176 out[4] = a[4]; 1177 out[5] = a[5]; 1178 out[6] = a[6]; 1179 out[7] = a[7]; 1180 out[8] = a[8]; 1181 return out; 1182} 1183/** 1184 * Copy the values from one mat3 to another 1185 * 1186 * @param {mat3} out the receiving matrix 1187 * @param {mat3} a the source matrix 1188 * @returns {mat3} out 1189 */ 1190 1191function copy(out, a) { 1192 out[0] = a[0]; 1193 out[1] = a[1]; 1194 out[2] = a[2]; 1195 out[3] = a[3]; 1196 out[4] = a[4]; 1197 out[5] = a[5]; 1198 out[6] = a[6]; 1199 out[7] = a[7]; 1200 out[8] = a[8]; 1201 return out; 1202} 1203/** 1204 * Create a new mat3 with the given values 1205 * 1206 * @param {Number} m00 Component in column 0, row 0 position (index 0) 1207 * @param {Number} m01 Component in column 0, row 1 position (index 1) 1208 * @param {Number} m02 Component in column 0, row 2 position (index 2) 1209 * @param {Number} m10 Component in column 1, row 0 position (index 3) 1210 * @param {Number} m11 Component in column 1, row 1 position (index 4) 1211 * @param {Number} m12 Component in column 1, row 2 position (index 5) 1212 * @param {Number} m20 Component in column 2, row 0 position (index 6) 1213 * @param {Number} m21 Component in column 2, row 1 position (index 7) 1214 * @param {Number} m22 Component in column 2, row 2 position (index 8) 1215 * @returns {mat3} A new mat3 1216 */ 1217 1218function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) { 1219 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(9); 1220 out[0] = m00; 1221 out[1] = m01; 1222 out[2] = m02; 1223 out[3] = m10; 1224 out[4] = m11; 1225 out[5] = m12; 1226 out[6] = m20; 1227 out[7] = m21; 1228 out[8] = m22; 1229 return out; 1230} 1231/** 1232 * Set the components of a mat3 to the given values 1233 * 1234 * @param {mat3} out the receiving matrix 1235 * @param {Number} m00 Component in column 0, row 0 position (index 0) 1236 * @param {Number} m01 Component in column 0, row 1 position (index 1) 1237 * @param {Number} m02 Component in column 0, row 2 position (index 2) 1238 * @param {Number} m10 Component in column 1, row 0 position (index 3) 1239 * @param {Number} m11 Component in column 1, row 1 position (index 4) 1240 * @param {Number} m12 Component in column 1, row 2 position (index 5) 1241 * @param {Number} m20 Component in column 2, row 0 position (index 6) 1242 * @param {Number} m21 Component in column 2, row 1 position (index 7) 1243 * @param {Number} m22 Component in column 2, row 2 position (index 8) 1244 * @returns {mat3} out 1245 */ 1246 1247function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { 1248 out[0] = m00; 1249 out[1] = m01; 1250 out[2] = m02; 1251 out[3] = m10; 1252 out[4] = m11; 1253 out[5] = m12; 1254 out[6] = m20; 1255 out[7] = m21; 1256 out[8] = m22; 1257 return out; 1258} 1259/** 1260 * Set a mat3 to the identity matrix 1261 * 1262 * @param {mat3} out the receiving matrix 1263 * @returns {mat3} out 1264 */ 1265 1266function identity(out) { 1267 out[0] = 1; 1268 out[1] = 0; 1269 out[2] = 0; 1270 out[3] = 0; 1271 out[4] = 1; 1272 out[5] = 0; 1273 out[6] = 0; 1274 out[7] = 0; 1275 out[8] = 1; 1276 return out; 1277} 1278/** 1279 * Transpose the values of a mat3 1280 * 1281 * @param {mat3} out the receiving matrix 1282 * @param {mat3} a the source matrix 1283 * @returns {mat3} out 1284 */ 1285 1286function transpose(out, a) { 1287 // If we are transposing ourselves we can skip a few steps but have to cache some values 1288 if (out === a) { 1289 var a01 = a[1], 1290 a02 = a[2], 1291 a12 = a[5]; 1292 out[1] = a[3]; 1293 out[2] = a[6]; 1294 out[3] = a01; 1295 out[5] = a[7]; 1296 out[6] = a02; 1297 out[7] = a12; 1298 } else { 1299 out[0] = a[0]; 1300 out[1] = a[3]; 1301 out[2] = a[6]; 1302 out[3] = a[1]; 1303 out[4] = a[4]; 1304 out[5] = a[7]; 1305 out[6] = a[2]; 1306 out[7] = a[5]; 1307 out[8] = a[8]; 1308 } 1309 1310 return out; 1311} 1312/** 1313 * Inverts a mat3 1314 * 1315 * @param {mat3} out the receiving matrix 1316 * @param {mat3} a the source matrix 1317 * @returns {mat3} out 1318 */ 1319 1320function invert(out, a) { 1321 var a00 = a[0], 1322 a01 = a[1], 1323 a02 = a[2]; 1324 var a10 = a[3], 1325 a11 = a[4], 1326 a12 = a[5]; 1327 var a20 = a[6], 1328 a21 = a[7], 1329 a22 = a[8]; 1330 var b01 = a22 * a11 - a12 * a21; 1331 var b11 = -a22 * a10 + a12 * a20; 1332 var b21 = a21 * a10 - a11 * a20; // Calculate the determinant 1333 1334 var det = a00 * b01 + a01 * b11 + a02 * b21; 1335 1336 if (!det) { 1337 return null; 1338 } 1339 1340 det = 1.0 / det; 1341 out[0] = b01 * det; 1342 out[1] = (-a22 * a01 + a02 * a21) * det; 1343 out[2] = (a12 * a01 - a02 * a11) * det; 1344 out[3] = b11 * det; 1345 out[4] = (a22 * a00 - a02 * a20) * det; 1346 out[5] = (-a12 * a00 + a02 * a10) * det; 1347 out[6] = b21 * det; 1348 out[7] = (-a21 * a00 + a01 * a20) * det; 1349 out[8] = (a11 * a00 - a01 * a10) * det; 1350 return out; 1351} 1352/** 1353 * Calculates the adjugate of a mat3 1354 * 1355 * @param {mat3} out the receiving matrix 1356 * @param {mat3} a the source matrix 1357 * @returns {mat3} out 1358 */ 1359 1360function adjoint(out, a) { 1361 var a00 = a[0], 1362 a01 = a[1], 1363 a02 = a[2]; 1364 var a10 = a[3], 1365 a11 = a[4], 1366 a12 = a[5]; 1367 var a20 = a[6], 1368 a21 = a[7], 1369 a22 = a[8]; 1370 out[0] = a11 * a22 - a12 * a21; 1371 out[1] = a02 * a21 - a01 * a22; 1372 out[2] = a01 * a12 - a02 * a11; 1373 out[3] = a12 * a20 - a10 * a22; 1374 out[4] = a00 * a22 - a02 * a20; 1375 out[5] = a02 * a10 - a00 * a12; 1376 out[6] = a10 * a21 - a11 * a20; 1377 out[7] = a01 * a20 - a00 * a21; 1378 out[8] = a00 * a11 - a01 * a10; 1379 return out; 1380} 1381/** 1382 * Calculates the determinant of a mat3 1383 * 1384 * @param {mat3} a the source matrix 1385 * @returns {Number} determinant of a 1386 */ 1387 1388function determinant(a) { 1389 var a00 = a[0], 1390 a01 = a[1], 1391 a02 = a[2]; 1392 var a10 = a[3], 1393 a11 = a[4], 1394 a12 = a[5]; 1395 var a20 = a[6], 1396 a21 = a[7], 1397 a22 = a[8]; 1398 return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); 1399} 1400/** 1401 * Multiplies two mat3's 1402 * 1403 * @param {mat3} out the receiving matrix 1404 * @param {mat3} a the first operand 1405 * @param {mat3} b the second operand 1406 * @returns {mat3} out 1407 */ 1408 1409function multiply(out, a, b) { 1410 var a00 = a[0], 1411 a01 = a[1], 1412 a02 = a[2]; 1413 var a10 = a[3], 1414 a11 = a[4], 1415 a12 = a[5]; 1416 var a20 = a[6], 1417 a21 = a[7], 1418 a22 = a[8]; 1419 var b00 = b[0], 1420 b01 = b[1], 1421 b02 = b[2]; 1422 var b10 = b[3], 1423 b11 = b[4], 1424 b12 = b[5]; 1425 var b20 = b[6], 1426 b21 = b[7], 1427 b22 = b[8]; 1428 out[0] = b00 * a00 + b01 * a10 + b02 * a20; 1429 out[1] = b00 * a01 + b01 * a11 + b02 * a21; 1430 out[2] = b00 * a02 + b01 * a12 + b02 * a22; 1431 out[3] = b10 * a00 + b11 * a10 + b12 * a20; 1432 out[4] = b10 * a01 + b11 * a11 + b12 * a21; 1433 out[5] = b10 * a02 + b11 * a12 + b12 * a22; 1434 out[6] = b20 * a00 + b21 * a10 + b22 * a20; 1435 out[7] = b20 * a01 + b21 * a11 + b22 * a21; 1436 out[8] = b20 * a02 + b21 * a12 + b22 * a22; 1437 return out; 1438} 1439/** 1440 * Translate a mat3 by the given vector 1441 * 1442 * @param {mat3} out the receiving matrix 1443 * @param {mat3} a the matrix to translate 1444 * @param {vec2} v vector to translate by 1445 * @returns {mat3} out 1446 */ 1447 1448function translate(out, a, v) { 1449 var a00 = a[0], 1450 a01 = a[1], 1451 a02 = a[2], 1452 a10 = a[3], 1453 a11 = a[4], 1454 a12 = a[5], 1455 a20 = a[6], 1456 a21 = a[7], 1457 a22 = a[8], 1458 x = v[0], 1459 y = v[1]; 1460 out[0] = a00; 1461 out[1] = a01; 1462 out[2] = a02; 1463 out[3] = a10; 1464 out[4] = a11; 1465 out[5] = a12; 1466 out[6] = x * a00 + y * a10 + a20; 1467 out[7] = x * a01 + y * a11 + a21; 1468 out[8] = x * a02 + y * a12 + a22; 1469 return out; 1470} 1471/** 1472 * Rotates a mat3 by the given angle 1473 * 1474 * @param {mat3} out the receiving matrix 1475 * @param {mat3} a the matrix to rotate 1476 * @param {Number} rad the angle to rotate the matrix by 1477 * @returns {mat3} out 1478 */ 1479 1480function rotate(out, a, rad) { 1481 var a00 = a[0], 1482 a01 = a[1], 1483 a02 = a[2], 1484 a10 = a[3], 1485 a11 = a[4], 1486 a12 = a[5], 1487 a20 = a[6], 1488 a21 = a[7], 1489 a22 = a[8], 1490 s = Math.sin(rad), 1491 c = Math.cos(rad); 1492 out[0] = c * a00 + s * a10; 1493 out[1] = c * a01 + s * a11; 1494 out[2] = c * a02 + s * a12; 1495 out[3] = c * a10 - s * a00; 1496 out[4] = c * a11 - s * a01; 1497 out[5] = c * a12 - s * a02; 1498 out[6] = a20; 1499 out[7] = a21; 1500 out[8] = a22; 1501 return out; 1502} 1503; 1504/** 1505 * Scales the mat3 by the dimensions in the given vec2 1506 * 1507 * @param {mat3} out the receiving matrix 1508 * @param {mat3} a the matrix to rotate 1509 * @param {vec2} v the vec2 to scale the matrix by 1510 * @returns {mat3} out 1511 **/ 1512 1513function scale(out, a, v) { 1514 var x = v[0], 1515 y = v[1]; 1516 out[0] = x * a[0]; 1517 out[1] = x * a[1]; 1518 out[2] = x * a[2]; 1519 out[3] = y * a[3]; 1520 out[4] = y * a[4]; 1521 out[5] = y * a[5]; 1522 out[6] = a[6]; 1523 out[7] = a[7]; 1524 out[8] = a[8]; 1525 return out; 1526} 1527/** 1528 * Creates a matrix from a vector translation 1529 * This is equivalent to (but much faster than): 1530 * 1531 * mat3.identity(dest); 1532 * mat3.translate(dest, dest, vec); 1533 * 1534 * @param {mat3} out mat3 receiving operation result 1535 * @param {vec2} v Translation vector 1536 * @returns {mat3} out 1537 */ 1538 1539function fromTranslation(out, v) { 1540 out[0] = 1; 1541 out[1] = 0; 1542 out[2] = 0; 1543 out[3] = 0; 1544 out[4] = 1; 1545 out[5] = 0; 1546 out[6] = v[0]; 1547 out[7] = v[1]; 1548 out[8] = 1; 1549 return out; 1550} 1551/** 1552 * Creates a matrix from a given angle 1553 * This is equivalent to (but much faster than): 1554 * 1555 * mat3.identity(dest); 1556 * mat3.rotate(dest, dest, rad); 1557 * 1558 * @param {mat3} out mat3 receiving operation result 1559 * @param {Number} rad the angle to rotate the matrix by 1560 * @returns {mat3} out 1561 */ 1562 1563function fromRotation(out, rad) { 1564 var s = Math.sin(rad), 1565 c = Math.cos(rad); 1566 out[0] = c; 1567 out[1] = s; 1568 out[2] = 0; 1569 out[3] = -s; 1570 out[4] = c; 1571 out[5] = 0; 1572 out[6] = 0; 1573 out[7] = 0; 1574 out[8] = 1; 1575 return out; 1576} 1577/** 1578 * Creates a matrix from a vector scaling 1579 * This is equivalent to (but much faster than): 1580 * 1581 * mat3.identity(dest); 1582 * mat3.scale(dest, dest, vec); 1583 * 1584 * @param {mat3} out mat3 receiving operation result 1585 * @param {vec2} v Scaling vector 1586 * @returns {mat3} out 1587 */ 1588 1589function fromScaling(out, v) { 1590 out[0] = v[0]; 1591 out[1] = 0; 1592 out[2] = 0; 1593 out[3] = 0; 1594 out[4] = v[1]; 1595 out[5] = 0; 1596 out[6] = 0; 1597 out[7] = 0; 1598 out[8] = 1; 1599 return out; 1600} 1601/** 1602 * Copies the values from a mat2d into a mat3 1603 * 1604 * @param {mat3} out the receiving matrix 1605 * @param {mat2d} a the matrix to copy 1606 * @returns {mat3} out 1607 **/ 1608 1609function fromMat2d(out, a) { 1610 out[0] = a[0]; 1611 out[1] = a[1]; 1612 out[2] = 0; 1613 out[3] = a[2]; 1614 out[4] = a[3]; 1615 out[5] = 0; 1616 out[6] = a[4]; 1617 out[7] = a[5]; 1618 out[8] = 1; 1619 return out; 1620} 1621/** 1622* Calculates a 3x3 matrix from the given quaternion 1623* 1624* @param {mat3} out mat3 receiving operation result 1625* @param {quat} q Quaternion to create matrix from 1626* 1627* @returns {mat3} out 1628*/ 1629 1630function fromQuat(out, q) { 1631 var x = q[0], 1632 y = q[1], 1633 z = q[2], 1634 w = q[3]; 1635 var x2 = x + x; 1636 var y2 = y + y; 1637 var z2 = z + z; 1638 var xx = x * x2; 1639 var yx = y * x2; 1640 var yy = y * y2; 1641 var zx = z * x2; 1642 var zy = z * y2; 1643 var zz = z * z2; 1644 var wx = w * x2; 1645 var wy = w * y2; 1646 var wz = w * z2; 1647 out[0] = 1 - yy - zz; 1648 out[3] = yx - wz; 1649 out[6] = zx + wy; 1650 out[1] = yx + wz; 1651 out[4] = 1 - xx - zz; 1652 out[7] = zy - wx; 1653 out[2] = zx - wy; 1654 out[5] = zy + wx; 1655 out[8] = 1 - xx - yy; 1656 return out; 1657} 1658/** 1659* Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix 1660* 1661* @param {mat3} out mat3 receiving operation result 1662* @param {mat4} a Mat4 to derive the normal matrix from 1663* 1664* @returns {mat3} out 1665*/ 1666 1667function normalFromMat4(out, a) { 1668 var a00 = a[0], 1669 a01 = a[1], 1670 a02 = a[2], 1671 a03 = a[3]; 1672 var a10 = a[4], 1673 a11 = a[5], 1674 a12 = a[6], 1675 a13 = a[7]; 1676 var a20 = a[8], 1677 a21 = a[9], 1678 a22 = a[10], 1679 a23 = a[11]; 1680 var a30 = a[12], 1681 a31 = a[13], 1682 a32 = a[14], 1683 a33 = a[15]; 1684 var b00 = a00 * a11 - a01 * a10; 1685 var b01 = a00 * a12 - a02 * a10; 1686 var b02 = a00 * a13 - a03 * a10; 1687 var b03 = a01 * a12 - a02 * a11; 1688 var b04 = a01 * a13 - a03 * a11; 1689 var b05 = a02 * a13 - a03 * a12; 1690 var b06 = a20 * a31 - a21 * a30; 1691 var b07 = a20 * a32 - a22 * a30; 1692 var b08 = a20 * a33 - a23 * a30; 1693 var b09 = a21 * a32 - a22 * a31; 1694 var b10 = a21 * a33 - a23 * a31; 1695 var b11 = a22 * a33 - a23 * a32; // Calculate the determinant 1696 1697 var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; 1698 1699 if (!det) { 1700 return null; 1701 } 1702 1703 det = 1.0 / det; 1704 out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; 1705 out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; 1706 out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; 1707 out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; 1708 out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; 1709 out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; 1710 out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; 1711 out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; 1712 out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; 1713 return out; 1714} 1715/** 1716 * Generates a 2D projection matrix with the given bounds 1717 * 1718 * @param {mat3} out mat3 frustum matrix will be written into 1719 * @param {number} width Width of your gl context 1720 * @param {number} height Height of gl context 1721 * @returns {mat3} out 1722 */ 1723 1724function projection(out, width, height) { 1725 out[0] = 2 / width; 1726 out[1] = 0; 1727 out[2] = 0; 1728 out[3] = 0; 1729 out[4] = -2 / height; 1730 out[5] = 0; 1731 out[6] = -1; 1732 out[7] = 1; 1733 out[8] = 1; 1734 return out; 1735} 1736/** 1737 * Returns a string representation of a mat3 1738 * 1739 * @param {mat3} a matrix to represent as a string 1740 * @returns {String} string representation of the matrix 1741 */ 1742 1743function str(a) { 1744 return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + a[8] + ')'; 1745} 1746/** 1747 * Returns Frobenius norm of a mat3 1748 * 1749 * @param {mat3} a the matrix to calculate Frobenius norm of 1750 * @returns {Number} Frobenius norm 1751 */ 1752 1753function frob(a) { 1754 return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]); 1755} 1756/** 1757 * Adds two mat3's 1758 * 1759 * @param {mat3} out the receiving matrix 1760 * @param {mat3} a the first operand 1761 * @param {mat3} b the second operand 1762 * @returns {mat3} out 1763 */ 1764 1765function add(out, a, b) { 1766 out[0] = a[0] + b[0]; 1767 out[1] = a[1] + b[1]; 1768 out[2] = a[2] + b[2]; 1769 out[3] = a[3] + b[3]; 1770 out[4] = a[4] + b[4]; 1771 out[5] = a[5] + b[5]; 1772 out[6] = a[6] + b[6]; 1773 out[7] = a[7] + b[7]; 1774 out[8] = a[8] + b[8]; 1775 return out; 1776} 1777/** 1778 * Subtracts matrix b from matrix a 1779 * 1780 * @param {mat3} out the receiving matrix 1781 * @param {mat3} a the first operand 1782 * @param {mat3} b the second operand 1783 * @returns {mat3} out 1784 */ 1785 1786function subtract(out, a, b) { 1787 out[0] = a[0] - b[0]; 1788 out[1] = a[1] - b[1]; 1789 out[2] = a[2] - b[2]; 1790 out[3] = a[3] - b[3]; 1791 out[4] = a[4] - b[4]; 1792 out[5] = a[5] - b[5]; 1793 out[6] = a[6] - b[6]; 1794 out[7] = a[7] - b[7]; 1795 out[8] = a[8] - b[8]; 1796 return out; 1797} 1798/** 1799 * Multiply each element of the matrix by a scalar. 1800 * 1801 * @param {mat3} out the receiving matrix 1802 * @param {mat3} a the matrix to scale 1803 * @param {Number} b amount to scale the matrix's elements by 1804 * @returns {mat3} out 1805 */ 1806 1807function multiplyScalar(out, a, b) { 1808 out[0] = a[0] * b; 1809 out[1] = a[1] * b; 1810 out[2] = a[2] * b; 1811 out[3] = a[3] * b; 1812 out[4] = a[4] * b; 1813 out[5] = a[5] * b; 1814 out[6] = a[6] * b; 1815 out[7] = a[7] * b; 1816 out[8] = a[8] * b; 1817 return out; 1818} 1819/** 1820 * Adds two mat3's after multiplying each element of the second operand by a scalar value. 1821 * 1822 * @param {mat3} out the receiving vector 1823 * @param {mat3} a the first operand 1824 * @param {mat3} b the second operand 1825 * @param {Number} scale the amount to scale b's elements by before adding 1826 * @returns {mat3} out 1827 */ 1828 1829function multiplyScalarAndAdd(out, a, b, scale) { 1830 out[0] = a[0] + b[0] * scale; 1831 out[1] = a[1] + b[1] * scale; 1832 out[2] = a[2] + b[2] * scale; 1833 out[3] = a[3] + b[3] * scale; 1834 out[4] = a[4] + b[4] * scale; 1835 out[5] = a[5] + b[5] * scale; 1836 out[6] = a[6] + b[6] * scale; 1837 out[7] = a[7] + b[7] * scale; 1838 out[8] = a[8] + b[8] * scale; 1839 return out; 1840} 1841/** 1842 * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) 1843 * 1844 * @param {mat3} a The first matrix. 1845 * @param {mat3} b The second matrix. 1846 * @returns {Boolean} True if the matrices are equal, false otherwise. 1847 */ 1848 1849function exactEquals(a, b) { 1850 return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8]; 1851} 1852/** 1853 * Returns whether or not the matrices have approximately the same elements in the same position. 1854 * 1855 * @param {mat3} a The first matrix. 1856 * @param {mat3} b The second matrix. 1857 * @returns {Boolean} True if the matrices are equal, false otherwise. 1858 */ 1859 1860function equals(a, b) { 1861 var a0 = a[0], 1862 a1 = a[1], 1863 a2 = a[2], 1864 a3 = a[3], 1865 a4 = a[4], 1866 a5 = a[5], 1867 a6 = a[6], 1868 a7 = a[7], 1869 a8 = a[8]; 1870 var b0 = b[0], 1871 b1 = b[1], 1872 b2 = b[2], 1873 b3 = b[3], 1874 b4 = b[4], 1875 b5 = b[5], 1876 b6 = b[6], 1877 b7 = b[7], 1878 b8 = b[8]; 1879 return Math.abs(a0 - b0) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)); 1880} 1881/** 1882 * Alias for {@link mat3.multiply} 1883 * @function 1884 */ 1885 1886var mul = multiply; 1887/** 1888 * Alias for {@link mat3.subtract} 1889 * @function 1890 */ 1891 1892var sub = subtract; 1893 1894/***/ }), 1895
vendor: 52,338 bytes, lines 1896-3771
1896/***/ "./node_modules/gl-matrix/esm/mat4.js": 1897/*!********************************************!*\ 1898 !*** ./node_modules/gl-matrix/esm/mat4.js ***! 1899 \********************************************/ 1900/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { 1901 1902"use strict"; 1903__webpack_require__.r(__webpack_exports__); 1904/* harmony export */ __webpack_require__.d(__webpack_exports__, { 1905/* harmony export */ add: () => (/* binding */ add), 1906/* harmony export */ adjoint: () => (/* binding */ adjoint), 1907/* harmony export */ clone: () => (/* binding */ clone), 1908/* harmony export */ copy: () => (/* binding */ copy), 1909/* harmony export */ create: () => (/* binding */ create), 1910/* harmony export */ determinant: () => (/* binding */ determinant), 1911/* harmony export */ equals: () => (/* binding */ equals), 1912/* harmony export */ exactEquals: () => (/* binding */ exactEquals), 1913/* harmony export */ frob: () => (/* binding */ frob), 1914/* harmony export */ fromQuat: () => (/* binding */ fromQuat), 1915/* harmony export */ fromQuat2: () => (/* binding */ fromQuat2), 1916/* harmony export */ fromRotation: () => (/* binding */ fromRotation), 1917/* harmony export */ fromRotationTranslation: () => (/* binding */ fromRotationTranslation), 1918/* harmony export */ fromRotationTranslationScale: () => (/* binding */ fromRotationTranslationScale), 1919/* harmony export */ fromRotationTranslationScaleOrigin: () => (/* binding */ fromRotationTranslationScaleOrigin), 1920/* harmony export */ fromScaling: () => (/* binding */ fromScaling), 1921/* harmony export */ fromTranslation: () => (/* binding */ fromTranslation), 1922/* harmony export */ fromValues: () => (/* binding */ fromValues), 1923/* harmony export */ fromXRotation: () => (/* binding */ fromXRotation), 1924/* harmony export */ fromYRotation: () => (/* binding */ fromYRotation), 1925/* harmony export */ fromZRotation: () => (/* binding */ fromZRotation), 1926/* harmony export */ frustum: () => (/* binding */ frustum), 1927/* harmony export */ getRotation: () => (/* binding */ getRotation), 1928/* harmony export */ getScaling: () => (/* binding */ getScaling), 1929/* harmony export */ getTranslation: () => (/* binding */ getTranslation), 1930/* harmony export */ identity: () => (/* binding */ identity), 1931/* harmony export */ invert: () => (/* binding */ invert), 1932/* harmony export */ lookAt: () => (/* binding */ lookAt), 1933/* harmony export */ mul: () => (/* binding */ mul), 1934/* harmony export */ multiply: () => (/* binding */ multiply), 1935/* harmony export */ multiplyScalar: () => (/* binding */ multiplyScalar), 1936/* harmony export */ multiplyScalarAndAdd: () => (/* binding */ multiplyScalarAndAdd), 1937/* harmony export */ ortho: () => (/* binding */ ortho), 1938/* harmony export */ perspective: () => (/* binding */ perspective), 1939/* harmony export */ perspectiveFromFieldOfView: () => (/* binding */ perspectiveFromFieldOfView), 1940/* harmony export */ rotate: () => (/* binding */ rotate), 1941/* harmony export */ rotateX: () => (/* binding */ rotateX), 1942/* harmony export */ rotateY: () => (/* binding */ rotateY), 1943/* harmony export */ rotateZ: () => (/* binding */ rotateZ), 1944/* harmony export */ scale: () => (/* binding */ scale), 1945/* harmony export */ set: () => (/* binding */ set), 1946/* harmony export */ str: () => (/* binding */ str), 1947/* harmony export */ sub: () => (/* binding */ sub), 1948/* harmony export */ subtract: () => (/* binding */ subtract), 1949/* harmony export */ targetTo: () => (/* binding */ targetTo), 1950/* harmony export */ translate: () => (/* binding */ translate), 1951/* harmony export */ transpose: () => (/* binding */ transpose) 1952/* harmony export */ }); 1953/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common.js */ "./node_modules/gl-matrix/esm/common.js"); 1954 1955/** 1956 * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied. 1957 * @module mat4 1958 */ 1959 1960/** 1961 * Creates a new identity mat4 1962 * 1963 * @returns {mat4} a new 4x4 matrix 1964 */ 1965 1966function create() { 1967 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(16); 1968 1969 if (_common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE != Float32Array) { 1970 out[1] = 0; 1971 out[2] = 0; 1972 out[3] = 0; 1973 out[4] = 0; 1974 out[6] = 0; 1975 out[7] = 0; 1976 out[8] = 0; 1977 out[9] = 0; 1978 out[11] = 0; 1979 out[12] = 0; 1980 out[13] = 0; 1981 out[14] = 0; 1982 } 1983 1984 out[0] = 1; 1985 out[5] = 1; 1986 out[10] = 1; 1987 out[15] = 1; 1988 return out; 1989} 1990/** 1991 * Creates a new mat4 initialized with values from an existing matrix 1992 * 1993 * @param {mat4} a matrix to clone 1994 * @returns {mat4} a new 4x4 matrix 1995 */ 1996 1997function clone(a) { 1998 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(16); 1999 out[0] = a[0]; 2000 out[1] = a[1]; 2001 out[2] = a[2]; 2002 out[3] = a[3]; 2003 out[4] = a[4]; 2004 out[5] = a[5]; 2005 out[6] = a[6]; 2006 out[7] = a[7]; 2007 out[8] = a[8]; 2008 out[9] = a[9]; 2009 out[10] = a[10]; 2010 out[11] = a[11]; 2011 out[12] = a[12]; 2012 out[13] = a[13]; 2013 out[14] = a[14]; 2014 out[15] = a[15]; 2015 return out; 2016} 2017/** 2018 * Copy the values from one mat4 to another 2019 * 2020 * @param {mat4} out the receiving matrix 2021 * @param {mat4} a the source matrix 2022 * @returns {mat4} out 2023 */ 2024 2025function copy(out, a) { 2026 out[0] = a[0]; 2027 out[1] = a[1]; 2028 out[2] = a[2]; 2029 out[3] = a[3]; 2030 out[4] = a[4]; 2031 out[5] = a[5]; 2032 out[6] = a[6]; 2033 out[7] = a[7]; 2034 out[8] = a[8]; 2035 out[9] = a[9]; 2036 out[10] = a[10]; 2037 out[11] = a[11]; 2038 out[12] = a[12]; 2039 out[13] = a[13]; 2040 out[14] = a[14]; 2041 out[15] = a[15]; 2042 return out; 2043} 2044/** 2045 * Create a new mat4 with the given values 2046 * 2047 * @param {Number} m00 Component in column 0, row 0 position (index 0) 2048 * @param {Number} m01 Component in column 0, row 1 position (index 1) 2049 * @param {Number} m02 Component in column 0, row 2 position (index 2) 2050 * @param {Number} m03 Component in column 0, row 3 position (index 3) 2051 * @param {Number} m10 Component in column 1, row 0 position (index 4) 2052 * @param {Number} m11 Component in column 1, row 1 position (index 5) 2053 * @param {Number} m12 Component in column 1, row 2 position (index 6) 2054 * @param {Number} m13 Component in column 1, row 3 position (index 7) 2055 * @param {Number} m20 Component in column 2, row 0 position (index 8) 2056 * @param {Number} m21 Component in column 2, row 1 position (index 9) 2057 * @param {Number} m22 Component in column 2, row 2 position (index 10) 2058 * @param {Number} m23 Component in column 2, row 3 position (index 11) 2059 * @param {Number} m30 Component in column 3, row 0 position (index 12) 2060 * @param {Number} m31 Component in column 3, row 1 position (index 13) 2061 * @param {Number} m32 Component in column 3, row 2 position (index 14) 2062 * @param {Number} m33 Component in column 3, row 3 position (index 15) 2063 * @returns {mat4} A new mat4 2064 */ 2065 2066function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { 2067 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(16); 2068 out[0] = m00; 2069 out[1] = m01; 2070 out[2] = m02; 2071 out[3] = m03; 2072 out[4] = m10; 2073 out[5] = m11; 2074 out[6] = m12; 2075 out[7] = m13; 2076 out[8] = m20; 2077 out[9] = m21; 2078 out[10] = m22; 2079 out[11] = m23; 2080 out[12] = m30; 2081 out[13] = m31; 2082 out[14] = m32; 2083 out[15] = m33; 2084 return out; 2085} 2086/** 2087 * Set the components of a mat4 to the given values 2088 * 2089 * @param {mat4} out the receiving matrix 2090 * @param {Number} m00 Component in column 0, row 0 position (index 0) 2091 * @param {Number} m01 Component in column 0, row 1 position (index 1) 2092 * @param {Number} m02 Component in column 0, row 2 position (index 2) 2093 * @param {Number} m03 Component in column 0, row 3 position (index 3) 2094 * @param {Number} m10 Component in column 1, row 0 position (index 4) 2095 * @param {Number} m11 Component in column 1, row 1 position (index 5) 2096 * @param {Number} m12 Component in column 1, row 2 position (index 6) 2097 * @param {Number} m13 Component in column 1, row 3 position (index 7) 2098 * @param {Number} m20 Component in column 2, row 0 position (index 8) 2099 * @param {Number} m21 Component in column 2, row 1 position (index 9) 2100 * @param {Number} m22 Component in column 2, row 2 position (index 10) 2101 * @param {Number} m23 Component in column 2, row 3 position (index 11) 2102 * @param {Number} m30 Component in column 3, row 0 position (index 12) 2103 * @param {Number} m31 Component in column 3, row 1 position (index 13) 2104 * @param {Number} m32 Component in column 3, row 2 position (index 14) 2105 * @param {Number} m33 Component in column 3, row 3 position (index 15) 2106 * @returns {mat4} out 2107 */ 2108 2109function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) { 2110 out[0] = m00; 2111 out[1] = m01; 2112 out[2] = m02; 2113 out[3] = m03; 2114 out[4] = m10; 2115 out[5] = m11; 2116 out[6] = m12; 2117 out[7] = m13; 2118 out[8] = m20; 2119 out[9] = m21; 2120 out[10] = m22; 2121 out[11] = m23; 2122 out[12] = m30; 2123 out[13] = m31; 2124 out[14] = m32; 2125 out[15] = m33; 2126 return out; 2127} 2128/** 2129 * Set a mat4 to the identity matrix 2130 * 2131 * @param {mat4} out the receiving matrix 2132 * @returns {mat4} out 2133 */ 2134 2135function identity(out) { 2136 out[0] = 1; 2137 out[1] = 0; 2138 out[2] = 0; 2139 out[3] = 0; 2140 out[4] = 0; 2141 out[5] = 1; 2142 out[6] = 0; 2143 out[7] = 0; 2144 out[8] = 0; 2145 out[9] = 0; 2146 out[10] = 1; 2147 out[11] = 0; 2148 out[12] = 0; 2149 out[13] = 0; 2150 out[14] = 0; 2151 out[15] = 1; 2152 return out; 2153} 2154/** 2155 * Transpose the values of a mat4 2156 * 2157 * @param {mat4} out the receiving matrix 2158 * @param {mat4} a the source matrix 2159 * @returns {mat4} out 2160 */ 2161 2162function transpose(out, a) { 2163 // If we are transposing ourselves we can skip a few steps but have to cache some values 2164 if (out === a) { 2165 var a01 = a[1], 2166 a02 = a[2], 2167 a03 = a[3]; 2168 var a12 = a[6], 2169 a13 = a[7]; 2170 var a23 = a[11]; 2171 out[1] = a[4]; 2172 out[2] = a[8]; 2173 out[3] = a[12]; 2174 out[4] = a01; 2175 out[6] = a[9]; 2176 out[7] = a[13]; 2177 out[8] = a02; 2178 out[9] = a12; 2179 out[11] = a[14]; 2180 out[12] = a03; 2181 out[13] = a13; 2182 out[14] = a23; 2183 } else { 2184 out[0] = a[0]; 2185 out[1] = a[4]; 2186 out[2] = a[8]; 2187 out[3] = a[12]; 2188 out[4] = a[1]; 2189 out[5] = a[5]; 2190 out[6] = a[9]; 2191 out[7] = a[13]; 2192 out[8] = a[2]; 2193 out[9] = a[6]; 2194 out[10] = a[10]; 2195 out[11] = a[14]; 2196 out[12] = a[3]; 2197 out[13] = a[7]; 2198 out[14] = a[11]; 2199 out[15] = a[15]; 2200 } 2201 2202 return out; 2203} 2204/** 2205 * Inverts a mat4 2206 * 2207 * @param {mat4} out the receiving matrix 2208 * @param {mat4} a the source matrix 2209 * @returns {mat4} out 2210 */ 2211 2212function invert(out, a) { 2213 var a00 = a[0], 2214 a01 = a[1], 2215 a02 = a[2], 2216 a03 = a[3]; 2217 var a10 = a[4], 2218 a11 = a[5], 2219 a12 = a[6], 2220 a13 = a[7]; 2221 var a20 = a[8], 2222 a21 = a[9], 2223 a22 = a[10], 2224 a23 = a[11]; 2225 var a30 = a[12], 2226 a31 = a[13], 2227 a32 = a[14], 2228 a33 = a[15]; 2229 var b00 = a00 * a11 - a01 * a10; 2230 var b01 = a00 * a12 - a02 * a10; 2231 var b02 = a00 * a13 - a03 * a10; 2232 var b03 = a01 * a12 - a02 * a11; 2233 var b04 = a01 * a13 - a03 * a11; 2234 var b05 = a02 * a13 - a03 * a12; 2235 var b06 = a20 * a31 - a21 * a30; 2236 var b07 = a20 * a32 - a22 * a30; 2237 var b08 = a20 * a33 - a23 * a30; 2238 var b09 = a21 * a32 - a22 * a31; 2239 var b10 = a21 * a33 - a23 * a31; 2240 var b11 = a22 * a33 - a23 * a32; // Calculate the determinant 2241 2242 var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; 2243 2244 if (!det) { 2245 return null; 2246 } 2247 2248 det = 1.0 / det; 2249 out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; 2250 out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; 2251 out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; 2252 out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; 2253 out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; 2254 out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; 2255 out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; 2256 out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; 2257 out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; 2258 out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; 2259 out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; 2260 out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; 2261 out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; 2262 out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; 2263 out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; 2264 out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; 2265 return out; 2266} 2267/** 2268 * Calculates the adjugate of a mat4 2269 * 2270 * @param {mat4} out the receiving matrix 2271 * @param {mat4} a the source matrix 2272 * @returns {mat4} out 2273 */ 2274 2275function adjoint(out, a) { 2276 var a00 = a[0], 2277 a01 = a[1], 2278 a02 = a[2], 2279 a03 = a[3]; 2280 var a10 = a[4], 2281 a11 = a[5], 2282 a12 = a[6], 2283 a13 = a[7]; 2284 var a20 = a[8], 2285 a21 = a[9], 2286 a22 = a[10], 2287 a23 = a[11]; 2288 var a30 = a[12], 2289 a31 = a[13], 2290 a32 = a[14], 2291 a33 = a[15]; 2292 out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22); 2293 out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); 2294 out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12); 2295 out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); 2296 out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); 2297 out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22); 2298 out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); 2299 out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12); 2300 out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21); 2301 out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); 2302 out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11); 2303 out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); 2304 out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); 2305 out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21); 2306 out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); 2307 out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11); 2308 return out; 2309} 2310/** 2311 * Calculates the determinant of a mat4 2312 * 2313 * @param {mat4} a the source matrix 2314 * @returns {Number} determinant of a 2315 */ 2316 2317function determinant(a) { 2318 var a00 = a[0], 2319 a01 = a[1], 2320 a02 = a[2], 2321 a03 = a[3]; 2322 var a10 = a[4], 2323 a11 = a[5], 2324 a12 = a[6], 2325 a13 = a[7]; 2326 var a20 = a[8], 2327 a21 = a[9], 2328 a22 = a[10], 2329 a23 = a[11]; 2330 var a30 = a[12], 2331 a31 = a[13], 2332 a32 = a[14], 2333 a33 = a[15]; 2334 var b00 = a00 * a11 - a01 * a10; 2335 var b01 = a00 * a12 - a02 * a10; 2336 var b02 = a00 * a13 - a03 * a10; 2337 var b03 = a01 * a12 - a02 * a11; 2338 var b04 = a01 * a13 - a03 * a11; 2339 var b05 = a02 * a13 - a03 * a12; 2340 var b06 = a20 * a31 - a21 * a30; 2341 var b07 = a20 * a32 - a22 * a30; 2342 var b08 = a20 * a33 - a23 * a30; 2343 var b09 = a21 * a32 - a22 * a31; 2344 var b10 = a21 * a33 - a23 * a31; 2345 var b11 = a22 * a33 - a23 * a32; // Calculate the determinant 2346 2347 return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; 2348} 2349/** 2350 * Multiplies two mat4s 2351 * 2352 * @param {mat4} out the receiving matrix 2353 * @param {mat4} a the first operand 2354 * @param {mat4} b the second operand 2355 * @returns {mat4} out 2356 */ 2357 2358function multiply(out, a, b) { 2359 var a00 = a[0], 2360 a01 = a[1], 2361 a02 = a[2], 2362 a03 = a[3]; 2363 var a10 = a[4], 2364 a11 = a[5], 2365 a12 = a[6], 2366 a13 = a[7]; 2367 var a20 = a[8], 2368 a21 = a[9], 2369 a22 = a[10], 2370 a23 = a[11]; 2371 var a30 = a[12], 2372 a31 = a[13], 2373 a32 = a[14], 2374 a33 = a[15]; // Cache only the current line of the second matrix 2375 2376 var b0 = b[0], 2377 b1 = b[1], 2378 b2 = b[2], 2379 b3 = b[3]; 2380 out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; 2381 out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; 2382 out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; 2383 out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; 2384 b0 = b[4]; 2385 b1 = b[5]; 2386 b2 = b[6]; 2387 b3 = b[7]; 2388 out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; 2389 out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; 2390 out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; 2391 out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; 2392 b0 = b[8]; 2393 b1 = b[9]; 2394 b2 = b[10]; 2395 b3 = b[11]; 2396 out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; 2397 out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; 2398 out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; 2399 out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; 2400 b0 = b[12]; 2401 b1 = b[13]; 2402 b2 = b[14]; 2403 b3 = b[15]; 2404 out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; 2405 out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; 2406 out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; 2407 out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; 2408 return out; 2409} 2410/** 2411 * Translate a mat4 by the given vector 2412 * 2413 * @param {mat4} out the receiving matrix 2414 * @param {mat4} a the matrix to translate 2415 * @param {vec3} v vector to translate by 2416 * @returns {mat4} out 2417 */ 2418 2419function translate(out, a, v) { 2420 var x = v[0], 2421 y = v[1], 2422 z = v[2]; 2423 var a00, a01, a02, a03; 2424 var a10, a11, a12, a13; 2425 var a20, a21, a22, a23; 2426 2427 if (a === out) { 2428 out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; 2429 out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; 2430 out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; 2431 out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; 2432 } else { 2433 a00 = a[0]; 2434 a01 = a[1]; 2435 a02 = a[2]; 2436 a03 = a[3]; 2437 a10 = a[4]; 2438 a11 = a[5]; 2439 a12 = a[6]; 2440 a13 = a[7]; 2441 a20 = a[8]; 2442 a21 = a[9]; 2443 a22 = a[10]; 2444 a23 = a[11]; 2445 out[0] = a00; 2446 out[1] = a01; 2447 out[2] = a02; 2448 out[3] = a03; 2449 out[4] = a10; 2450 out[5] = a11; 2451 out[6] = a12; 2452 out[7] = a13; 2453 out[8] = a20; 2454 out[9] = a21; 2455 out[10] = a22; 2456 out[11] = a23; 2457 out[12] = a00 * x + a10 * y + a20 * z + a[12]; 2458 out[13] = a01 * x + a11 * y + a21 * z + a[13]; 2459 out[14] = a02 * x + a12 * y + a22 * z + a[14]; 2460 out[15] = a03 * x + a13 * y + a23 * z + a[15]; 2461 } 2462 2463 return out; 2464} 2465/** 2466 * Scales the mat4 by the dimensions in the given vec3 not using vectorization 2467 * 2468 * @param {mat4} out the receiving matrix 2469 * @param {mat4} a the matrix to scale 2470 * @param {vec3} v the vec3 to scale the matrix by 2471 * @returns {mat4} out 2472 **/ 2473 2474function scale(out, a, v) { 2475 var x = v[0], 2476 y = v[1], 2477 z = v[2]; 2478 out[0] = a[0] * x; 2479 out[1] = a[1] * x; 2480 out[2] = a[2] * x; 2481 out[3] = a[3] * x; 2482 out[4] = a[4] * y; 2483 out[5] = a[5] * y; 2484 out[6] = a[6] * y; 2485 out[7] = a[7] * y; 2486 out[8] = a[8] * z; 2487 out[9] = a[9] * z; 2488 out[10] = a[10] * z; 2489 out[11] = a[11] * z; 2490 out[12] = a[12]; 2491 out[13] = a[13]; 2492 out[14] = a[14]; 2493 out[15] = a[15]; 2494 return out; 2495} 2496/** 2497 * Rotates a mat4 by the given angle around the given axis 2498 * 2499 * @param {mat4} out the receiving matrix 2500 * @param {mat4} a the matrix to rotate 2501 * @param {Number} rad the angle to rotate the matrix by 2502 * @param {vec3} axis the axis to rotate around 2503 * @returns {mat4} out 2504 */ 2505 2506function rotate(out, a, rad, axis) { 2507 var x = axis[0], 2508 y = axis[1], 2509 z = axis[2]; 2510 var len = Math.hypot(x, y, z); 2511 var s, c, t; 2512 var a00, a01, a02, a03; 2513 var a10, a11, a12, a13; 2514 var a20, a21, a22, a23; 2515 var b00, b01, b02; 2516 var b10, b11, b12; 2517 var b20, b21, b22; 2518 2519 if (len < _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON) { 2520 return null; 2521 } 2522 2523 len = 1 / len; 2524 x *= len; 2525 y *= len; 2526 z *= len; 2527 s = Math.sin(rad); 2528 c = Math.cos(rad); 2529 t = 1 - c; 2530 a00 = a[0]; 2531 a01 = a[1]; 2532 a02 = a[2]; 2533 a03 = a[3]; 2534 a10 = a[4]; 2535 a11 = a[5]; 2536 a12 = a[6]; 2537 a13 = a[7]; 2538 a20 = a[8]; 2539 a21 = a[9]; 2540 a22 = a[10]; 2541 a23 = a[11]; // Construct the elements of the rotation matrix 2542 2543 b00 = x * x * t + c; 2544 b01 = y * x * t + z * s; 2545 b02 = z * x * t - y * s; 2546 b10 = x * y * t - z * s; 2547 b11 = y * y * t + c; 2548 b12 = z * y * t + x * s; 2549 b20 = x * z * t + y * s; 2550 b21 = y * z * t - x * s; 2551 b22 = z * z * t + c; // Perform rotation-specific matrix multiplication 2552 2553 out[0] = a00 * b00 + a10 * b01 + a20 * b02; 2554 out[1] = a01 * b00 + a11 * b01 + a21 * b02; 2555 out[2] = a02 * b00 + a12 * b01 + a22 * b02; 2556 out[3] = a03 * b00 + a13 * b01 + a23 * b02; 2557 out[4] = a00 * b10 + a10 * b11 + a20 * b12; 2558 out[5] = a01 * b10 + a11 * b11 + a21 * b12; 2559 out[6] = a02 * b10 + a12 * b11 + a22 * b12; 2560 out[7] = a03 * b10 + a13 * b11 + a23 * b12; 2561 out[8] = a00 * b20 + a10 * b21 + a20 * b22; 2562 out[9] = a01 * b20 + a11 * b21 + a21 * b22; 2563 out[10] = a02 * b20 + a12 * b21 + a22 * b22; 2564 out[11] = a03 * b20 + a13 * b21 + a23 * b22; 2565 2566 if (a !== out) { 2567 // If the source and destination differ, copy the unchanged last row 2568 out[12] = a[12]; 2569 out[13] = a[13]; 2570 out[14] = a[14]; 2571 out[15] = a[15]; 2572 } 2573 2574 return out; 2575} 2576/** 2577 * Rotates a matrix by the given angle around the X axis 2578 * 2579 * @param {mat4} out the receiving matrix 2580 * @param {mat4} a the matrix to rotate 2581 * @param {Number} rad the angle to rotate the matrix by 2582 * @returns {mat4} out 2583 */ 2584 2585function rotateX(out, a, rad) { 2586 var s = Math.sin(rad); 2587 var c = Math.cos(rad); 2588 var a10 = a[4]; 2589 var a11 = a[5]; 2590 var a12 = a[6]; 2591 var a13 = a[7]; 2592 var a20 = a[8]; 2593 var a21 = a[9]; 2594 var a22 = a[10]; 2595 var a23 = a[11]; 2596 2597 if (a !== out) { 2598 // If the source and destination differ, copy the unchanged rows 2599 out[0] = a[0]; 2600 out[1] = a[1]; 2601 out[2] = a[2]; 2602 out[3] = a[3]; 2603 out[12] = a[12]; 2604 out[13] = a[13]; 2605 out[14] = a[14]; 2606 out[15] = a[15]; 2607 } // Perform axis-specific matrix multiplication 2608 2609 2610 out[4] = a10 * c + a20 * s; 2611 out[5] = a11 * c + a21 * s; 2612 out[6] = a12 * c + a22 * s; 2613 out[7] = a13 * c + a23 * s; 2614 out[8] = a20 * c - a10 * s; 2615 out[9] = a21 * c - a11 * s; 2616 out[10] = a22 * c - a12 * s; 2617 out[11] = a23 * c - a13 * s; 2618 return out; 2619} 2620/** 2621 * Rotates a matrix by the given angle around the Y axis 2622 * 2623 * @param {mat4} out the receiving matrix 2624 * @param {mat4} a the matrix to rotate 2625 * @param {Number} rad the angle to rotate the matrix by 2626 * @returns {mat4} out 2627 */ 2628 2629function rotateY(out, a, rad) { 2630 var s = Math.sin(rad); 2631 var c = Math.cos(rad); 2632 var a00 = a[0]; 2633 var a01 = a[1]; 2634 var a02 = a[2]; 2635 var a03 = a[3]; 2636 var a20 = a[8]; 2637 var a21 = a[9]; 2638 var a22 = a[10]; 2639 var a23 = a[11]; 2640 2641 if (a !== out) { 2642 // If the source and destination differ, copy the unchanged rows 2643 out[4] = a[4]; 2644 out[5] = a[5]; 2645 out[6] = a[6]; 2646 out[7] = a[7]; 2647 out[12] = a[12]; 2648 out[13] = a[13]; 2649 out[14] = a[14]; 2650 out[15] = a[15]; 2651 } // Perform axis-specific matrix multiplication 2652 2653 2654 out[0] = a00 * c - a20 * s; 2655 out[1] = a01 * c - a21 * s; 2656 out[2] = a02 * c - a22 * s; 2657 out[3] = a03 * c - a23 * s; 2658 out[8] = a00 * s + a20 * c; 2659 out[9] = a01 * s + a21 * c; 2660 out[10] = a02 * s + a22 * c; 2661 out[11] = a03 * s + a23 * c; 2662 return out; 2663} 2664/** 2665 * Rotates a matrix by the given angle around the Z axis 2666 * 2667 * @param {mat4} out the receiving matrix 2668 * @param {mat4} a the matrix to rotate 2669 * @param {Number} rad the angle to rotate the matrix by 2670 * @returns {mat4} out 2671 */ 2672 2673function rotateZ(out, a, rad) { 2674 var s = Math.sin(rad); 2675 var c = Math.cos(rad); 2676 var a00 = a[0]; 2677 var a01 = a[1]; 2678 var a02 = a[2]; 2679 var a03 = a[3]; 2680 var a10 = a[4]; 2681 var a11 = a[5]; 2682 var a12 = a[6]; 2683 var a13 = a[7]; 2684 2685 if (a !== out) { 2686 // If the source and destination differ, copy the unchanged last row 2687 out[8] = a[8]; 2688 out[9] = a[9]; 2689 out[10] = a[10]; 2690 out[11] = a[11]; 2691 out[12] = a[12]; 2692 out[13] = a[13]; 2693 out[14] = a[14]; 2694 out[15] = a[15]; 2695 } // Perform axis-specific matrix multiplication 2696 2697 2698 out[0] = a00 * c + a10 * s; 2699 out[1] = a01 * c + a11 * s; 2700 out[2] = a02 * c + a12 * s; 2701 out[3] = a03 * c + a13 * s; 2702 out[4] = a10 * c - a00 * s; 2703 out[5] = a11 * c - a01 * s; 2704 out[6] = a12 * c - a02 * s; 2705 out[7] = a13 * c - a03 * s; 2706 return out; 2707} 2708/** 2709 * Creates a matrix from a vector translation 2710 * This is equivalent to (but much faster than): 2711 * 2712 * mat4.identity(dest); 2713 * mat4.translate(dest, dest, vec); 2714 * 2715 * @param {mat4} out mat4 receiving operation result 2716 * @param {vec3} v Translation vector 2717 * @returns {mat4} out 2718 */ 2719 2720function fromTranslation(out, v) { 2721 out[0] = 1; 2722 out[1] = 0; 2723 out[2] = 0; 2724 out[3] = 0; 2725 out[4] = 0; 2726 out[5] = 1; 2727 out[6] = 0; 2728 out[7] = 0; 2729 out[8] = 0; 2730 out[9] = 0; 2731 out[10] = 1; 2732 out[11] = 0; 2733 out[12] = v[0]; 2734 out[13] = v[1]; 2735 out[14] = v[2]; 2736 out[15] = 1; 2737 return out; 2738} 2739/** 2740 * Creates a matrix from a vector scaling 2741 * This is equivalent to (but much faster than): 2742 * 2743 * mat4.identity(dest); 2744 * mat4.scale(dest, dest, vec); 2745 * 2746 * @param {mat4} out mat4 receiving operation result 2747 * @param {vec3} v Scaling vector 2748 * @returns {mat4} out 2749 */ 2750 2751function fromScaling(out, v) { 2752 out[0] = v[0]; 2753 out[1] = 0; 2754 out[2] = 0; 2755 out[3] = 0; 2756 out[4] = 0; 2757 out[5] = v[1]; 2758 out[6] = 0; 2759 out[7] = 0; 2760 out[8] = 0; 2761 out[9] = 0; 2762 out[10] = v[2]; 2763 out[11] = 0; 2764 out[12] = 0; 2765 out[13] = 0; 2766 out[14] = 0; 2767 out[15] = 1; 2768 return out; 2769} 2770/** 2771 * Creates a matrix from a given angle around a given axis 2772 * This is equivalent to (but much faster than): 2773 * 2774 * mat4.identity(dest); 2775 * mat4.rotate(dest, dest, rad, axis); 2776 * 2777 * @param {mat4} out mat4 receiving operation result 2778 * @param {Number} rad the angle to rotate the matrix by 2779 * @param {vec3} axis the axis to rotate around 2780 * @returns {mat4} out 2781 */ 2782 2783function fromRotation(out, rad, axis) { 2784 var x = axis[0], 2785 y = axis[1], 2786 z = axis[2]; 2787 var len = Math.hypot(x, y, z); 2788 var s, c, t; 2789 2790 if (len < _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON) { 2791 return null; 2792 } 2793 2794 len = 1 / len; 2795 x *= len; 2796 y *= len; 2797 z *= len; 2798 s = Math.sin(rad); 2799 c = Math.cos(rad); 2800 t = 1 - c; // Perform rotation-specific matrix multiplication 2801 2802 out[0] = x * x * t + c; 2803 out[1] = y * x * t + z * s; 2804 out[2] = z * x * t - y * s; 2805 out[3] = 0; 2806 out[4] = x * y * t - z * s; 2807 out[5] = y * y * t + c; 2808 out[6] = z * y * t + x * s; 2809 out[7] = 0; 2810 out[8] = x * z * t + y * s; 2811 out[9] = y * z * t - x * s; 2812 out[10] = z * z * t + c; 2813 out[11] = 0; 2814 out[12] = 0; 2815 out[13] = 0; 2816 out[14] = 0; 2817 out[15] = 1; 2818 return out; 2819} 2820/** 2821 * Creates a matrix from the given angle around the X axis 2822 * This is equivalent to (but much faster than): 2823 * 2824 * mat4.identity(dest); 2825 * mat4.rotateX(dest, dest, rad); 2826 * 2827 * @param {mat4} out mat4 receiving operation result 2828 * @param {Number} rad the angle to rotate the matrix by 2829 * @returns {mat4} out 2830 */ 2831 2832function fromXRotation(out, rad) { 2833 var s = Math.sin(rad); 2834 var c = Math.cos(rad); // Perform axis-specific matrix multiplication 2835 2836 out[0] = 1; 2837 out[1] = 0; 2838 out[2] = 0; 2839 out[3] = 0; 2840 out[4] = 0; 2841 out[5] = c; 2842 out[6] = s; 2843 out[7] = 0; 2844 out[8] = 0; 2845 out[9] = -s; 2846 out[10] = c; 2847 out[11] = 0; 2848 out[12] = 0; 2849 out[13] = 0; 2850 out[14] = 0; 2851 out[15] = 1; 2852 return out; 2853} 2854/** 2855 * Creates a matrix from the given angle around the Y axis 2856 * This is equivalent to (but much faster than): 2857 * 2858 * mat4.identity(dest); 2859 * mat4.rotateY(dest, dest, rad); 2860 * 2861 * @param {mat4} out mat4 receiving operation result 2862 * @param {Number} rad the angle to rotate the matrix by 2863 * @returns {mat4} out 2864 */ 2865 2866function fromYRotation(out, rad) { 2867 var s = Math.sin(rad); 2868 var c = Math.cos(rad); // Perform axis-specific matrix multiplication 2869 2870 out[0] = c; 2871 out[1] = 0; 2872 out[2] = -s; 2873 out[3] = 0; 2874 out[4] = 0; 2875 out[5] = 1; 2876 out[6] = 0; 2877 out[7] = 0; 2878 out[8] = s; 2879 out[9] = 0; 2880 out[10] = c; 2881 out[11] = 0; 2882 out[12] = 0; 2883 out[13] = 0; 2884 out[14] = 0; 2885 out[15] = 1; 2886 return out; 2887} 2888/** 2889 * Creates a matrix from the given angle around the Z axis 2890 * This is equivalent to (but much faster than): 2891 * 2892 * mat4.identity(dest); 2893 * mat4.rotateZ(dest, dest, rad); 2894 * 2895 * @param {mat4} out mat4 receiving operation result 2896 * @param {Number} rad the angle to rotate the matrix by 2897 * @returns {mat4} out 2898 */ 2899 2900function fromZRotation(out, rad) { 2901 var s = Math.sin(rad); 2902 var c = Math.cos(rad); // Perform axis-specific matrix multiplication 2903 2904 out[0] = c; 2905 out[1] = s; 2906 out[2] = 0; 2907 out[3] = 0; 2908 out[4] = -s; 2909 out[5] = c; 2910 out[6] = 0; 2911 out[7] = 0; 2912 out[8] = 0; 2913 out[9] = 0; 2914 out[10] = 1; 2915 out[11] = 0; 2916 out[12] = 0; 2917 out[13] = 0; 2918 out[14] = 0; 2919 out[15] = 1; 2920 return out; 2921} 2922/** 2923 * Creates a matrix from a quaternion rotation and vector translation 2924 * This is equivalent to (but much faster than): 2925 * 2926 * mat4.identity(dest); 2927 * mat4.translate(dest, vec); 2928 * let quatMat = mat4.create(); 2929 * quat4.toMat4(quat, quatMat); 2930 * mat4.multiply(dest, quatMat); 2931 * 2932 * @param {mat4} out mat4 receiving operation result 2933 * @param {quat4} q Rotation quaternion 2934 * @param {vec3} v Translation vector 2935 * @returns {mat4} out 2936 */ 2937 2938function fromRotationTranslation(out, q, v) { 2939 // Quaternion math 2940 var x = q[0], 2941 y = q[1], 2942 z = q[2], 2943 w = q[3]; 2944 var x2 = x + x; 2945 var y2 = y + y; 2946 var z2 = z + z; 2947 var xx = x * x2; 2948 var xy = x * y2; 2949 var xz = x * z2; 2950 var yy = y * y2; 2951 var yz = y * z2; 2952 var zz = z * z2; 2953 var wx = w * x2; 2954 var wy = w * y2; 2955 var wz = w * z2; 2956 out[0] = 1 - (yy + zz); 2957 out[1] = xy + wz; 2958 out[2] = xz - wy; 2959 out[3] = 0; 2960 out[4] = xy - wz; 2961 out[5] = 1 - (xx + zz); 2962 out[6] = yz + wx; 2963 out[7] = 0; 2964 out[8] = xz + wy; 2965 out[9] = yz - wx; 2966 out[10] = 1 - (xx + yy); 2967 out[11] = 0; 2968 out[12] = v[0]; 2969 out[13] = v[1]; 2970 out[14] = v[2]; 2971 out[15] = 1; 2972 return out; 2973} 2974/** 2975 * Creates a new mat4 from a dual quat. 2976 * 2977 * @param {mat4} out Matrix 2978 * @param {quat2} a Dual Quaternion 2979 * @returns {mat4} mat4 receiving operation result 2980 */ 2981 2982function fromQuat2(out, a) { 2983 var translation = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(3); 2984 var bx = -a[0], 2985 by = -a[1], 2986 bz = -a[2], 2987 bw = a[3], 2988 ax = a[4], 2989 ay = a[5], 2990 az = a[6], 2991 aw = a[7]; 2992 var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense 2993 2994 if (magnitude > 0) { 2995 translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude; 2996 translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude; 2997 translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude; 2998 } else { 2999 translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2; 3000 translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2; 3001 translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2; 3002 } 3003 3004 fromRotationTranslation(out, a, translation); 3005 return out; 3006} 3007/** 3008 * Returns the translation vector component of a transformation 3009 * matrix. If a matrix is built with fromRotationTranslation, 3010 * the returned vector will be the same as the translation vector 3011 * originally supplied. 3012 * @param {vec3} out Vector to receive translation component 3013 * @param {mat4} mat Matrix to be decomposed (input) 3014 * @return {vec3} out 3015 */ 3016 3017function getTranslation(out, mat) { 3018 out[0] = mat[12]; 3019 out[1] = mat[13]; 3020 out[2] = mat[14]; 3021 return out; 3022} 3023/** 3024 * Returns the scaling factor component of a transformation 3025 * matrix. If a matrix is built with fromRotationTranslationScale 3026 * with a normalized Quaternion paramter, the returned vector will be 3027 * the same as the scaling vector 3028 * originally supplied. 3029 * @param {vec3} out Vector to receive scaling factor component 3030 * @param {mat4} mat Matrix to be decomposed (input) 3031 * @return {vec3} out 3032 */ 3033 3034function getScaling(out, mat) { 3035 var m11 = mat[0]; 3036 var m12 = mat[1]; 3037 var m13 = mat[2]; 3038 var m21 = mat[4]; 3039 var m22 = mat[5]; 3040 var m23 = mat[6]; 3041 var m31 = mat[8]; 3042 var m32 = mat[9]; 3043 var m33 = mat[10]; 3044 out[0] = Math.hypot(m11, m12, m13); 3045 out[1] = Math.hypot(m21, m22, m23); 3046 out[2] = Math.hypot(m31, m32, m33); 3047 return out; 3048} 3049/** 3050 * Returns a quaternion representing the rotational component 3051 * of a transformation matrix. If a matrix is built with 3052 * fromRotationTranslation, the returned quaternion will be the 3053 * same as the quaternion originally supplied. 3054 * @param {quat} out Quaternion to receive the rotation component 3055 * @param {mat4} mat Matrix to be decomposed (input) 3056 * @return {quat} out 3057 */ 3058 3059function getRotation(out, mat) { 3060 var scaling = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(3); 3061 getScaling(scaling, mat); 3062 var is1 = 1 / scaling[0]; 3063 var is2 = 1 / scaling[1]; 3064 var is3 = 1 / scaling[2]; 3065 var sm11 = mat[0] * is1; 3066 var sm12 = mat[1] * is2; 3067 var sm13 = mat[2] * is3; 3068 var sm21 = mat[4] * is1; 3069 var sm22 = mat[5] * is2; 3070 var sm23 = mat[6] * is3; 3071 var sm31 = mat[8] * is1; 3072 var sm32 = mat[9] * is2; 3073 var sm33 = mat[10] * is3; 3074 var trace = sm11 + sm22 + sm33; 3075 var S = 0; 3076 3077 if (trace > 0) { 3078 S = Math.sqrt(trace + 1.0) * 2; 3079 out[3] = 0.25 * S; 3080 out[0] = (sm23 - sm32) / S; 3081 out[1] = (sm31 - sm13) / S; 3082 out[2] = (sm12 - sm21) / S; 3083 } else if (sm11 > sm22 && sm11 > sm33) { 3084 S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2; 3085 out[3] = (sm23 - sm32) / S; 3086 out[0] = 0.25 * S; 3087 out[1] = (sm12 + sm21) / S; 3088 out[2] = (sm31 + sm13) / S; 3089 } else if (sm22 > sm33) { 3090 S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2; 3091 out[3] = (sm31 - sm13) / S; 3092 out[0] = (sm12 + sm21) / S; 3093 out[1] = 0.25 * S; 3094 out[2] = (sm23 + sm32) / S; 3095 } else { 3096 S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2; 3097 out[3] = (sm12 - sm21) / S; 3098 out[0] = (sm31 + sm13) / S; 3099 out[1] = (sm23 + sm32) / S; 3100 out[2] = 0.25 * S; 3101 } 3102 3103 return out; 3104} 3105/** 3106 * Creates a matrix from a quaternion rotation, vector translation and vector scale 3107 * This is equivalent to (but much faster than): 3108 * 3109 * mat4.identity(dest); 3110 * mat4.translate(dest, vec); 3111 * let quatMat = mat4.create(); 3112 * quat4.toMat4(quat, quatMat); 3113 * mat4.multiply(dest, quatMat); 3114 * mat4.scale(dest, scale) 3115 * 3116 * @param {mat4} out mat4 receiving operation result 3117 * @param {quat4} q Rotation quaternion 3118 * @param {vec3} v Translation vector 3119 * @param {vec3} s Scaling vector 3120 * @returns {mat4} out 3121 */ 3122 3123function fromRotationTranslationScale(out, q, v, s) { 3124 // Quaternion math 3125 var x = q[0], 3126 y = q[1], 3127 z = q[2], 3128 w = q[3]; 3129 var x2 = x + x; 3130 var y2 = y + y; 3131 var z2 = z + z; 3132 var xx = x * x2; 3133 var xy = x * y2; 3134 var xz = x * z2; 3135 var yy = y * y2; 3136 var yz = y * z2; 3137 var zz = z * z2; 3138 var wx = w * x2; 3139 var wy = w * y2; 3140 var wz = w * z2; 3141 var sx = s[0]; 3142 var sy = s[1]; 3143 var sz = s[2]; 3144 out[0] = (1 - (yy + zz)) * sx; 3145 out[1] = (xy + wz) * sx; 3146 out[2] = (xz - wy) * sx; 3147 out[3] = 0; 3148 out[4] = (xy - wz) * sy; 3149 out[5] = (1 - (xx + zz)) * sy; 3150 out[6] = (yz + wx) * sy; 3151 out[7] = 0; 3152 out[8] = (xz + wy) * sz; 3153 out[9] = (yz - wx) * sz; 3154 out[10] = (1 - (xx + yy)) * sz; 3155 out[11] = 0; 3156 out[12] = v[0]; 3157 out[13] = v[1]; 3158 out[14] = v[2]; 3159 out[15] = 1; 3160 return out; 3161} 3162/** 3163 * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin 3164 * This is equivalent to (but much faster than): 3165 * 3166 * mat4.identity(dest); 3167 * mat4.translate(dest, vec); 3168 * mat4.translate(dest, origin); 3169 * let quatMat = mat4.create(); 3170 * quat4.toMat4(quat, quatMat); 3171 * mat4.multiply(dest, quatMat); 3172 * mat4.scale(dest, scale) 3173 * mat4.translate(dest, negativeOrigin); 3174 * 3175 * @param {mat4} out mat4 receiving operation result 3176 * @param {quat4} q Rotation quaternion 3177 * @param {vec3} v Translation vector 3178 * @param {vec3} s Scaling vector 3179 * @param {vec3} o The origin vector around which to scale and rotate 3180 * @returns {mat4} out 3181 */ 3182 3183function fromRotationTranslationScaleOrigin(out, q, v, s, o) { 3184 // Quaternion math 3185 var x = q[0], 3186 y = q[1], 3187 z = q[2], 3188 w = q[3]; 3189 var x2 = x + x; 3190 var y2 = y + y; 3191 var z2 = z + z; 3192 var xx = x * x2; 3193 var xy = x * y2; 3194 var xz = x * z2; 3195 var yy = y * y2; 3196 var yz = y * z2; 3197 var zz = z * z2; 3198 var wx = w * x2; 3199 var wy = w * y2; 3200 var wz = w * z2; 3201 var sx = s[0]; 3202 var sy = s[1]; 3203 var sz = s[2]; 3204 var ox = o[0]; 3205 var oy = o[1]; 3206 var oz = o[2]; 3207 var out0 = (1 - (yy + zz)) * sx; 3208 var out1 = (xy + wz) * sx; 3209 var out2 = (xz - wy) * sx; 3210 var out4 = (xy - wz) * sy; 3211 var out5 = (1 - (xx + zz)) * sy; 3212 var out6 = (yz + wx) * sy; 3213 var out8 = (xz + wy) * sz; 3214 var out9 = (yz - wx) * sz; 3215 var out10 = (1 - (xx + yy)) * sz; 3216 out[0] = out0; 3217 out[1] = out1; 3218 out[2] = out2; 3219 out[3] = 0; 3220 out[4] = out4; 3221 out[5] = out5; 3222 out[6] = out6; 3223 out[7] = 0; 3224 out[8] = out8; 3225 out[9] = out9; 3226 out[10] = out10; 3227 out[11] = 0; 3228 out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz); 3229 out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz); 3230 out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz); 3231 out[15] = 1; 3232 return out; 3233} 3234/** 3235 * Calculates a 4x4 matrix from the given quaternion 3236 * 3237 * @param {mat4} out mat4 receiving operation result 3238 * @param {quat} q Quaternion to create matrix from 3239 * 3240 * @returns {mat4} out 3241 */ 3242 3243function fromQuat(out, q) { 3244 var x = q[0], 3245 y = q[1], 3246 z = q[2], 3247 w = q[3]; 3248 var x2 = x + x; 3249 var y2 = y + y; 3250 var z2 = z + z; 3251 var xx = x * x2; 3252 var yx = y * x2; 3253 var yy = y * y2; 3254 var zx = z * x2; 3255 var zy = z * y2; 3256 var zz = z * z2; 3257 var wx = w * x2; 3258 var wy = w * y2; 3259 var wz = w * z2; 3260 out[0] = 1 - yy - zz; 3261 out[1] = yx + wz; 3262 out[2] = zx - wy; 3263 out[3] = 0; 3264 out[4] = yx - wz; 3265 out[5] = 1 - xx - zz; 3266 out[6] = zy + wx; 3267 out[7] = 0; 3268 out[8] = zx + wy; 3269 out[9] = zy - wx; 3270 out[10] = 1 - xx - yy; 3271 out[11] = 0; 3272 out[12] = 0; 3273 out[13] = 0; 3274 out[14] = 0; 3275 out[15] = 1; 3276 return out; 3277} 3278/** 3279 * Generates a frustum matrix with the given bounds 3280 * 3281 * @param {mat4} out mat4 frustum matrix will be written into 3282 * @param {Number} left Left bound of the frustum 3283 * @param {Number} right Right bound of the frustum 3284 * @param {Number} bottom Bottom bound of the frustum 3285 * @param {Number} top Top bound of the frustum 3286 * @param {Number} near Near bound of the frustum 3287 * @param {Number} far Far bound of the frustum 3288 * @returns {mat4} out 3289 */ 3290 3291function frustum(out, left, right, bottom, top, near, far) { 3292 var rl = 1 / (right - left); 3293 var tb = 1 / (top - bottom); 3294 var nf = 1 / (near - far); 3295 out[0] = near * 2 * rl; 3296 out[1] = 0; 3297 out[2] = 0; 3298 out[3] = 0; 3299 out[4] = 0; 3300 out[5] = near * 2 * tb; 3301 out[6] = 0; 3302 out[7] = 0; 3303 out[8] = (right + left) * rl; 3304 out[9] = (top + bottom) * tb; 3305 out[10] = (far + near) * nf; 3306 out[11] = -1; 3307 out[12] = 0; 3308 out[13] = 0; 3309 out[14] = far * near * 2 * nf; 3310 out[15] = 0; 3311 return out; 3312} 3313/** 3314 * Generates a perspective projection matrix with the given bounds. 3315 * Passing null/undefined/no value for far will generate infinite projection matrix. 3316 * 3317 * @param {mat4} out mat4 frustum matrix will be written into 3318 * @param {number} fovy Vertical field of view in radians 3319 * @param {number} aspect Aspect ratio. typically viewport width/height 3320 * @param {number} near Near bound of the frustum 3321 * @param {number} far Far bound of the frustum, can be null or Infinity 3322 * @returns {mat4} out 3323 */ 3324 3325function perspective(out, fovy, aspect, near, far) { 3326 var f = 1.0 / Math.tan(fovy / 2), 3327 nf; 3328 out[0] = f / aspect; 3329 out[1] = 0; 3330 out[2] = 0; 3331 out[3] = 0; 3332 out[4] = 0; 3333 out[5] = f; 3334 out[6] = 0; 3335 out[7] = 0; 3336 out[8] = 0; 3337 out[9] = 0; 3338 out[11] = -1; 3339 out[12] = 0; 3340 out[13] = 0; 3341 out[15] = 0; 3342 3343 if (far != null && far !== Infinity) { 3344 nf = 1 / (near - far); 3345 out[10] = (far + near) * nf; 3346 out[14] = 2 * far * near * nf; 3347 } else { 3348 out[10] = -1; 3349 out[14] = -2 * near; 3350 } 3351 3352 return out; 3353} 3354/** 3355 * Generates a perspective projection matrix with the given field of view. 3356 * This is primarily useful for generating projection matrices to be used 3357 * with the still experiemental WebVR API. 3358 * 3359 * @param {mat4} out mat4 frustum matrix will be written into 3360 * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees 3361 * @param {number} near Near bound of the frustum 3362 * @param {number} far Far bound of the frustum 3363 * @returns {mat4} out 3364 */ 3365 3366function perspectiveFromFieldOfView(out, fov, near, far) { 3367 var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0); 3368 var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0); 3369 var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0); 3370 var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0); 3371 var xScale = 2.0 / (leftTan + rightTan); 3372 var yScale = 2.0 / (upTan + downTan); 3373 out[0] = xScale; 3374 out[1] = 0.0; 3375 out[2] = 0.0; 3376 out[3] = 0.0; 3377 out[4] = 0.0; 3378 out[5] = yScale; 3379 out[6] = 0.0; 3380 out[7] = 0.0; 3381 out[8] = -((leftTan - rightTan) * xScale * 0.5); 3382 out[9] = (upTan - downTan) * yScale * 0.5; 3383 out[10] = far / (near - far); 3384 out[11] = -1.0; 3385 out[12] = 0.0; 3386 out[13] = 0.0; 3387 out[14] = far * near / (near - far); 3388 out[15] = 0.0; 3389 return out; 3390} 3391/** 3392 * Generates a orthogonal projection matrix with the given bounds 3393 * 3394 * @param {mat4} out mat4 frustum matrix will be written into 3395 * @param {number} left Left bound of the frustum 3396 * @param {number} right Right bound of the frustum 3397 * @param {number} bottom Bottom bound of the frustum 3398 * @param {number} top Top bound of the frustum 3399 * @param {number} near Near bound of the frustum 3400 * @param {number} far Far bound of the frustum 3401 * @returns {mat4} out 3402 */ 3403 3404function ortho(out, left, right, bottom, top, near, far) { 3405 var lr = 1 / (left - right); 3406 var bt = 1 / (bottom - top); 3407 var nf = 1 / (near - far); 3408 out[0] = -2 * lr; 3409 out[1] = 0; 3410 out[2] = 0; 3411 out[3] = 0; 3412 out[4] = 0; 3413 out[5] = -2 * bt; 3414 out[6] = 0; 3415 out[7] = 0; 3416 out[8] = 0; 3417 out[9] = 0; 3418 out[10] = 2 * nf; 3419 out[11] = 0; 3420 out[12] = (left + right) * lr; 3421 out[13] = (top + bottom) * bt; 3422 out[14] = (far + near) * nf; 3423 out[15] = 1; 3424 return out; 3425} 3426/** 3427 * Generates a look-at matrix with the given eye position, focal point, and up axis. 3428 * If you want a matrix that actually makes an object look at another object, you should use targetTo instead. 3429 * 3430 * @param {mat4} out mat4 frustum matrix will be written into 3431 * @param {vec3} eye Position of the viewer 3432 * @param {vec3} center Point the viewer is looking at 3433 * @param {vec3} up vec3 pointing up 3434 * @returns {mat4} out 3435 */ 3436 3437function lookAt(out, eye, center, up) { 3438 var x0, x1, x2, y0, y1, y2, z0, z1, z2, len; 3439 var eyex = eye[0]; 3440 var eyey = eye[1]; 3441 var eyez = eye[2]; 3442 var upx = up[0]; 3443 var upy = up[1]; 3444 var upz = up[2]; 3445 var centerx = center[0]; 3446 var centery = center[1]; 3447 var centerz = center[2]; 3448 3449 if (Math.abs(eyex - centerx) < _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON && Math.abs(eyey - centery) < _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON && Math.abs(eyez - centerz) < _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON) { 3450 return identity(out); 3451 } 3452 3453 z0 = eyex - centerx; 3454 z1 = eyey - centery; 3455 z2 = eyez - centerz; 3456 len = 1 / Math.hypot(z0, z1, z2); 3457 z0 *= len; 3458 z1 *= len; 3459 z2 *= len; 3460 x0 = upy * z2 - upz * z1; 3461 x1 = upz * z0 - upx * z2; 3462 x2 = upx * z1 - upy * z0; 3463 len = Math.hypot(x0, x1, x2); 3464 3465 if (!len) { 3466 x0 = 0; 3467 x1 = 0; 3468 x2 = 0; 3469 } else { 3470 len = 1 / len; 3471 x0 *= len; 3472 x1 *= len; 3473 x2 *= len; 3474 } 3475 3476 y0 = z1 * x2 - z2 * x1; 3477 y1 = z2 * x0 - z0 * x2; 3478 y2 = z0 * x1 - z1 * x0; 3479 len = Math.hypot(y0, y1, y2); 3480 3481 if (!len) { 3482 y0 = 0; 3483 y1 = 0; 3484 y2 = 0; 3485 } else { 3486 len = 1 / len; 3487 y0 *= len; 3488 y1 *= len; 3489 y2 *= len; 3490 } 3491 3492 out[0] = x0; 3493 out[1] = y0; 3494 out[2] = z0; 3495 out[3] = 0; 3496 out[4] = x1; 3497 out[5] = y1; 3498 out[6] = z1; 3499 out[7] = 0; 3500 out[8] = x2; 3501 out[9] = y2; 3502 out[10] = z2; 3503 out[11] = 0; 3504 out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); 3505 out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); 3506 out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); 3507 out[15] = 1; 3508 return out; 3509} 3510/** 3511 * Generates a matrix that makes something look at something else. 3512 * 3513 * @param {mat4} out mat4 frustum matrix will be written into 3514 * @param {vec3} eye Position of the viewer 3515 * @param {vec3} center Point the viewer is looking at 3516 * @param {vec3} up vec3 pointing up 3517 * @returns {mat4} out 3518 */ 3519 3520function targetTo(out, eye, target, up) { 3521 var eyex = eye[0], 3522 eyey = eye[1], 3523 eyez = eye[2], 3524 upx = up[0], 3525 upy = up[1], 3526 upz = up[2]; 3527 var z0 = eyex - target[0], 3528 z1 = eyey - target[1], 3529 z2 = eyez - target[2]; 3530 var len = z0 * z0 + z1 * z1 + z2 * z2; 3531 3532 if (len > 0) { 3533 len = 1 / Math.sqrt(len); 3534 z0 *= len; 3535 z1 *= len; 3536 z2 *= len; 3537 } 3538 3539 var x0 = upy * z2 - upz * z1, 3540 x1 = upz * z0 - upx * z2, 3541 x2 = upx * z1 - upy * z0; 3542 len = x0 * x0 + x1 * x1 + x2 * x2; 3543 3544 if (len > 0) { 3545 len = 1 / Math.sqrt(len); 3546 x0 *= len; 3547 x1 *= len; 3548 x2 *= len; 3549 } 3550 3551 out[0] = x0; 3552 out[1] = x1; 3553 out[2] = x2; 3554 out[3] = 0; 3555 out[4] = z1 * x2 - z2 * x1; 3556 out[5] = z2 * x0 - z0 * x2; 3557 out[6] = z0 * x1 - z1 * x0; 3558 out[7] = 0; 3559 out[8] = z0; 3560 out[9] = z1; 3561 out[10] = z2; 3562 out[11] = 0; 3563 out[12] = eyex; 3564 out[13] = eyey; 3565 out[14] = eyez; 3566 out[15] = 1; 3567 return out; 3568} 3569; 3570/** 3571 * Returns a string representation of a mat4 3572 * 3573 * @param {mat4} a matrix to represent as a string 3574 * @returns {String} string representation of the matrix 3575 */ 3576 3577function str(a) { 3578 return 'mat4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + a[8] + ', ' + a[9] + ', ' + a[10] + ', ' + a[11] + ', ' + a[12] + ', ' + a[13] + ', ' + a[14] + ', ' + a[15] + ')'; 3579} 3580/** 3581 * Returns Frobenius norm of a mat4 3582 * 3583 * @param {mat4} a the matrix to calculate Frobenius norm of 3584 * @returns {Number} Frobenius norm 3585 */ 3586 3587function frob(a) { 3588 return Math.hypot(a[0], a[1], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); 3589} 3590/** 3591 * Adds two mat4's 3592 * 3593 * @param {mat4} out the receiving matrix 3594 * @param {mat4} a the first operand 3595 * @param {mat4} b the second operand 3596 * @returns {mat4} out 3597 */ 3598 3599function add(out, a, b) { 3600 out[0] = a[0] + b[0]; 3601 out[1] = a[1] + b[1]; 3602 out[2] = a[2] + b[2]; 3603 out[3] = a[3] + b[3]; 3604 out[4] = a[4] + b[4]; 3605 out[5] = a[5] + b[5]; 3606 out[6] = a[6] + b[6]; 3607 out[7] = a[7] + b[7]; 3608 out[8] = a[8] + b[8]; 3609 out[9] = a[9] + b[9]; 3610 out[10] = a[10] + b[10]; 3611 out[11] = a[11] + b[11]; 3612 out[12] = a[12] + b[12]; 3613 out[13] = a[13] + b[13]; 3614 out[14] = a[14] + b[14]; 3615 out[15] = a[15] + b[15]; 3616 return out; 3617} 3618/** 3619 * Subtracts matrix b from matrix a 3620 * 3621 * @param {mat4} out the receiving matrix 3622 * @param {mat4} a the first operand 3623 * @param {mat4} b the second operand 3624 * @returns {mat4} out 3625 */ 3626 3627function subtract(out, a, b) { 3628 out[0] = a[0] - b[0]; 3629 out[1] = a[1] - b[1]; 3630 out[2] = a[2] - b[2]; 3631 out[3] = a[3] - b[3]; 3632 out[4] = a[4] - b[4]; 3633 out[5] = a[5] - b[5]; 3634 out[6] = a[6] - b[6]; 3635 out[7] = a[7] - b[7]; 3636 out[8] = a[8] - b[8]; 3637 out[9] = a[9] - b[9]; 3638 out[10] = a[10] - b[10]; 3639 out[11] = a[11] - b[11]; 3640 out[12] = a[12] - b[12]; 3641 out[13] = a[13] - b[13]; 3642 out[14] = a[14] - b[14]; 3643 out[15] = a[15] - b[15]; 3644 return out; 3645} 3646/** 3647 * Multiply each element of the matrix by a scalar. 3648 * 3649 * @param {mat4} out the receiving matrix 3650 * @param {mat4} a the matrix to scale 3651 * @param {Number} b amount to scale the matrix's elements by 3652 * @returns {mat4} out 3653 */ 3654 3655function multiplyScalar(out, a, b) { 3656 out[0] = a[0] * b; 3657 out[1] = a[1] * b; 3658 out[2] = a[2] * b; 3659 out[3] = a[3] * b; 3660 out[4] = a[4] * b; 3661 out[5] = a[5] * b; 3662 out[6] = a[6] * b; 3663 out[7] = a[7] * b; 3664 out[8] = a[8] * b; 3665 out[9] = a[9] * b; 3666 out[10] = a[10] * b; 3667 out[11] = a[11] * b; 3668 out[12] = a[12] * b; 3669 out[13] = a[13] * b; 3670 out[14] = a[14] * b; 3671 out[15] = a[15] * b; 3672 return out; 3673} 3674/** 3675 * Adds two mat4's after multiplying each element of the second operand by a scalar value. 3676 * 3677 * @param {mat4} out the receiving vector 3678 * @param {mat4} a the first operand 3679 * @param {mat4} b the second operand 3680 * @param {Number} scale the amount to scale b's elements by before adding 3681 * @returns {mat4} out 3682 */ 3683 3684function multiplyScalarAndAdd(out, a, b, scale) { 3685 out[0] = a[0] + b[0] * scale; 3686 out[1] = a[1] + b[1] * scale; 3687 out[2] = a[2] + b[2] * scale; 3688 out[3] = a[3] + b[3] * scale; 3689 out[4] = a[4] + b[4] * scale; 3690 out[5] = a[5] + b[5] * scale; 3691 out[6] = a[6] + b[6] * scale; 3692 out[7] = a[7] + b[7] * scale; 3693 out[8] = a[8] + b[8] * scale; 3694 out[9] = a[9] + b[9] * scale; 3695 out[10] = a[10] + b[10] * scale; 3696 out[11] = a[11] + b[11] * scale; 3697 out[12] = a[12] + b[12] * scale; 3698 out[13] = a[13] + b[13] * scale; 3699 out[14] = a[14] + b[14] * scale; 3700 out[15] = a[15] + b[15] * scale; 3701 return out; 3702} 3703/** 3704 * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) 3705 * 3706 * @param {mat4} a The first matrix. 3707 * @param {mat4} b The second matrix. 3708 * @returns {Boolean} True if the matrices are equal, false otherwise. 3709 */ 3710 3711function exactEquals(a, b) { 3712 return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15]; 3713} 3714/** 3715 * Returns whether or not the matrices have approximately the same elements in the same position. 3716 * 3717 * @param {mat4} a The first matrix. 3718 * @param {mat4} b The second matrix. 3719 * @returns {Boolean} True if the matrices are equal, false otherwise. 3720 */ 3721 3722function equals(a, b) { 3723 var a0 = a[0], 3724 a1 = a[1], 3725 a2 = a[2], 3726 a3 = a[3]; 3727 var a4 = a[4], 3728 a5 = a[5], 3729 a6 = a[6], 3730 a7 = a[7]; 3731 var a8 = a[8], 3732 a9 = a[9], 3733 a10 = a[10], 3734 a11 = a[11]; 3735 var a12 = a[12], 3736 a13 = a[13], 3737 a14 = a[14], 3738 a15 = a[15]; 3739 var b0 = b[0], 3740 b1 = b[1], 3741 b2 = b[2], 3742 b3 = b[3]; 3743 var b4 = b[4], 3744 b5 = b[5], 3745 b6 = b[6], 3746 b7 = b[7]; 3747 var b8 = b[8], 3748 b9 = b[9], 3749 b10 = b[10], 3750 b11 = b[11]; 3751 var b12 = b[12], 3752 b13 = b[13], 3753 b14 = b[14], 3754 b15 = b[15]; 3755 return Math.abs(a0 - b0) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15)); 3756} 3757/** 3758 * Alias for {@link mat4.multiply} 3759 * @function 3760 */ 3761 3762var mul = multiply; 3763/** 3764 * Alias for {@link mat4.subtract} 3765 * @function 3766 */ 3767 3768var sub = subtract; 3769 3770/***/ }), 3771
vendor: 22,137 bytes, lines 3772-4537
3772/***/ "./node_modules/gl-matrix/esm/quat.js": 3773/*!********************************************!*\ 3774 !*** ./node_modules/gl-matrix/esm/quat.js ***! 3775 \********************************************/ 3776/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { 3777 3778"use strict"; 3779__webpack_require__.r(__webpack_exports__); 3780/* harmony export */ __webpack_require__.d(__webpack_exports__, { 3781/* harmony export */ add: () => (/* binding */ add), 3782/* harmony export */ calculateW: () => (/* binding */ calculateW), 3783/* harmony export */ clone: () => (/* binding */ clone), 3784/* harmony export */ conjugate: () => (/* binding */ conjugate), 3785/* harmony export */ copy: () => (/* binding */ copy), 3786/* harmony export */ create: () => (/* binding */ create), 3787/* harmony export */ dot: () => (/* binding */ dot), 3788/* harmony export */ equals: () => (/* binding */ equals), 3789/* harmony export */ exactEquals: () => (/* binding */ exactEquals), 3790/* harmony export */ exp: () => (/* binding */ exp), 3791/* harmony export */ fromEuler: () => (/* binding */ fromEuler), 3792/* harmony export */ fromMat3: () => (/* binding */ fromMat3), 3793/* harmony export */ fromValues: () => (/* binding */ fromValues), 3794/* harmony export */ getAngle: () => (/* binding */ getAngle), 3795/* harmony export */ getAxisAngle: () => (/* binding */ getAxisAngle), 3796/* harmony export */ identity: () => (/* binding */ identity), 3797/* harmony export */ invert: () => (/* binding */ invert), 3798/* harmony export */ len: () => (/* binding */ len), 3799/* harmony export */ length: () => (/* binding */ length), 3800/* harmony export */ lerp: () => (/* binding */ lerp), 3801/* harmony export */ ln: () => (/* binding */ ln), 3802/* harmony export */ mul: () => (/* binding */ mul), 3803/* harmony export */ multiply: () => (/* binding */ multiply), 3804/* harmony export */ normalize: () => (/* binding */ normalize), 3805/* harmony export */ pow: () => (/* binding */ pow), 3806/* harmony export */ random: () => (/* binding */ random), 3807/* harmony export */ rotateX: () => (/* binding */ rotateX), 3808/* harmony export */ rotateY: () => (/* binding */ rotateY), 3809/* harmony export */ rotateZ: () => (/* binding */ rotateZ), 3810/* harmony export */ rotationTo: () => (/* binding */ rotationTo), 3811/* harmony export */ scale: () => (/* binding */ scale), 3812/* harmony export */ set: () => (/* binding */ set), 3813/* harmony export */ setAxes: () => (/* binding */ setAxes), 3814/* harmony export */ setAxisAngle: () => (/* binding */ setAxisAngle), 3815/* harmony export */ slerp: () => (/* binding */ slerp), 3816/* harmony export */ sqlerp: () => (/* binding */ sqlerp), 3817/* harmony export */ sqrLen: () => (/* binding */ sqrLen), 3818/* harmony export */ squaredLength: () => (/* binding */ squaredLength), 3819/* harmony export */ str: () => (/* binding */ str) 3820/* harmony export */ }); 3821/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common.js */ "./node_modules/gl-matrix/esm/common.js"); 3822/* harmony import */ var _mat3_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mat3.js */ "./node_modules/gl-matrix/esm/mat3.js"); 3823/* harmony import */ var _vec3_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vec3.js */ "./node_modules/gl-matrix/esm/vec3.js"); 3824/* harmony import */ var _vec4_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vec4.js */ "./node_modules/gl-matrix/esm/vec4.js"); 3825 3826 3827 3828 3829/** 3830 * Quaternion 3831 * @module quat 3832 */ 3833 3834/** 3835 * Creates a new identity quat 3836 * 3837 * @returns {quat} a new quaternion 3838 */ 3839 3840function create() { 3841 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(4); 3842 3843 if (_common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE != Float32Array) { 3844 out[0] = 0; 3845 out[1] = 0; 3846 out[2] = 0; 3847 } 3848 3849 out[3] = 1; 3850 return out; 3851} 3852/** 3853 * Set a quat to the identity quaternion 3854 * 3855 * @param {quat} out the receiving quaternion 3856 * @returns {quat} out 3857 */ 3858 3859function identity(out) { 3860 out[0] = 0; 3861 out[1] = 0; 3862 out[2] = 0; 3863 out[3] = 1; 3864 return out; 3865} 3866/** 3867 * Sets a quat from the given angle and rotation axis, 3868 * then returns it. 3869 * 3870 * @param {quat} out the receiving quaternion 3871 * @param {vec3} axis the axis around which to rotate 3872 * @param {Number} rad the angle in radians 3873 * @returns {quat} out 3874 **/ 3875 3876function setAxisAngle(out, axis, rad) { 3877 rad = rad * 0.5; 3878 var s = Math.sin(rad); 3879 out[0] = s * axis[0]; 3880 out[1] = s * axis[1]; 3881 out[2] = s * axis[2]; 3882 out[3] = Math.cos(rad); 3883 return out; 3884} 3885/** 3886 * Gets the rotation axis and angle for a given 3887 * quaternion. If a quaternion is created with 3888 * setAxisAngle, this method will return the same 3889 * values as providied in the original parameter list 3890 * OR functionally equivalent values. 3891 * Example: The quaternion formed by axis [0, 0, 1] and 3892 * angle -90 is the same as the quaternion formed by 3893 * [0, 0, 1] and 270. This method favors the latter. 3894 * @param {vec3} out_axis Vector receiving the axis of rotation 3895 * @param {quat} q Quaternion to be decomposed 3896 * @return {Number} Angle, in radians, of the rotation 3897 */ 3898 3899function getAxisAngle(out_axis, q) { 3900 var rad = Math.acos(q[3]) * 2.0; 3901 var s = Math.sin(rad / 2.0); 3902 3903 if (s > _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON) { 3904 out_axis[0] = q[0] / s; 3905 out_axis[1] = q[1] / s; 3906 out_axis[2] = q[2] / s; 3907 } else { 3908 // If s is zero, return any axis (no rotation - axis does not matter) 3909 out_axis[0] = 1; 3910 out_axis[1] = 0; 3911 out_axis[2] = 0; 3912 } 3913 3914 return rad; 3915} 3916/** 3917 * Gets the angular distance between two unit quaternions 3918 * 3919 * @param {quat} a Origin unit quaternion 3920 * @param {quat} b Destination unit quaternion 3921 * @return {Number} Angle, in radians, between the two quaternions 3922 */ 3923 3924function getAngle(a, b) { 3925 var dotproduct = dot(a, b); 3926 return Math.acos(2 * dotproduct * dotproduct - 1); 3927} 3928/** 3929 * Multiplies two quat's 3930 * 3931 * @param {quat} out the receiving quaternion 3932 * @param {quat} a the first operand 3933 * @param {quat} b the second operand 3934 * @returns {quat} out 3935 */ 3936 3937function multiply(out, a, b) { 3938 var ax = a[0], 3939 ay = a[1], 3940 az = a[2], 3941 aw = a[3]; 3942 var bx = b[0], 3943 by = b[1], 3944 bz = b[2], 3945 bw = b[3]; 3946 out[0] = ax * bw + aw * bx + ay * bz - az * by; 3947 out[1] = ay * bw + aw * by + az * bx - ax * bz; 3948 out[2] = az * bw + aw * bz + ax * by - ay * bx; 3949 out[3] = aw * bw - ax * bx - ay * by - az * bz; 3950 return out; 3951} 3952/** 3953 * Rotates a quaternion by the given angle about the X axis 3954 * 3955 * @param {quat} out quat receiving operation result 3956 * @param {quat} a quat to rotate 3957 * @param {number} rad angle (in radians) to rotate 3958 * @returns {quat} out 3959 */ 3960 3961function rotateX(out, a, rad) { 3962 rad *= 0.5; 3963 var ax = a[0], 3964 ay = a[1], 3965 az = a[2], 3966 aw = a[3]; 3967 var bx = Math.sin(rad), 3968 bw = Math.cos(rad); 3969 out[0] = ax * bw + aw * bx; 3970 out[1] = ay * bw + az * bx; 3971 out[2] = az * bw - ay * bx; 3972 out[3] = aw * bw - ax * bx; 3973 return out; 3974} 3975/** 3976 * Rotates a quaternion by the given angle about the Y axis 3977 * 3978 * @param {quat} out quat receiving operation result 3979 * @param {quat} a quat to rotate 3980 * @param {number} rad angle (in radians) to rotate 3981 * @returns {quat} out 3982 */ 3983 3984function rotateY(out, a, rad) { 3985 rad *= 0.5; 3986 var ax = a[0], 3987 ay = a[1], 3988 az = a[2], 3989 aw = a[3]; 3990 var by = Math.sin(rad), 3991 bw = Math.cos(rad); 3992 out[0] = ax * bw - az * by; 3993 out[1] = ay * bw + aw * by; 3994 out[2] = az * bw + ax * by; 3995 out[3] = aw * bw - ay * by; 3996 return out; 3997} 3998/** 3999 * Rotates a quaternion by the given angle about the Z axis 4000 * 4001 * @param {quat} out quat receiving operation result 4002 * @param {quat} a quat to rotate 4003 * @param {number} rad angle (in radians) to rotate 4004 * @returns {quat} out 4005 */ 4006 4007function rotateZ(out, a, rad) { 4008 rad *= 0.5; 4009 var ax = a[0], 4010 ay = a[1], 4011 az = a[2], 4012 aw = a[3]; 4013 var bz = Math.sin(rad), 4014 bw = Math.cos(rad); 4015 out[0] = ax * bw + ay * bz; 4016 out[1] = ay * bw - ax * bz; 4017 out[2] = az * bw + aw * bz; 4018 out[3] = aw * bw - az * bz; 4019 return out; 4020} 4021/** 4022 * Calculates the W component of a quat from the X, Y, and Z components. 4023 * Assumes that quaternion is 1 unit in length. 4024 * Any existing W component will be ignored. 4025 * 4026 * @param {quat} out the receiving quaternion 4027 * @param {quat} a quat to calculate W component of 4028 * @returns {quat} out 4029 */ 4030 4031function calculateW(out, a) { 4032 var x = a[0], 4033 y = a[1], 4034 z = a[2]; 4035 out[0] = x; 4036 out[1] = y; 4037 out[2] = z; 4038 out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z)); 4039 return out; 4040} 4041/** 4042 * Calculate the exponential of a unit quaternion. 4043 * 4044 * @param {quat} out the receiving quaternion 4045 * @param {quat} a quat to calculate the exponential of 4046 * @returns {quat} out 4047 */ 4048 4049function exp(out, a) { 4050 var x = a[0], 4051 y = a[1], 4052 z = a[2], 4053 w = a[3]; 4054 var r = Math.sqrt(x * x + y * y + z * z); 4055 var et = Math.exp(w); 4056 var s = r > 0 ? et * Math.sin(r) / r : 0; 4057 out[0] = x * s; 4058 out[1] = y * s; 4059 out[2] = z * s; 4060 out[3] = et * Math.cos(r); 4061 return out; 4062} 4063/** 4064 * Calculate the natural logarithm of a unit quaternion. 4065 * 4066 * @param {quat} out the receiving quaternion 4067 * @param {quat} a quat to calculate the exponential of 4068 * @returns {quat} out 4069 */ 4070 4071function ln(out, a) { 4072 var x = a[0], 4073 y = a[1], 4074 z = a[2], 4075 w = a[3]; 4076 var r = Math.sqrt(x * x + y * y + z * z); 4077 var t = r > 0 ? Math.atan2(r, w) / r : 0; 4078 out[0] = x * t; 4079 out[1] = y * t; 4080 out[2] = z * t; 4081 out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w); 4082 return out; 4083} 4084/** 4085 * Calculate the scalar power of a unit quaternion. 4086 * 4087 * @param {quat} out the receiving quaternion 4088 * @param {quat} a quat to calculate the exponential of 4089 * @param {Number} b amount to scale the quaternion by 4090 * @returns {quat} out 4091 */ 4092 4093function pow(out, a, b) { 4094 ln(out, a); 4095 scale(out, out, b); 4096 exp(out, out); 4097 return out; 4098} 4099/** 4100 * Performs a spherical linear interpolation between two quat 4101 * 4102 * @param {quat} out the receiving quaternion 4103 * @param {quat} a the first operand 4104 * @param {quat} b the second operand 4105 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs 4106 * @returns {quat} out 4107 */ 4108 4109function slerp(out, a, b, t) { 4110 // benchmarks: 4111 // http://jsperf.com/quaternion-slerp-implementations 4112 var ax = a[0], 4113 ay = a[1], 4114 az = a[2], 4115 aw = a[3]; 4116 var bx = b[0], 4117 by = b[1], 4118 bz = b[2], 4119 bw = b[3]; 4120 var omega, cosom, sinom, scale0, scale1; // calc cosine 4121 4122 cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary) 4123 4124 if (cosom < 0.0) { 4125 cosom = -cosom; 4126 bx = -bx; 4127 by = -by; 4128 bz = -bz; 4129 bw = -bw; 4130 } // calculate coefficients 4131 4132 4133 if (1.0 - cosom > _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON) { 4134 // standard case (slerp) 4135 omega = Math.acos(cosom); 4136 sinom = Math.sin(omega); 4137 scale0 = Math.sin((1.0 - t) * omega) / sinom; 4138 scale1 = Math.sin(t * omega) / sinom; 4139 } else { 4140 // "from" and "to" quaternions are very close 4141 // ... so we can do a linear interpolation 4142 scale0 = 1.0 - t; 4143 scale1 = t; 4144 } // calculate final values 4145 4146 4147 out[0] = scale0 * ax + scale1 * bx; 4148 out[1] = scale0 * ay + scale1 * by; 4149 out[2] = scale0 * az + scale1 * bz; 4150 out[3] = scale0 * aw + scale1 * bw; 4151 return out; 4152} 4153/** 4154 * Generates a random unit quaternion 4155 * 4156 * @param {quat} out the receiving quaternion 4157 * @returns {quat} out 4158 */ 4159 4160function random(out) { 4161 // Implementation of http://planning.cs.uiuc.edu/node198.html 4162 // TODO: Calling random 3 times is probably not the fastest solution 4163 var u1 = _common_js__WEBPACK_IMPORTED_MODULE_0__.RANDOM(); 4164 var u2 = _common_js__WEBPACK_IMPORTED_MODULE_0__.RANDOM(); 4165 var u3 = _common_js__WEBPACK_IMPORTED_MODULE_0__.RANDOM(); 4166 var sqrt1MinusU1 = Math.sqrt(1 - u1); 4167 var sqrtU1 = Math.sqrt(u1); 4168 out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2); 4169 out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2); 4170 out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3); 4171 out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3); 4172 return out; 4173} 4174/** 4175 * Calculates the inverse of a quat 4176 * 4177 * @param {quat} out the receiving quaternion 4178 * @param {quat} a quat to calculate inverse of 4179 * @returns {quat} out 4180 */ 4181 4182function invert(out, a) { 4183 var a0 = a[0], 4184 a1 = a[1], 4185 a2 = a[2], 4186 a3 = a[3]; 4187 var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; 4188 var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 4189 4190 out[0] = -a0 * invDot; 4191 out[1] = -a1 * invDot; 4192 out[2] = -a2 * invDot; 4193 out[3] = a3 * invDot; 4194 return out; 4195} 4196/** 4197 * Calculates the conjugate of a quat 4198 * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. 4199 * 4200 * @param {quat} out the receiving quaternion 4201 * @param {quat} a quat to calculate conjugate of 4202 * @returns {quat} out 4203 */ 4204 4205function conjugate(out, a) { 4206 out[0] = -a[0]; 4207 out[1] = -a[1]; 4208 out[2] = -a[2]; 4209 out[3] = a[3]; 4210 return out; 4211} 4212/** 4213 * Creates a quaternion from the given 3x3 rotation matrix. 4214 * 4215 * NOTE: The resultant quaternion is not normalized, so you should be sure 4216 * to renormalize the quaternion yourself where necessary. 4217 * 4218 * @param {quat} out the receiving quaternion 4219 * @param {mat3} m rotation matrix 4220 * @returns {quat} out 4221 * @function 4222 */ 4223 4224function fromMat3(out, m) { 4225 // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes 4226 // article "Quaternion Calculus and Fast Animation". 4227 var fTrace = m[0] + m[4] + m[8]; 4228 var fRoot; 4229 4230 if (fTrace > 0.0) { 4231 // |w| > 1/2, may as well choose w > 1/2 4232 fRoot = Math.sqrt(fTrace + 1.0); // 2w 4233 4234 out[3] = 0.5 * fRoot; 4235 fRoot = 0.5 / fRoot; // 1/(4w) 4236 4237 out[0] = (m[5] - m[7]) * fRoot; 4238 out[1] = (m[6] - m[2]) * fRoot; 4239 out[2] = (m[1] - m[3]) * fRoot; 4240 } else { 4241 // |w| <= 1/2 4242 var i = 0; 4243 if (m[4] > m[0]) i = 1; 4244 if (m[8] > m[i * 3 + i]) i = 2; 4245 var j = (i + 1) % 3; 4246 var k = (i + 2) % 3; 4247 fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0); 4248 out[i] = 0.5 * fRoot; 4249 fRoot = 0.5 / fRoot; 4250 out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot; 4251 out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot; 4252 out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot; 4253 } 4254 4255 return out; 4256} 4257/** 4258 * Creates a quaternion from the given euler angle x, y, z. 4259 * 4260 * @param {quat} out the receiving quaternion 4261 * @param {x} Angle to rotate around X axis in degrees. 4262 * @param {y} Angle to rotate around Y axis in degrees. 4263 * @param {z} Angle to rotate around Z axis in degrees. 4264 * @returns {quat} out 4265 * @function 4266 */ 4267 4268function fromEuler(out, x, y, z) { 4269 var halfToRad = 0.5 * Math.PI / 180.0; 4270 x *= halfToRad; 4271 y *= halfToRad; 4272 z *= halfToRad; 4273 var sx = Math.sin(x); 4274 var cx = Math.cos(x); 4275 var sy = Math.sin(y); 4276 var cy = Math.cos(y); 4277 var sz = Math.sin(z); 4278 var cz = Math.cos(z); 4279 out[0] = sx * cy * cz - cx * sy * sz; 4280 out[1] = cx * sy * cz + sx * cy * sz; 4281 out[2] = cx * cy * sz - sx * sy * cz; 4282 out[3] = cx * cy * cz + sx * sy * sz; 4283 return out; 4284} 4285/** 4286 * Returns a string representation of a quatenion 4287 * 4288 * @param {quat} a vector to represent as a string 4289 * @returns {String} string representation of the vector 4290 */ 4291 4292function str(a) { 4293 return 'quat(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')'; 4294} 4295/** 4296 * Creates a new quat initialized with values from an existing quaternion 4297 * 4298 * @param {quat} a quaternion to clone 4299 * @returns {quat} a new quaternion 4300 * @function 4301 */ 4302 4303var clone = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.clone; 4304/** 4305 * Creates a new quat initialized with the given values 4306 * 4307 * @param {Number} x X component 4308 * @param {Number} y Y component 4309 * @param {Number} z Z component 4310 * @param {Number} w W component 4311 * @returns {quat} a new quaternion 4312 * @function 4313 */ 4314 4315var fromValues = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.fromValues; 4316/** 4317 * Copy the values from one quat to another 4318 * 4319 * @param {quat} out the receiving quaternion 4320 * @param {quat} a the source quaternion 4321 * @returns {quat} out 4322 * @function 4323 */ 4324 4325var copy = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.copy; 4326/** 4327 * Set the components of a quat to the given values 4328 * 4329 * @param {quat} out the receiving quaternion 4330 * @param {Number} x X component 4331 * @param {Number} y Y component 4332 * @param {Number} z Z component 4333 * @param {Number} w W component 4334 * @returns {quat} out 4335 * @function 4336 */ 4337 4338var set = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.set; 4339/** 4340 * Adds two quat's 4341 * 4342 * @param {quat} out the receiving quaternion 4343 * @param {quat} a the first operand 4344 * @param {quat} b the second operand 4345 * @returns {quat} out 4346 * @function 4347 */ 4348 4349var add = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.add; 4350/** 4351 * Alias for {@link quat.multiply} 4352 * @function 4353 */ 4354 4355var mul = multiply; 4356/** 4357 * Scales a quat by a scalar number 4358 * 4359 * @param {quat} out the receiving vector 4360 * @param {quat} a the vector to scale 4361 * @param {Number} b amount to scale the vector by 4362 * @returns {quat} out 4363 * @function 4364 */ 4365 4366var scale = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.scale; 4367/** 4368 * Calculates the dot product of two quat's 4369 * 4370 * @param {quat} a the first operand 4371 * @param {quat} b the second operand 4372 * @returns {Number} dot product of a and b 4373 * @function 4374 */ 4375 4376var dot = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.dot; 4377/** 4378 * Performs a linear interpolation between two quat's 4379 * 4380 * @param {quat} out the receiving quaternion 4381 * @param {quat} a the first operand 4382 * @param {quat} b the second operand 4383 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs 4384 * @returns {quat} out 4385 * @function 4386 */ 4387 4388var lerp = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.lerp; 4389/** 4390 * Calculates the length of a quat 4391 * 4392 * @param {quat} a vector to calculate length of 4393 * @returns {Number} length of a 4394 */ 4395 4396var length = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.length; 4397/** 4398 * Alias for {@link quat.length} 4399 * @function 4400 */ 4401 4402var len = length; 4403/** 4404 * Calculates the squared length of a quat 4405 * 4406 * @param {quat} a vector to calculate squared length of 4407 * @returns {Number} squared length of a 4408 * @function 4409 */ 4410 4411var squaredLength = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.squaredLength; 4412/** 4413 * Alias for {@link quat.squaredLength} 4414 * @function 4415 */ 4416 4417var sqrLen = squaredLength; 4418/** 4419 * Normalize a quat 4420 * 4421 * @param {quat} out the receiving quaternion 4422 * @param {quat} a quaternion to normalize 4423 * @returns {quat} out 4424 * @function 4425 */ 4426 4427var normalize = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.normalize; 4428/** 4429 * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) 4430 * 4431 * @param {quat} a The first quaternion. 4432 * @param {quat} b The second quaternion. 4433 * @returns {Boolean} True if the vectors are equal, false otherwise. 4434 */ 4435 4436var exactEquals = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.exactEquals; 4437/** 4438 * Returns whether or not the quaternions have approximately the same elements in the same position. 4439 * 4440 * @param {quat} a The first vector. 4441 * @param {quat} b The second vector. 4442 * @returns {Boolean} True if the vectors are equal, false otherwise. 4443 */ 4444 4445var equals = _vec4_js__WEBPACK_IMPORTED_MODULE_1__.equals; 4446/** 4447 * Sets a quaternion to represent the shortest rotation from one 4448 * vector to another. 4449 * 4450 * Both vectors are assumed to be unit length. 4451 * 4452 * @param {quat} out the receiving quaternion. 4453 * @param {vec3} a the initial vector 4454 * @param {vec3} b the destination vector 4455 * @returns {quat} out 4456 */ 4457 4458var rotationTo = function () { 4459 var tmpvec3 = _vec3_js__WEBPACK_IMPORTED_MODULE_2__.create(); 4460 var xUnitVec3 = _vec3_js__WEBPACK_IMPORTED_MODULE_2__.fromValues(1, 0, 0); 4461 var yUnitVec3 = _vec3_js__WEBPACK_IMPORTED_MODULE_2__.fromValues(0, 1, 0); 4462 return function (out, a, b) { 4463 var dot = _vec3_js__WEBPACK_IMPORTED_MODULE_2__.dot(a, b); 4464 4465 if (dot < -0.999999) { 4466 _vec3_js__WEBPACK_IMPORTED_MODULE_2__.cross(tmpvec3, xUnitVec3, a); 4467 if (_vec3_js__WEBPACK_IMPORTED_MODULE_2__.len(tmpvec3) < 0.000001) _vec3_js__WEBPACK_IMPORTED_MODULE_2__.cross(tmpvec3, yUnitVec3, a); 4468 _vec3_js__WEBPACK_IMPORTED_MODULE_2__.normalize(tmpvec3, tmpvec3); 4469 setAxisAngle(out, tmpvec3, Math.PI); 4470 return out; 4471 } else if (dot > 0.999999) { 4472 out[0] = 0; 4473 out[1] = 0; 4474 out[2] = 0; 4475 out[3] = 1; 4476 return out; 4477 } else { 4478 _vec3_js__WEBPACK_IMPORTED_MODULE_2__.cross(tmpvec3, a, b); 4479 out[0] = tmpvec3[0]; 4480 out[1] = tmpvec3[1]; 4481 out[2] = tmpvec3[2]; 4482 out[3] = 1 + dot; 4483 return normalize(out, out); 4484 } 4485 }; 4486}(); 4487/** 4488 * Performs a spherical linear interpolation with two control points 4489 * 4490 * @param {quat} out the receiving quaternion 4491 * @param {quat} a the first operand 4492 * @param {quat} b the second operand 4493 * @param {quat} c the third operand 4494 * @param {quat} d the fourth operand 4495 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs 4496 * @returns {quat} out 4497 */ 4498 4499var sqlerp = function () { 4500 var temp1 = create(); 4501 var temp2 = create(); 4502 return function (out, a, b, c, d, t) { 4503 slerp(temp1, a, d, t); 4504 slerp(temp2, b, c, t); 4505 slerp(out, temp1, temp2, 2 * t * (1 - t)); 4506 return out; 4507 }; 4508}(); 4509/** 4510 * Sets the specified quaternion with values corresponding to the given 4511 * axes. Each axis is a vec3 and is expected to be unit length and 4512 * perpendicular to all other specified axes. 4513 * 4514 * @param {vec3} view the vector representing the viewing direction 4515 * @param {vec3} right the vector representing the local "right" direction 4516 * @param {vec3} up the vector representing the local "up" direction 4517 * @returns {quat} out 4518 */ 4519 4520var setAxes = function () { 4521 var matr = _mat3_js__WEBPACK_IMPORTED_MODULE_3__.create(); 4522 return function (out, view, right, up) { 4523 matr[0] = right[0]; 4524 matr[3] = right[1]; 4525 matr[6] = right[2]; 4526 matr[1] = up[0]; 4527 matr[4] = up[1]; 4528 matr[7] = up[2]; 4529 matr[2] = -view[0]; 4530 matr[5] = -view[1]; 4531 matr[8] = -view[2]; 4532 return normalize(out, fromMat3(out, matr)); 4533 }; 4534}(); 4535 4536/***/ }), 4537
vendor: 25,968 bytes, lines 4538-5427
4538/***/ "./node_modules/gl-matrix/esm/quat2.js": 4539/*!*********************************************!*\ 4540 !*** ./node_modules/gl-matrix/esm/quat2.js ***! 4541 \*********************************************/ 4542/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { 4543 4544"use strict"; 4545__webpack_require__.r(__webpack_exports__); 4546/* harmony export */ __webpack_require__.d(__webpack_exports__, { 4547/* harmony export */ add: () => (/* binding */ add), 4548/* harmony export */ clone: () => (/* binding */ clone), 4549/* harmony export */ conjugate: () => (/* binding */ conjugate), 4550/* harmony export */ copy: () => (/* binding */ copy), 4551/* harmony export */ create: () => (/* binding */ create), 4552/* harmony export */ dot: () => (/* binding */ dot), 4553/* harmony export */ equals: () => (/* binding */ equals), 4554/* harmony export */ exactEquals: () => (/* binding */ exactEquals), 4555/* harmony export */ fromMat4: () => (/* binding */ fromMat4), 4556/* harmony export */ fromRotation: () => (/* binding */ fromRotation), 4557/* harmony export */ fromRotationTranslation: () => (/* binding */ fromRotationTranslation), 4558/* harmony export */ fromRotationTranslationValues: () => (/* binding */ fromRotationTranslationValues), 4559/* harmony export */ fromTranslation: () => (/* binding */ fromTranslation), 4560/* harmony export */ fromValues: () => (/* binding */ fromValues), 4561/* harmony export */ getDual: () => (/* binding */ getDual), 4562/* harmony export */ getReal: () => (/* binding */ getReal), 4563/* harmony export */ getTranslation: () => (/* binding */ getTranslation), 4564/* harmony export */ identity: () => (/* binding */ identity), 4565/* harmony export */ invert: () => (/* binding */ invert), 4566/* harmony export */ len: () => (/* binding */ len), 4567/* harmony export */ length: () => (/* binding */ length), 4568/* harmony export */ lerp: () => (/* binding */ lerp), 4569/* harmony export */ mul: () => (/* binding */ mul), 4570/* harmony export */ multiply: () => (/* binding */ multiply), 4571/* harmony export */ normalize: () => (/* binding */ normalize), 4572/* harmony export */ rotateAroundAxis: () => (/* binding */ rotateAroundAxis), 4573/* harmony export */ rotateByQuatAppend: () => (/* binding */ rotateByQuatAppend), 4574/* harmony export */ rotateByQuatPrepend: () => (/* binding */ rotateByQuatPrepend), 4575/* harmony export */ rotateX: () => (/* binding */ rotateX), 4576/* harmony export */ rotateY: () => (/* binding */ rotateY), 4577/* harmony export */ rotateZ: () => (/* binding */ rotateZ), 4578/* harmony export */ scale: () => (/* binding */ scale), 4579/* harmony export */ set: () => (/* binding */ set), 4580/* harmony export */ setDual: () => (/* binding */ setDual), 4581/* harmony export */ setReal: () => (/* binding */ setReal), 4582/* harmony export */ sqrLen: () => (/* binding */ sqrLen), 4583/* harmony export */ squaredLength: () => (/* binding */ squaredLength), 4584/* harmony export */ str: () => (/* binding */ str), 4585/* harmony export */ translate: () => (/* binding */ translate) 4586/* harmony export */ }); 4587/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common.js */ "./node_modules/gl-matrix/esm/common.js"); 4588/* harmony import */ var _quat_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./quat.js */ "./node_modules/gl-matrix/esm/quat.js"); 4589/* harmony import */ var _mat4_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mat4.js */ "./node_modules/gl-matrix/esm/mat4.js"); 4590 4591 4592 4593/** 4594 * Dual Quaternion<br> 4595 * Format: [real, dual]<br> 4596 * Quaternion format: XYZW<br> 4597 * Make sure to have normalized dual quaternions, otherwise the functions may not work as intended.<br> 4598 * @module quat2 4599 */ 4600 4601/** 4602 * Creates a new identity dual quat 4603 * 4604 * @returns {quat2} a new dual quaternion [real -> rotation, dual -> translation] 4605 */ 4606 4607function create() { 4608 var dq = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(8); 4609 4610 if (_common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE != Float32Array) { 4611 dq[0] = 0; 4612 dq[1] = 0; 4613 dq[2] = 0; 4614 dq[4] = 0; 4615 dq[5] = 0; 4616 dq[6] = 0; 4617 dq[7] = 0; 4618 } 4619 4620 dq[3] = 1; 4621 return dq; 4622} 4623/** 4624 * Creates a new quat initialized with values from an existing quaternion 4625 * 4626 * @param {quat2} a dual quaternion to clone 4627 * @returns {quat2} new dual quaternion 4628 * @function 4629 */ 4630 4631function clone(a) { 4632 var dq = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(8); 4633 dq[0] = a[0]; 4634 dq[1] = a[1]; 4635 dq[2] = a[2]; 4636 dq[3] = a[3]; 4637 dq[4] = a[4]; 4638 dq[5] = a[5]; 4639 dq[6] = a[6]; 4640 dq[7] = a[7]; 4641 return dq; 4642} 4643/** 4644 * Creates a new dual quat initialized with the given values 4645 * 4646 * @param {Number} x1 X component 4647 * @param {Number} y1 Y component 4648 * @param {Number} z1 Z component 4649 * @param {Number} w1 W component 4650 * @param {Number} x2 X component 4651 * @param {Number} y2 Y component 4652 * @param {Number} z2 Z component 4653 * @param {Number} w2 W component 4654 * @returns {quat2} new dual quaternion 4655 * @function 4656 */ 4657 4658function fromValues(x1, y1, z1, w1, x2, y2, z2, w2) { 4659 var dq = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(8); 4660 dq[0] = x1; 4661 dq[1] = y1; 4662 dq[2] = z1; 4663 dq[3] = w1; 4664 dq[4] = x2; 4665 dq[5] = y2; 4666 dq[6] = z2; 4667 dq[7] = w2; 4668 return dq; 4669} 4670/** 4671 * Creates a new dual quat from the given values (quat and translation) 4672 * 4673 * @param {Number} x1 X component 4674 * @param {Number} y1 Y component 4675 * @param {Number} z1 Z component 4676 * @param {Number} w1 W component 4677 * @param {Number} x2 X component (translation) 4678 * @param {Number} y2 Y component (translation) 4679 * @param {Number} z2 Z component (translation) 4680 * @returns {quat2} new dual quaternion 4681 * @function 4682 */ 4683 4684function fromRotationTranslationValues(x1, y1, z1, w1, x2, y2, z2) { 4685 var dq = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(8); 4686 dq[0] = x1; 4687 dq[1] = y1; 4688 dq[2] = z1; 4689 dq[3] = w1; 4690 var ax = x2 * 0.5, 4691 ay = y2 * 0.5, 4692 az = z2 * 0.5; 4693 dq[4] = ax * w1 + ay * z1 - az * y1; 4694 dq[5] = ay * w1 + az * x1 - ax * z1; 4695 dq[6] = az * w1 + ax * y1 - ay * x1; 4696 dq[7] = -ax * x1 - ay * y1 - az * z1; 4697 return dq; 4698} 4699/** 4700 * Creates a dual quat from a quaternion and a translation 4701 * 4702 * @param {quat2} dual quaternion receiving operation result 4703 * @param {quat} q a normalized quaternion 4704 * @param {vec3} t tranlation vector 4705 * @returns {quat2} dual quaternion receiving operation result 4706 * @function 4707 */ 4708 4709function fromRotationTranslation(out, q, t) { 4710 var ax = t[0] * 0.5, 4711 ay = t[1] * 0.5, 4712 az = t[2] * 0.5, 4713 bx = q[0], 4714 by = q[1], 4715 bz = q[2], 4716 bw = q[3]; 4717 out[0] = bx; 4718 out[1] = by; 4719 out[2] = bz; 4720 out[3] = bw; 4721 out[4] = ax * bw + ay * bz - az * by; 4722 out[5] = ay * bw + az * bx - ax * bz; 4723 out[6] = az * bw + ax * by - ay * bx; 4724 out[7] = -ax * bx - ay * by - az * bz; 4725 return out; 4726} 4727/** 4728 * Creates a dual quat from a translation 4729 * 4730 * @param {quat2} dual quaternion receiving operation result 4731 * @param {vec3} t translation vector 4732 * @returns {quat2} dual quaternion receiving operation result 4733 * @function 4734 */ 4735 4736function fromTranslation(out, t) { 4737 out[0] = 0; 4738 out[1] = 0; 4739 out[2] = 0; 4740 out[3] = 1; 4741 out[4] = t[0] * 0.5; 4742 out[5] = t[1] * 0.5; 4743 out[6] = t[2] * 0.5; 4744 out[7] = 0; 4745 return out; 4746} 4747/** 4748 * Creates a dual quat from a quaternion 4749 * 4750 * @param {quat2} dual quaternion receiving operation result 4751 * @param {quat} q the quaternion 4752 * @returns {quat2} dual quaternion receiving operation result 4753 * @function 4754 */ 4755 4756function fromRotation(out, q) { 4757 out[0] = q[0]; 4758 out[1] = q[1]; 4759 out[2] = q[2]; 4760 out[3] = q[3]; 4761 out[4] = 0; 4762 out[5] = 0; 4763 out[6] = 0; 4764 out[7] = 0; 4765 return out; 4766} 4767/** 4768 * Creates a new dual quat from a matrix (4x4) 4769 * 4770 * @param {quat2} out the dual quaternion 4771 * @param {mat4} a the matrix 4772 * @returns {quat2} dual quat receiving operation result 4773 * @function 4774 */ 4775 4776function fromMat4(out, a) { 4777 //TODO Optimize this 4778 var outer = _quat_js__WEBPACK_IMPORTED_MODULE_1__.create(); 4779 _mat4_js__WEBPACK_IMPORTED_MODULE_2__.getRotation(outer, a); 4780 var t = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(3); 4781 _mat4_js__WEBPACK_IMPORTED_MODULE_2__.getTranslation(t, a); 4782 fromRotationTranslation(out, outer, t); 4783 return out; 4784} 4785/** 4786 * Copy the values from one dual quat to another 4787 * 4788 * @param {quat2} out the receiving dual quaternion 4789 * @param {quat2} a the source dual quaternion 4790 * @returns {quat2} out 4791 * @function 4792 */ 4793 4794function copy(out, a) { 4795 out[0] = a[0]; 4796 out[1] = a[1]; 4797 out[2] = a[2]; 4798 out[3] = a[3]; 4799 out[4] = a[4]; 4800 out[5] = a[5]; 4801 out[6] = a[6]; 4802 out[7] = a[7]; 4803 return out; 4804} 4805/** 4806 * Set a dual quat to the identity dual quaternion 4807 * 4808 * @param {quat2} out the receiving quaternion 4809 * @returns {quat2} out 4810 */ 4811 4812function identity(out) { 4813 out[0] = 0; 4814 out[1] = 0; 4815 out[2] = 0; 4816 out[3] = 1; 4817 out[4] = 0; 4818 out[5] = 0; 4819 out[6] = 0; 4820 out[7] = 0; 4821 return out; 4822} 4823/** 4824 * Set the components of a dual quat to the given values 4825 * 4826 * @param {quat2} out the receiving quaternion 4827 * @param {Number} x1 X component 4828 * @param {Number} y1 Y component 4829 * @param {Number} z1 Z component 4830 * @param {Number} w1 W component 4831 * @param {Number} x2 X component 4832 * @param {Number} y2 Y component 4833 * @param {Number} z2 Z component 4834 * @param {Number} w2 W component 4835 * @returns {quat2} out 4836 * @function 4837 */ 4838 4839function set(out, x1, y1, z1, w1, x2, y2, z2, w2) { 4840 out[0] = x1; 4841 out[1] = y1; 4842 out[2] = z1; 4843 out[3] = w1; 4844 out[4] = x2; 4845 out[5] = y2; 4846 out[6] = z2; 4847 out[7] = w2; 4848 return out; 4849} 4850/** 4851 * Gets the real part of a dual quat 4852 * @param {quat} out real part 4853 * @param {quat2} a Dual Quaternion 4854 * @return {quat} real part 4855 */ 4856 4857var getReal = _quat_js__WEBPACK_IMPORTED_MODULE_1__.copy; 4858/** 4859 * Gets the dual part of a dual quat 4860 * @param {quat} out dual part 4861 * @param {quat2} a Dual Quaternion 4862 * @return {quat} dual part 4863 */ 4864 4865function getDual(out, a) { 4866 out[0] = a[4]; 4867 out[1] = a[5]; 4868 out[2] = a[6]; 4869 out[3] = a[7]; 4870 return out; 4871} 4872/** 4873 * Set the real component of a dual quat to the given quaternion 4874 * 4875 * @param {quat2} out the receiving quaternion 4876 * @param {quat} q a quaternion representing the real part 4877 * @returns {quat2} out 4878 * @function 4879 */ 4880 4881var setReal = _quat_js__WEBPACK_IMPORTED_MODULE_1__.copy; 4882/** 4883 * Set the dual component of a dual quat to the given quaternion 4884 * 4885 * @param {quat2} out the receiving quaternion 4886 * @param {quat} q a quaternion representing the dual part 4887 * @returns {quat2} out 4888 * @function 4889 */ 4890 4891function setDual(out, q) { 4892 out[4] = q[0]; 4893 out[5] = q[1]; 4894 out[6] = q[2]; 4895 out[7] = q[3]; 4896 return out; 4897} 4898/** 4899 * Gets the translation of a normalized dual quat 4900 * @param {vec3} out translation 4901 * @param {quat2} a Dual Quaternion to be decomposed 4902 * @return {vec3} translation 4903 */ 4904 4905function getTranslation(out, a) { 4906 var ax = a[4], 4907 ay = a[5], 4908 az = a[6], 4909 aw = a[7], 4910 bx = -a[0], 4911 by = -a[1], 4912 bz = -a[2], 4913 bw = a[3]; 4914 out[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2; 4915 out[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2; 4916 out[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2; 4917 return out; 4918} 4919/** 4920 * Translates a dual quat by the given vector 4921 * 4922 * @param {quat2} out the receiving dual quaternion 4923 * @param {quat2} a the dual quaternion to translate 4924 * @param {vec3} v vector to translate by 4925 * @returns {quat2} out 4926 */ 4927 4928function translate(out, a, v) { 4929 var ax1 = a[0], 4930 ay1 = a[1], 4931 az1 = a[2], 4932 aw1 = a[3], 4933 bx1 = v[0] * 0.5, 4934 by1 = v[1] * 0.5, 4935 bz1 = v[2] * 0.5, 4936 ax2 = a[4], 4937 ay2 = a[5], 4938 az2 = a[6], 4939 aw2 = a[7]; 4940 out[0] = ax1; 4941 out[1] = ay1; 4942 out[2] = az1; 4943 out[3] = aw1; 4944 out[4] = aw1 * bx1 + ay1 * bz1 - az1 * by1 + ax2; 4945 out[5] = aw1 * by1 + az1 * bx1 - ax1 * bz1 + ay2; 4946 out[6] = aw1 * bz1 + ax1 * by1 - ay1 * bx1 + az2; 4947 out[7] = -ax1 * bx1 - ay1 * by1 - az1 * bz1 + aw2; 4948 return out; 4949} 4950/** 4951 * Rotates a dual quat around the X axis 4952 * 4953 * @param {quat2} out the receiving dual quaternion 4954 * @param {quat2} a the dual quaternion to rotate 4955 * @param {number} rad how far should the rotation be 4956 * @returns {quat2} out 4957 */ 4958 4959function rotateX(out, a, rad) { 4960 var bx = -a[0], 4961 by = -a[1], 4962 bz = -a[2], 4963 bw = a[3], 4964 ax = a[4], 4965 ay = a[5], 4966 az = a[6], 4967 aw = a[7], 4968 ax1 = ax * bw + aw * bx + ay * bz - az * by, 4969 ay1 = ay * bw + aw * by + az * bx - ax * bz, 4970 az1 = az * bw + aw * bz + ax * by - ay * bx, 4971 aw1 = aw * bw - ax * bx - ay * by - az * bz; 4972 _quat_js__WEBPACK_IMPORTED_MODULE_1__.rotateX(out, a, rad); 4973 bx = out[0]; 4974 by = out[1]; 4975 bz = out[2]; 4976 bw = out[3]; 4977 out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; 4978 out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; 4979 out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; 4980 out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; 4981 return out; 4982} 4983/** 4984 * Rotates a dual quat around the Y axis 4985 * 4986 * @param {quat2} out the receiving dual quaternion 4987 * @param {quat2} a the dual quaternion to rotate 4988 * @param {number} rad how far should the rotation be 4989 * @returns {quat2} out 4990 */ 4991 4992function rotateY(out, a, rad) { 4993 var bx = -a[0], 4994 by = -a[1], 4995 bz = -a[2], 4996 bw = a[3], 4997 ax = a[4], 4998 ay = a[5], 4999 az = a[6], 5000 aw = a[7], 5001 ax1 = ax * bw + aw * bx + ay * bz - az * by, 5002 ay1 = ay * bw + aw * by + az * bx - ax * bz, 5003 az1 = az * bw + aw * bz + ax * by - ay * bx, 5004 aw1 = aw * bw - ax * bx - ay * by - az * bz; 5005 _quat_js__WEBPACK_IMPORTED_MODULE_1__.rotateY(out, a, rad); 5006 bx = out[0]; 5007 by = out[1]; 5008 bz = out[2]; 5009 bw = out[3]; 5010 out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; 5011 out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; 5012 out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; 5013 out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; 5014 return out; 5015} 5016/** 5017 * Rotates a dual quat around the Z axis 5018 * 5019 * @param {quat2} out the receiving dual quaternion 5020 * @param {quat2} a the dual quaternion to rotate 5021 * @param {number} rad how far should the rotation be 5022 * @returns {quat2} out 5023 */ 5024 5025function rotateZ(out, a, rad) { 5026 var bx = -a[0], 5027 by = -a[1], 5028 bz = -a[2], 5029 bw = a[3], 5030 ax = a[4], 5031 ay = a[5], 5032 az = a[6], 5033 aw = a[7], 5034 ax1 = ax * bw + aw * bx + ay * bz - az * by, 5035 ay1 = ay * bw + aw * by + az * bx - ax * bz, 5036 az1 = az * bw + aw * bz + ax * by - ay * bx, 5037 aw1 = aw * bw - ax * bx - ay * by - az * bz; 5038 _quat_js__WEBPACK_IMPORTED_MODULE_1__.rotateZ(out, a, rad); 5039 bx = out[0]; 5040 by = out[1]; 5041 bz = out[2]; 5042 bw = out[3]; 5043 out[4] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; 5044 out[5] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; 5045 out[6] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; 5046 out[7] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; 5047 return out; 5048} 5049/** 5050 * Rotates a dual quat by a given quaternion (a * q) 5051 * 5052 * @param {quat2} out the receiving dual quaternion 5053 * @param {quat2} a the dual quaternion to rotate 5054 * @param {quat} q quaternion to rotate by 5055 * @returns {quat2} out 5056 */ 5057 5058function rotateByQuatAppend(out, a, q) { 5059 var qx = q[0], 5060 qy = q[1], 5061 qz = q[2], 5062 qw = q[3], 5063 ax = a[0], 5064 ay = a[1], 5065 az = a[2], 5066 aw = a[3]; 5067 out[0] = ax * qw + aw * qx + ay * qz - az * qy; 5068 out[1] = ay * qw + aw * qy + az * qx - ax * qz; 5069 out[2] = az * qw + aw * qz + ax * qy - ay * qx; 5070 out[3] = aw * qw - ax * qx - ay * qy - az * qz; 5071 ax = a[4]; 5072 ay = a[5]; 5073 az = a[6]; 5074 aw = a[7]; 5075 out[4] = ax * qw + aw * qx + ay * qz - az * qy; 5076 out[5] = ay * qw + aw * qy + az * qx - ax * qz; 5077 out[6] = az * qw + aw * qz + ax * qy - ay * qx; 5078 out[7] = aw * qw - ax * qx - ay * qy - az * qz; 5079 return out; 5080} 5081/** 5082 * Rotates a dual quat by a given quaternion (q * a) 5083 * 5084 * @param {quat2} out the receiving dual quaternion 5085 * @param {quat} q quaternion to rotate by 5086 * @param {quat2} a the dual quaternion to rotate 5087 * @returns {quat2} out 5088 */ 5089 5090function rotateByQuatPrepend(out, q, a) { 5091 var qx = q[0], 5092 qy = q[1], 5093 qz = q[2], 5094 qw = q[3], 5095 bx = a[0], 5096 by = a[1], 5097 bz = a[2], 5098 bw = a[3]; 5099 out[0] = qx * bw + qw * bx + qy * bz - qz * by; 5100 out[1] = qy * bw + qw * by + qz * bx - qx * bz; 5101 out[2] = qz * bw + qw * bz + qx * by - qy * bx; 5102 out[3] = qw * bw - qx * bx - qy * by - qz * bz; 5103 bx = a[4]; 5104 by = a[5]; 5105 bz = a[6]; 5106 bw = a[7]; 5107 out[4] = qx * bw + qw * bx + qy * bz - qz * by; 5108 out[5] = qy * bw + qw * by + qz * bx - qx * bz; 5109 out[6] = qz * bw + qw * bz + qx * by - qy * bx; 5110 out[7] = qw * bw - qx * bx - qy * by - qz * bz; 5111 return out; 5112} 5113/** 5114 * Rotates a dual quat around a given axis. Does the normalisation automatically 5115 * 5116 * @param {quat2} out the receiving dual quaternion 5117 * @param {quat2} a the dual quaternion to rotate 5118 * @param {vec3} axis the axis to rotate around 5119 * @param {Number} rad how far the rotation should be 5120 * @returns {quat2} out 5121 */ 5122 5123function rotateAroundAxis(out, a, axis, rad) { 5124 //Special case for rad = 0 5125 if (Math.abs(rad) < _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON) { 5126 return copy(out, a); 5127 } 5128 5129 var axisLength = Math.hypot(axis[0], axis[1], axis[2]); 5130 rad = rad * 0.5; 5131 var s = Math.sin(rad); 5132 var bx = s * axis[0] / axisLength; 5133 var by = s * axis[1] / axisLength; 5134 var bz = s * axis[2] / axisLength; 5135 var bw = Math.cos(rad); 5136 var ax1 = a[0], 5137 ay1 = a[1], 5138 az1 = a[2], 5139 aw1 = a[3]; 5140 out[0] = ax1 * bw + aw1 * bx + ay1 * bz - az1 * by; 5141 out[1] = ay1 * bw + aw1 * by + az1 * bx - ax1 * bz; 5142 out[2] = az1 * bw + aw1 * bz + ax1 * by - ay1 * bx; 5143 out[3] = aw1 * bw - ax1 * bx - ay1 * by - az1 * bz; 5144 var ax = a[4], 5145 ay = a[5], 5146 az = a[6], 5147 aw = a[7]; 5148 out[4] = ax * bw + aw * bx + ay * bz - az * by; 5149 out[5] = ay * bw + aw * by + az * bx - ax * bz; 5150 out[6] = az * bw + aw * bz + ax * by - ay * bx; 5151 out[7] = aw * bw - ax * bx - ay * by - az * bz; 5152 return out; 5153} 5154/** 5155 * Adds two dual quat's 5156 * 5157 * @param {quat2} out the receiving dual quaternion 5158 * @param {quat2} a the first operand 5159 * @param {quat2} b the second operand 5160 * @returns {quat2} out 5161 * @function 5162 */ 5163 5164function add(out, a, b) { 5165 out[0] = a[0] + b[0]; 5166 out[1] = a[1] + b[1]; 5167 out[2] = a[2] + b[2]; 5168 out[3] = a[3] + b[3]; 5169 out[4] = a[4] + b[4]; 5170 out[5] = a[5] + b[5]; 5171 out[6] = a[6] + b[6]; 5172 out[7] = a[7] + b[7]; 5173 return out; 5174} 5175/** 5176 * Multiplies two dual quat's 5177 * 5178 * @param {quat2} out the receiving dual quaternion 5179 * @param {quat2} a the first operand 5180 * @param {quat2} b the second operand 5181 * @returns {quat2} out 5182 */ 5183 5184function multiply(out, a, b) { 5185 var ax0 = a[0], 5186 ay0 = a[1], 5187 az0 = a[2], 5188 aw0 = a[3], 5189 bx1 = b[4], 5190 by1 = b[5], 5191 bz1 = b[6], 5192 bw1 = b[7], 5193 ax1 = a[4], 5194 ay1 = a[5], 5195 az1 = a[6], 5196 aw1 = a[7], 5197 bx0 = b[0], 5198 by0 = b[1], 5199 bz0 = b[2], 5200 bw0 = b[3]; 5201 out[0] = ax0 * bw0 + aw0 * bx0 + ay0 * bz0 - az0 * by0; 5202 out[1] = ay0 * bw0 + aw0 * by0 + az0 * bx0 - ax0 * bz0; 5203 out[2] = az0 * bw0 + aw0 * bz0 + ax0 * by0 - ay0 * bx0; 5204 out[3] = aw0 * bw0 - ax0 * bx0 - ay0 * by0 - az0 * bz0; 5205 out[4] = ax0 * bw1 + aw0 * bx1 + ay0 * bz1 - az0 * by1 + ax1 * bw0 + aw1 * bx0 + ay1 * bz0 - az1 * by0; 5206 out[5] = ay0 * bw1 + aw0 * by1 + az0 * bx1 - ax0 * bz1 + ay1 * bw0 + aw1 * by0 + az1 * bx0 - ax1 * bz0; 5207 out[6] = az0 * bw1 + aw0 * bz1 + ax0 * by1 - ay0 * bx1 + az1 * bw0 + aw1 * bz0 + ax1 * by0 - ay1 * bx0; 5208 out[7] = aw0 * bw1 - ax0 * bx1 - ay0 * by1 - az0 * bz1 + aw1 * bw0 - ax1 * bx0 - ay1 * by0 - az1 * bz0; 5209 return out; 5210} 5211/** 5212 * Alias for {@link quat2.multiply} 5213 * @function 5214 */ 5215 5216var mul = multiply; 5217/** 5218 * Scales a dual quat by a scalar number 5219 * 5220 * @param {quat2} out the receiving dual quat 5221 * @param {quat2} a the dual quat to scale 5222 * @param {Number} b amount to scale the dual quat by 5223 * @returns {quat2} out 5224 * @function 5225 */ 5226 5227function scale(out, a, b) { 5228 out[0] = a[0] * b; 5229 out[1] = a[1] * b; 5230 out[2] = a[2] * b; 5231 out[3] = a[3] * b; 5232 out[4] = a[4] * b; 5233 out[5] = a[5] * b; 5234 out[6] = a[6] * b; 5235 out[7] = a[7] * b; 5236 return out; 5237} 5238/** 5239 * Calculates the dot product of two dual quat's (The dot product of the real parts) 5240 * 5241 * @param {quat2} a the first operand 5242 * @param {quat2} b the second operand 5243 * @returns {Number} dot product of a and b 5244 * @function 5245 */ 5246 5247var dot = _quat_js__WEBPACK_IMPORTED_MODULE_1__.dot; 5248/** 5249 * Performs a linear interpolation between two dual quats's 5250 * NOTE: The resulting dual quaternions won't always be normalized (The error is most noticeable when t = 0.5) 5251 * 5252 * @param {quat2} out the receiving dual quat 5253 * @param {quat2} a the first operand 5254 * @param {quat2} b the second operand 5255 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs 5256 * @returns {quat2} out 5257 */ 5258 5259function lerp(out, a, b, t) { 5260 var mt = 1 - t; 5261 if (dot(a, b) < 0) t = -t; 5262 out[0] = a[0] * mt + b[0] * t; 5263 out[1] = a[1] * mt + b[1] * t; 5264 out[2] = a[2] * mt + b[2] * t; 5265 out[3] = a[3] * mt + b[3] * t; 5266 out[4] = a[4] * mt + b[4] * t; 5267 out[5] = a[5] * mt + b[5] * t; 5268 out[6] = a[6] * mt + b[6] * t; 5269 out[7] = a[7] * mt + b[7] * t; 5270 return out; 5271} 5272/** 5273 * Calculates the inverse of a dual quat. If they are normalized, conjugate is cheaper 5274 * 5275 * @param {quat2} out the receiving dual quaternion 5276 * @param {quat2} a dual quat to calculate inverse of 5277 * @returns {quat2} out 5278 */ 5279 5280function invert(out, a) { 5281 var sqlen = squaredLength(a); 5282 out[0] = -a[0] / sqlen; 5283 out[1] = -a[1] / sqlen; 5284 out[2] = -a[2] / sqlen; 5285 out[3] = a[3] / sqlen; 5286 out[4] = -a[4] / sqlen; 5287 out[5] = -a[5] / sqlen; 5288 out[6] = -a[6] / sqlen; 5289 out[7] = a[7] / sqlen; 5290 return out; 5291} 5292/** 5293 * Calculates the conjugate of a dual quat 5294 * If the dual quaternion is normalized, this function is faster than quat2.inverse and produces the same result. 5295 * 5296 * @param {quat2} out the receiving quaternion 5297 * @param {quat2} a quat to calculate conjugate of 5298 * @returns {quat2} out 5299 */ 5300 5301function conjugate(out, a) { 5302 out[0] = -a[0]; 5303 out[1] = -a[1]; 5304 out[2] = -a[2]; 5305 out[3] = a[3]; 5306 out[4] = -a[4]; 5307 out[5] = -a[5]; 5308 out[6] = -a[6]; 5309 out[7] = a[7]; 5310 return out; 5311} 5312/** 5313 * Calculates the length of a dual quat 5314 * 5315 * @param {quat2} a dual quat to calculate length of 5316 * @returns {Number} length of a 5317 * @function 5318 */ 5319 5320var length = _quat_js__WEBPACK_IMPORTED_MODULE_1__.length; 5321/** 5322 * Alias for {@link quat2.length} 5323 * @function 5324 */ 5325 5326var len = length; 5327/** 5328 * Calculates the squared length of a dual quat 5329 * 5330 * @param {quat2} a dual quat to calculate squared length of 5331 * @returns {Number} squared length of a 5332 * @function 5333 */ 5334 5335var squaredLength = _quat_js__WEBPACK_IMPORTED_MODULE_1__.squaredLength; 5336/** 5337 * Alias for {@link quat2.squaredLength} 5338 * @function 5339 */ 5340 5341var sqrLen = squaredLength; 5342/** 5343 * Normalize a dual quat 5344 * 5345 * @param {quat2} out the receiving dual quaternion 5346 * @param {quat2} a dual quaternion to normalize 5347 * @returns {quat2} out 5348 * @function 5349 */ 5350 5351function normalize(out, a) { 5352 var magnitude = squaredLength(a); 5353 5354 if (magnitude > 0) { 5355 magnitude = Math.sqrt(magnitude); 5356 var a0 = a[0] / magnitude; 5357 var a1 = a[1] / magnitude; 5358 var a2 = a[2] / magnitude; 5359 var a3 = a[3] / magnitude; 5360 var b0 = a[4]; 5361 var b1 = a[5]; 5362 var b2 = a[6]; 5363 var b3 = a[7]; 5364 var a_dot_b = a0 * b0 + a1 * b1 + a2 * b2 + a3 * b3; 5365 out[0] = a0; 5366 out[1] = a1; 5367 out[2] = a2; 5368 out[3] = a3; 5369 out[4] = (b0 - a0 * a_dot_b) / magnitude; 5370 out[5] = (b1 - a1 * a_dot_b) / magnitude; 5371 out[6] = (b2 - a2 * a_dot_b) / magnitude; 5372 out[7] = (b3 - a3 * a_dot_b) / magnitude; 5373 } 5374 5375 return out; 5376} 5377/** 5378 * Returns a string representation of a dual quatenion 5379 * 5380 * @param {quat2} a dual quaternion to represent as a string 5381 * @returns {String} string representation of the dual quat 5382 */ 5383 5384function str(a) { 5385 return 'quat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ')'; 5386} 5387/** 5388 * Returns whether or not the dual quaternions have exactly the same elements in the same position (when compared with ===) 5389 * 5390 * @param {quat2} a the first dual quaternion. 5391 * @param {quat2} b the second dual quaternion. 5392 * @returns {Boolean} true if the dual quaternions are equal, false otherwise. 5393 */ 5394 5395function exactEquals(a, b) { 5396 return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7]; 5397} 5398/** 5399 * Returns whether or not the dual quaternions have approximately the same elements in the same position. 5400 * 5401 * @param {quat2} a the first dual quat. 5402 * @param {quat2} b the second dual quat. 5403 * @returns {Boolean} true if the dual quats are equal, false otherwise. 5404 */ 5405 5406function equals(a, b) { 5407 var a0 = a[0], 5408 a1 = a[1], 5409 a2 = a[2], 5410 a3 = a[3], 5411 a4 = a[4], 5412 a5 = a[5], 5413 a6 = a[6], 5414 a7 = a[7]; 5415 var b0 = b[0], 5416 b1 = b[1], 5417 b2 = b[2], 5418 b3 = b[3], 5419 b4 = b[4], 5420 b5 = b[5], 5421 b6 = b[6], 5422 b7 = b[7]; 5423 return Math.abs(a0 - b0) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)); 5424} 5425 5426/***/ }), 5427
vendor: 17,429 bytes, lines 5428-6127
5428/***/ "./node_modules/gl-matrix/esm/vec2.js": 5429/*!********************************************!*\ 5430 !*** ./node_modules/gl-matrix/esm/vec2.js ***! 5431 \********************************************/ 5432/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { 5433 5434"use strict"; 5435__webpack_require__.r(__webpack_exports__); 5436/* harmony export */ __webpack_require__.d(__webpack_exports__, { 5437/* harmony export */ add: () => (/* binding */ add), 5438/* harmony export */ angle: () => (/* binding */ angle), 5439/* harmony export */ ceil: () => (/* binding */ ceil), 5440/* harmony export */ clone: () => (/* binding */ clone), 5441/* harmony export */ copy: () => (/* binding */ copy), 5442/* harmony export */ create: () => (/* binding */ create), 5443/* harmony export */ cross: () => (/* binding */ cross), 5444/* harmony export */ dist: () => (/* binding */ dist), 5445/* harmony export */ distance: () => (/* binding */ distance), 5446/* harmony export */ div: () => (/* binding */ div), 5447/* harmony export */ divide: () => (/* binding */ divide), 5448/* harmony export */ dot: () => (/* binding */ dot), 5449/* harmony export */ equals: () => (/* binding */ equals), 5450/* harmony export */ exactEquals: () => (/* binding */ exactEquals), 5451/* harmony export */ floor: () => (/* binding */ floor), 5452/* harmony export */ forEach: () => (/* binding */ forEach), 5453/* harmony export */ fromValues: () => (/* binding */ fromValues), 5454/* harmony export */ inverse: () => (/* binding */ inverse), 5455/* harmony export */ len: () => (/* binding */ len), 5456/* harmony export */ length: () => (/* binding */ length), 5457/* harmony export */ lerp: () => (/* binding */ lerp), 5458/* harmony export */ max: () => (/* binding */ max), 5459/* harmony export */ min: () => (/* binding */ min), 5460/* harmony export */ mul: () => (/* binding */ mul), 5461/* harmony export */ multiply: () => (/* binding */ multiply), 5462/* harmony export */ negate: () => (/* binding */ negate), 5463/* harmony export */ normalize: () => (/* binding */ normalize), 5464/* harmony export */ random: () => (/* binding */ random), 5465/* harmony export */ rotate: () => (/* binding */ rotate), 5466/* harmony export */ round: () => (/* binding */ round), 5467/* harmony export */ scale: () => (/* binding */ scale), 5468/* harmony export */ scaleAndAdd: () => (/* binding */ scaleAndAdd), 5469/* harmony export */ set: () => (/* binding */ set), 5470/* harmony export */ sqrDist: () => (/* binding */ sqrDist), 5471/* harmony export */ sqrLen: () => (/* binding */ sqrLen), 5472/* harmony export */ squaredDistance: () => (/* binding */ squaredDistance), 5473/* harmony export */ squaredLength: () => (/* binding */ squaredLength), 5474/* harmony export */ str: () => (/* binding */ str), 5475/* harmony export */ sub: () => (/* binding */ sub), 5476/* harmony export */ subtract: () => (/* binding */ subtract), 5477/* harmony export */ transformMat2: () => (/* binding */ transformMat2), 5478/* harmony export */ transformMat2d: () => (/* binding */ transformMat2d), 5479/* harmony export */ transformMat3: () => (/* binding */ transformMat3), 5480/* harmony export */ transformMat4: () => (/* binding */ transformMat4), 5481/* harmony export */ zero: () => (/* binding */ zero) 5482/* harmony export */ }); 5483/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common.js */ "./node_modules/gl-matrix/esm/common.js"); 5484 5485/** 5486 * 2 Dimensional Vector 5487 * @module vec2 5488 */ 5489 5490/** 5491 * Creates a new, empty vec2 5492 * 5493 * @returns {vec2} a new 2D vector 5494 */ 5495 5496function create() { 5497 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(2); 5498 5499 if (_common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE != Float32Array) { 5500 out[0] = 0; 5501 out[1] = 0; 5502 } 5503 5504 return out; 5505} 5506/** 5507 * Creates a new vec2 initialized with values from an existing vector 5508 * 5509 * @param {vec2} a vector to clone 5510 * @returns {vec2} a new 2D vector 5511 */ 5512 5513function clone(a) { 5514 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(2); 5515 out[0] = a[0]; 5516 out[1] = a[1]; 5517 return out; 5518} 5519/** 5520 * Creates a new vec2 initialized with the given values 5521 * 5522 * @param {Number} x X component 5523 * @param {Number} y Y component 5524 * @returns {vec2} a new 2D vector 5525 */ 5526 5527function fromValues(x, y) { 5528 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(2); 5529 out[0] = x; 5530 out[1] = y; 5531 return out; 5532} 5533/** 5534 * Copy the values from one vec2 to another 5535 * 5536 * @param {vec2} out the receiving vector 5537 * @param {vec2} a the source vector 5538 * @returns {vec2} out 5539 */ 5540 5541function copy(out, a) { 5542 out[0] = a[0]; 5543 out[1] = a[1]; 5544 return out; 5545} 5546/** 5547 * Set the components of a vec2 to the given values 5548 * 5549 * @param {vec2} out the receiving vector 5550 * @param {Number} x X component 5551 * @param {Number} y Y component 5552 * @returns {vec2} out 5553 */ 5554 5555function set(out, x, y) { 5556 out[0] = x; 5557 out[1] = y; 5558 return out; 5559} 5560/** 5561 * Adds two vec2's 5562 * 5563 * @param {vec2} out the receiving vector 5564 * @param {vec2} a the first operand 5565 * @param {vec2} b the second operand 5566 * @returns {vec2} out 5567 */ 5568 5569function add(out, a, b) { 5570 out[0] = a[0] + b[0]; 5571 out[1] = a[1] + b[1]; 5572 return out; 5573} 5574/** 5575 * Subtracts vector b from vector a 5576 * 5577 * @param {vec2} out the receiving vector 5578 * @param {vec2} a the first operand 5579 * @param {vec2} b the second operand 5580 * @returns {vec2} out 5581 */ 5582 5583function subtract(out, a, b) { 5584 out[0] = a[0] - b[0]; 5585 out[1] = a[1] - b[1]; 5586 return out; 5587} 5588/** 5589 * Multiplies two vec2's 5590 * 5591 * @param {vec2} out the receiving vector 5592 * @param {vec2} a the first operand 5593 * @param {vec2} b the second operand 5594 * @returns {vec2} out 5595 */ 5596 5597function multiply(out, a, b) { 5598 out[0] = a[0] * b[0]; 5599 out[1] = a[1] * b[1]; 5600 return out; 5601} 5602/** 5603 * Divides two vec2's 5604 * 5605 * @param {vec2} out the receiving vector 5606 * @param {vec2} a the first operand 5607 * @param {vec2} b the second operand 5608 * @returns {vec2} out 5609 */ 5610 5611function divide(out, a, b) { 5612 out[0] = a[0] / b[0]; 5613 out[1] = a[1] / b[1]; 5614 return out; 5615} 5616/** 5617 * Math.ceil the components of a vec2 5618 * 5619 * @param {vec2} out the receiving vector 5620 * @param {vec2} a vector to ceil 5621 * @returns {vec2} out 5622 */ 5623 5624function ceil(out, a) { 5625 out[0] = Math.ceil(a[0]); 5626 out[1] = Math.ceil(a[1]); 5627 return out; 5628} 5629/** 5630 * Math.floor the components of a vec2 5631 * 5632 * @param {vec2} out the receiving vector 5633 * @param {vec2} a vector to floor 5634 * @returns {vec2} out 5635 */ 5636 5637function floor(out, a) { 5638 out[0] = Math.floor(a[0]); 5639 out[1] = Math.floor(a[1]); 5640 return out; 5641} 5642/** 5643 * Returns the minimum of two vec2's 5644 * 5645 * @param {vec2} out the receiving vector 5646 * @param {vec2} a the first operand 5647 * @param {vec2} b the second operand 5648 * @returns {vec2} out 5649 */ 5650 5651function min(out, a, b) { 5652 out[0] = Math.min(a[0], b[0]); 5653 out[1] = Math.min(a[1], b[1]); 5654 return out; 5655} 5656/** 5657 * Returns the maximum of two vec2's 5658 * 5659 * @param {vec2} out the receiving vector 5660 * @param {vec2} a the first operand 5661 * @param {vec2} b the second operand 5662 * @returns {vec2} out 5663 */ 5664 5665function max(out, a, b) { 5666 out[0] = Math.max(a[0], b[0]); 5667 out[1] = Math.max(a[1], b[1]); 5668 return out; 5669} 5670/** 5671 * Math.round the components of a vec2 5672 * 5673 * @param {vec2} out the receiving vector 5674 * @param {vec2} a vector to round 5675 * @returns {vec2} out 5676 */ 5677 5678function round(out, a) { 5679 out[0] = Math.round(a[0]); 5680 out[1] = Math.round(a[1]); 5681 return out; 5682} 5683/** 5684 * Scales a vec2 by a scalar number 5685 * 5686 * @param {vec2} out the receiving vector 5687 * @param {vec2} a the vector to scale 5688 * @param {Number} b amount to scale the vector by 5689 * @returns {vec2} out 5690 */ 5691 5692function scale(out, a, b) { 5693 out[0] = a[0] * b; 5694 out[1] = a[1] * b; 5695 return out; 5696} 5697/** 5698 * Adds two vec2's after scaling the second operand by a scalar value 5699 * 5700 * @param {vec2} out the receiving vector 5701 * @param {vec2} a the first operand 5702 * @param {vec2} b the second operand 5703 * @param {Number} scale the amount to scale b by before adding 5704 * @returns {vec2} out 5705 */ 5706 5707function scaleAndAdd(out, a, b, scale) { 5708 out[0] = a[0] + b[0] * scale; 5709 out[1] = a[1] + b[1] * scale; 5710 return out; 5711} 5712/** 5713 * Calculates the euclidian distance between two vec2's 5714 * 5715 * @param {vec2} a the first operand 5716 * @param {vec2} b the second operand 5717 * @returns {Number} distance between a and b 5718 */ 5719 5720function distance(a, b) { 5721 var x = b[0] - a[0], 5722 y = b[1] - a[1]; 5723 return Math.hypot(x, y); 5724} 5725/** 5726 * Calculates the squared euclidian distance between two vec2's 5727 * 5728 * @param {vec2} a the first operand 5729 * @param {vec2} b the second operand 5730 * @returns {Number} squared distance between a and b 5731 */ 5732 5733function squaredDistance(a, b) { 5734 var x = b[0] - a[0], 5735 y = b[1] - a[1]; 5736 return x * x + y * y; 5737} 5738/** 5739 * Calculates the length of a vec2 5740 * 5741 * @param {vec2} a vector to calculate length of 5742 * @returns {Number} length of a 5743 */ 5744 5745function length(a) { 5746 var x = a[0], 5747 y = a[1]; 5748 return Math.hypot(x, y); 5749} 5750/** 5751 * Calculates the squared length of a vec2 5752 * 5753 * @param {vec2} a vector to calculate squared length of 5754 * @returns {Number} squared length of a 5755 */ 5756 5757function squaredLength(a) { 5758 var x = a[0], 5759 y = a[1]; 5760 return x * x + y * y; 5761} 5762/** 5763 * Negates the components of a vec2 5764 * 5765 * @param {vec2} out the receiving vector 5766 * @param {vec2} a vector to negate 5767 * @returns {vec2} out 5768 */ 5769 5770function negate(out, a) { 5771 out[0] = -a[0]; 5772 out[1] = -a[1]; 5773 return out; 5774} 5775/** 5776 * Returns the inverse of the components of a vec2 5777 * 5778 * @param {vec2} out the receiving vector 5779 * @param {vec2} a vector to invert 5780 * @returns {vec2} out 5781 */ 5782 5783function inverse(out, a) { 5784 out[0] = 1.0 / a[0]; 5785 out[1] = 1.0 / a[1]; 5786 return out; 5787} 5788/** 5789 * Normalize a vec2 5790 * 5791 * @param {vec2} out the receiving vector 5792 * @param {vec2} a vector to normalize 5793 * @returns {vec2} out 5794 */ 5795 5796function normalize(out, a) { 5797 var x = a[0], 5798 y = a[1]; 5799 var len = x * x + y * y; 5800 5801 if (len > 0) { 5802 //TODO: evaluate use of glm_invsqrt here? 5803 len = 1 / Math.sqrt(len); 5804 } 5805 5806 out[0] = a[0] * len; 5807 out[1] = a[1] * len; 5808 return out; 5809} 5810/** 5811 * Calculates the dot product of two vec2's 5812 * 5813 * @param {vec2} a the first operand 5814 * @param {vec2} b the second operand 5815 * @returns {Number} dot product of a and b 5816 */ 5817 5818function dot(a, b) { 5819 return a[0] * b[0] + a[1] * b[1]; 5820} 5821/** 5822 * Computes the cross product of two vec2's 5823 * Note that the cross product must by definition produce a 3D vector 5824 * 5825 * @param {vec3} out the receiving vector 5826 * @param {vec2} a the first operand 5827 * @param {vec2} b the second operand 5828 * @returns {vec3} out 5829 */ 5830 5831function cross(out, a, b) { 5832 var z = a[0] * b[1] - a[1] * b[0]; 5833 out[0] = out[1] = 0; 5834 out[2] = z; 5835 return out; 5836} 5837/** 5838 * Performs a linear interpolation between two vec2's 5839 * 5840 * @param {vec2} out the receiving vector 5841 * @param {vec2} a the first operand 5842 * @param {vec2} b the second operand 5843 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs 5844 * @returns {vec2} out 5845 */ 5846 5847function lerp(out, a, b, t) { 5848 var ax = a[0], 5849 ay = a[1]; 5850 out[0] = ax + t * (b[0] - ax); 5851 out[1] = ay + t * (b[1] - ay); 5852 return out; 5853} 5854/** 5855 * Generates a random vector with the given scale 5856 * 5857 * @param {vec2} out the receiving vector 5858 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned 5859 * @returns {vec2} out 5860 */ 5861 5862function random(out, scale) { 5863 scale = scale || 1.0; 5864 var r = _common_js__WEBPACK_IMPORTED_MODULE_0__.RANDOM() * 2.0 * Math.PI; 5865 out[0] = Math.cos(r) * scale; 5866 out[1] = Math.sin(r) * scale; 5867 return out; 5868} 5869/** 5870 * Transforms the vec2 with a mat2 5871 * 5872 * @param {vec2} out the receiving vector 5873 * @param {vec2} a the vector to transform 5874 * @param {mat2} m matrix to transform with 5875 * @returns {vec2} out 5876 */ 5877 5878function transformMat2(out, a, m) { 5879 var x = a[0], 5880 y = a[1]; 5881 out[0] = m[0] * x + m[2] * y; 5882 out[1] = m[1] * x + m[3] * y; 5883 return out; 5884} 5885/** 5886 * Transforms the vec2 with a mat2d 5887 * 5888 * @param {vec2} out the receiving vector 5889 * @param {vec2} a the vector to transform 5890 * @param {mat2d} m matrix to transform with 5891 * @returns {vec2} out 5892 */ 5893 5894function transformMat2d(out, a, m) { 5895 var x = a[0], 5896 y = a[1]; 5897 out[0] = m[0] * x + m[2] * y + m[4]; 5898 out[1] = m[1] * x + m[3] * y + m[5]; 5899 return out; 5900} 5901/** 5902 * Transforms the vec2 with a mat3 5903 * 3rd vector component is implicitly '1' 5904 * 5905 * @param {vec2} out the receiving vector 5906 * @param {vec2} a the vector to transform 5907 * @param {mat3} m matrix to transform with 5908 * @returns {vec2} out 5909 */ 5910 5911function transformMat3(out, a, m) { 5912 var x = a[0], 5913 y = a[1]; 5914 out[0] = m[0] * x + m[3] * y + m[6]; 5915 out[1] = m[1] * x + m[4] * y + m[7]; 5916 return out; 5917} 5918/** 5919 * Transforms the vec2 with a mat4 5920 * 3rd vector component is implicitly '0' 5921 * 4th vector component is implicitly '1' 5922 * 5923 * @param {vec2} out the receiving vector 5924 * @param {vec2} a the vector to transform 5925 * @param {mat4} m matrix to transform with 5926 * @returns {vec2} out 5927 */ 5928 5929function transformMat4(out, a, m) { 5930 var x = a[0]; 5931 var y = a[1]; 5932 out[0] = m[0] * x + m[4] * y + m[12]; 5933 out[1] = m[1] * x + m[5] * y + m[13]; 5934 return out; 5935} 5936/** 5937 * Rotate a 2D vector 5938 * @param {vec2} out The receiving vec2 5939 * @param {vec2} a The vec2 point to rotate 5940 * @param {vec2} b The origin of the rotation 5941 * @param {Number} c The angle of rotation 5942 * @returns {vec2} out 5943 */ 5944 5945function rotate(out, a, b, c) { 5946 //Translate point to the origin 5947 var p0 = a[0] - b[0], 5948 p1 = a[1] - b[1], 5949 sinC = Math.sin(c), 5950 cosC = Math.cos(c); //perform rotation and translate to correct position 5951 5952 out[0] = p0 * cosC - p1 * sinC + b[0]; 5953 out[1] = p0 * sinC + p1 * cosC + b[1]; 5954 return out; 5955} 5956/** 5957 * Get the angle between two 2D vectors 5958 * @param {vec2} a The first operand 5959 * @param {vec2} b The second operand 5960 * @returns {Number} The angle in radians 5961 */ 5962 5963function angle(a, b) { 5964 var x1 = a[0], 5965 y1 = a[1], 5966 x2 = b[0], 5967 y2 = b[1]; 5968 var len1 = x1 * x1 + y1 * y1; 5969 5970 if (len1 > 0) { 5971 //TODO: evaluate use of glm_invsqrt here? 5972 len1 = 1 / Math.sqrt(len1); 5973 } 5974 5975 var len2 = x2 * x2 + y2 * y2; 5976 5977 if (len2 > 0) { 5978 //TODO: evaluate use of glm_invsqrt here? 5979 len2 = 1 / Math.sqrt(len2); 5980 } 5981 5982 var cosine = (x1 * x2 + y1 * y2) * len1 * len2; 5983 5984 if (cosine > 1.0) { 5985 return 0; 5986 } else if (cosine < -1.0) { 5987 return Math.PI; 5988 } else { 5989 return Math.acos(cosine); 5990 } 5991} 5992/** 5993 * Set the components of a vec2 to zero 5994 * 5995 * @param {vec2} out the receiving vector 5996 * @returns {vec2} out 5997 */ 5998 5999function zero(out) { 6000 out[0] = 0.0; 6001 out[1] = 0.0; 6002 return out; 6003} 6004/** 6005 * Returns a string representation of a vector 6006 * 6007 * @param {vec2} a vector to represent as a string 6008 * @returns {String} string representation of the vector 6009 */ 6010 6011function str(a) { 6012 return 'vec2(' + a[0] + ', ' + a[1] + ')'; 6013} 6014/** 6015 * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) 6016 * 6017 * @param {vec2} a The first vector. 6018 * @param {vec2} b The second vector. 6019 * @returns {Boolean} True if the vectors are equal, false otherwise. 6020 */ 6021 6022function exactEquals(a, b) { 6023 return a[0] === b[0] && a[1] === b[1]; 6024} 6025/** 6026 * Returns whether or not the vectors have approximately the same elements in the same position. 6027 * 6028 * @param {vec2} a The first vector. 6029 * @param {vec2} b The second vector. 6030 * @returns {Boolean} True if the vectors are equal, false otherwise. 6031 */ 6032 6033function equals(a, b) { 6034 var a0 = a[0], 6035 a1 = a[1]; 6036 var b0 = b[0], 6037 b1 = b[1]; 6038 return Math.abs(a0 - b0) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)); 6039} 6040/** 6041 * Alias for {@link vec2.length} 6042 * @function 6043 */ 6044 6045var len = length; 6046/** 6047 * Alias for {@link vec2.subtract} 6048 * @function 6049 */ 6050 6051var sub = subtract; 6052/** 6053 * Alias for {@link vec2.multiply} 6054 * @function 6055 */ 6056 6057var mul = multiply; 6058/** 6059 * Alias for {@link vec2.divide} 6060 * @function 6061 */ 6062 6063var div = divide; 6064/** 6065 * Alias for {@link vec2.distance} 6066 * @function 6067 */ 6068 6069var dist = distance; 6070/** 6071 * Alias for {@link vec2.squaredDistance} 6072 * @function 6073 */ 6074 6075var sqrDist = squaredDistance; 6076/** 6077 * Alias for {@link vec2.squaredLength} 6078 * @function 6079 */ 6080 6081var sqrLen = squaredLength; 6082/** 6083 * Perform some operation over an array of vec2s. 6084 * 6085 * @param {Array} a the array of vectors to iterate over 6086 * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed 6087 * @param {Number} offset Number of elements to skip at the beginning of the array 6088 * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array 6089 * @param {Function} fn Function to call for each vector in the array 6090 * @param {Object} [arg] additional argument to pass to fn 6091 * @returns {Array} a 6092 * @function 6093 */ 6094 6095var forEach = function () { 6096 var vec = create(); 6097 return function (a, stride, offset, count, fn, arg) { 6098 var i, l; 6099 6100 if (!stride) { 6101 stride = 2; 6102 } 6103 6104 if (!offset) { 6105 offset = 0; 6106 } 6107 6108 if (count) { 6109 l = Math.min(count * stride + offset, a.length); 6110 } else { 6111 l = a.length; 6112 } 6113 6114 for (i = offset; i < l; i += stride) { 6115 vec[0] = a[i]; 6116 vec[1] = a[i + 1]; 6117 fn(vec, vec, arg); 6118 a[i] = vec[0]; 6119 a[i + 1] = vec[1]; 6120 } 6121 6122 return a; 6123 }; 6124}(); 6125 6126/***/ }), 6127
vendor: 22,405 bytes, lines 6128-6978
6128/***/ "./node_modules/gl-matrix/esm/vec3.js": 6129/*!********************************************!*\ 6130 !*** ./node_modules/gl-matrix/esm/vec3.js ***! 6131 \********************************************/ 6132/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { 6133 6134"use strict"; 6135__webpack_require__.r(__webpack_exports__); 6136/* harmony export */ __webpack_require__.d(__webpack_exports__, { 6137/* harmony export */ add: () => (/* binding */ add), 6138/* harmony export */ angle: () => (/* binding */ angle), 6139/* harmony export */ bezier: () => (/* binding */ bezier), 6140/* harmony export */ ceil: () => (/* binding */ ceil), 6141/* harmony export */ clone: () => (/* binding */ clone), 6142/* harmony export */ copy: () => (/* binding */ copy), 6143/* harmony export */ create: () => (/* binding */ create), 6144/* harmony export */ cross: () => (/* binding */ cross), 6145/* harmony export */ dist: () => (/* binding */ dist), 6146/* harmony export */ distance: () => (/* binding */ distance), 6147/* harmony export */ div: () => (/* binding */ div), 6148/* harmony export */ divide: () => (/* binding */ divide), 6149/* harmony export */ dot: () => (/* binding */ dot), 6150/* harmony export */ equals: () => (/* binding */ equals), 6151/* harmony export */ exactEquals: () => (/* binding */ exactEquals), 6152/* harmony export */ floor: () => (/* binding */ floor), 6153/* harmony export */ forEach: () => (/* binding */ forEach), 6154/* harmony export */ fromValues: () => (/* binding */ fromValues), 6155/* harmony export */ hermite: () => (/* binding */ hermite), 6156/* harmony export */ inverse: () => (/* binding */ inverse), 6157/* harmony export */ len: () => (/* binding */ len), 6158/* harmony export */ length: () => (/* binding */ length), 6159/* harmony export */ lerp: () => (/* binding */ lerp), 6160/* harmony export */ max: () => (/* binding */ max), 6161/* harmony export */ min: () => (/* binding */ min), 6162/* harmony export */ mul: () => (/* binding */ mul), 6163/* harmony export */ multiply: () => (/* binding */ multiply), 6164/* harmony export */ negate: () => (/* binding */ negate), 6165/* harmony export */ normalize: () => (/* binding */ normalize), 6166/* harmony export */ random: () => (/* binding */ random), 6167/* harmony export */ rotateX: () => (/* binding */ rotateX), 6168/* harmony export */ rotateY: () => (/* binding */ rotateY), 6169/* harmony export */ rotateZ: () => (/* binding */ rotateZ), 6170/* harmony export */ round: () => (/* binding */ round), 6171/* harmony export */ scale: () => (/* binding */ scale), 6172/* harmony export */ scaleAndAdd: () => (/* binding */ scaleAndAdd), 6173/* harmony export */ set: () => (/* binding */ set), 6174/* harmony export */ sqrDist: () => (/* binding */ sqrDist), 6175/* harmony export */ sqrLen: () => (/* binding */ sqrLen), 6176/* harmony export */ squaredDistance: () => (/* binding */ squaredDistance), 6177/* harmony export */ squaredLength: () => (/* binding */ squaredLength), 6178/* harmony export */ str: () => (/* binding */ str), 6179/* harmony export */ sub: () => (/* binding */ sub), 6180/* harmony export */ subtract: () => (/* binding */ subtract), 6181/* harmony export */ transformMat3: () => (/* binding */ transformMat3), 6182/* harmony export */ transformMat4: () => (/* binding */ transformMat4), 6183/* harmony export */ transformQuat: () => (/* binding */ transformQuat), 6184/* harmony export */ zero: () => (/* binding */ zero) 6185/* harmony export */ }); 6186/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common.js */ "./node_modules/gl-matrix/esm/common.js"); 6187 6188/** 6189 * 3 Dimensional Vector 6190 * @module vec3 6191 */ 6192 6193/** 6194 * Creates a new, empty vec3 6195 * 6196 * @returns {vec3} a new 3D vector 6197 */ 6198 6199function create() { 6200 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(3); 6201 6202 if (_common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE != Float32Array) { 6203 out[0] = 0; 6204 out[1] = 0; 6205 out[2] = 0; 6206 } 6207 6208 return out; 6209} 6210/** 6211 * Creates a new vec3 initialized with values from an existing vector 6212 * 6213 * @param {vec3} a vector to clone 6214 * @returns {vec3} a new 3D vector 6215 */ 6216 6217function clone(a) { 6218 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(3); 6219 out[0] = a[0]; 6220 out[1] = a[1]; 6221 out[2] = a[2]; 6222 return out; 6223} 6224/** 6225 * Calculates the length of a vec3 6226 * 6227 * @param {vec3} a vector to calculate length of 6228 * @returns {Number} length of a 6229 */ 6230 6231function length(a) { 6232 var x = a[0]; 6233 var y = a[1]; 6234 var z = a[2]; 6235 return Math.hypot(x, y, z); 6236} 6237/** 6238 * Creates a new vec3 initialized with the given values 6239 * 6240 * @param {Number} x X component 6241 * @param {Number} y Y component 6242 * @param {Number} z Z component 6243 * @returns {vec3} a new 3D vector 6244 */ 6245 6246function fromValues(x, y, z) { 6247 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(3); 6248 out[0] = x; 6249 out[1] = y; 6250 out[2] = z; 6251 return out; 6252} 6253/** 6254 * Copy the values from one vec3 to another 6255 * 6256 * @param {vec3} out the receiving vector 6257 * @param {vec3} a the source vector 6258 * @returns {vec3} out 6259 */ 6260 6261function copy(out, a) { 6262 out[0] = a[0]; 6263 out[1] = a[1]; 6264 out[2] = a[2]; 6265 return out; 6266} 6267/** 6268 * Set the components of a vec3 to the given values 6269 * 6270 * @param {vec3} out the receiving vector 6271 * @param {Number} x X component 6272 * @param {Number} y Y component 6273 * @param {Number} z Z component 6274 * @returns {vec3} out 6275 */ 6276 6277function set(out, x, y, z) { 6278 out[0] = x; 6279 out[1] = y; 6280 out[2] = z; 6281 return out; 6282} 6283/** 6284 * Adds two vec3's 6285 * 6286 * @param {vec3} out the receiving vector 6287 * @param {vec3} a the first operand 6288 * @param {vec3} b the second operand 6289 * @returns {vec3} out 6290 */ 6291 6292function add(out, a, b) { 6293 out[0] = a[0] + b[0]; 6294 out[1] = a[1] + b[1]; 6295 out[2] = a[2] + b[2]; 6296 return out; 6297} 6298/** 6299 * Subtracts vector b from vector a 6300 * 6301 * @param {vec3} out the receiving vector 6302 * @param {vec3} a the first operand 6303 * @param {vec3} b the second operand 6304 * @returns {vec3} out 6305 */ 6306 6307function subtract(out, a, b) { 6308 out[0] = a[0] - b[0]; 6309 out[1] = a[1] - b[1]; 6310 out[2] = a[2] - b[2]; 6311 return out; 6312} 6313/** 6314 * Multiplies two vec3's 6315 * 6316 * @param {vec3} out the receiving vector 6317 * @param {vec3} a the first operand 6318 * @param {vec3} b the second operand 6319 * @returns {vec3} out 6320 */ 6321 6322function multiply(out, a, b) { 6323 out[0] = a[0] * b[0]; 6324 out[1] = a[1] * b[1]; 6325 out[2] = a[2] * b[2]; 6326 return out; 6327} 6328/** 6329 * Divides two vec3's 6330 * 6331 * @param {vec3} out the receiving vector 6332 * @param {vec3} a the first operand 6333 * @param {vec3} b the second operand 6334 * @returns {vec3} out 6335 */ 6336 6337function divide(out, a, b) { 6338 out[0] = a[0] / b[0]; 6339 out[1] = a[1] / b[1]; 6340 out[2] = a[2] / b[2]; 6341 return out; 6342} 6343/** 6344 * Math.ceil the components of a vec3 6345 * 6346 * @param {vec3} out the receiving vector 6347 * @param {vec3} a vector to ceil 6348 * @returns {vec3} out 6349 */ 6350 6351function ceil(out, a) { 6352 out[0] = Math.ceil(a[0]); 6353 out[1] = Math.ceil(a[1]); 6354 out[2] = Math.ceil(a[2]); 6355 return out; 6356} 6357/** 6358 * Math.floor the components of a vec3 6359 * 6360 * @param {vec3} out the receiving vector 6361 * @param {vec3} a vector to floor 6362 * @returns {vec3} out 6363 */ 6364 6365function floor(out, a) { 6366 out[0] = Math.floor(a[0]); 6367 out[1] = Math.floor(a[1]); 6368 out[2] = Math.floor(a[2]); 6369 return out; 6370} 6371/** 6372 * Returns the minimum of two vec3's 6373 * 6374 * @param {vec3} out the receiving vector 6375 * @param {vec3} a the first operand 6376 * @param {vec3} b the second operand 6377 * @returns {vec3} out 6378 */ 6379 6380function min(out, a, b) { 6381 out[0] = Math.min(a[0], b[0]); 6382 out[1] = Math.min(a[1], b[1]); 6383 out[2] = Math.min(a[2], b[2]); 6384 return out; 6385} 6386/** 6387 * Returns the maximum of two vec3's 6388 * 6389 * @param {vec3} out the receiving vector 6390 * @param {vec3} a the first operand 6391 * @param {vec3} b the second operand 6392 * @returns {vec3} out 6393 */ 6394 6395function max(out, a, b) { 6396 out[0] = Math.max(a[0], b[0]); 6397 out[1] = Math.max(a[1], b[1]); 6398 out[2] = Math.max(a[2], b[2]); 6399 return out; 6400} 6401/** 6402 * Math.round the components of a vec3 6403 * 6404 * @param {vec3} out the receiving vector 6405 * @param {vec3} a vector to round 6406 * @returns {vec3} out 6407 */ 6408 6409function round(out, a) { 6410 out[0] = Math.round(a[0]); 6411 out[1] = Math.round(a[1]); 6412 out[2] = Math.round(a[2]); 6413 return out; 6414} 6415/** 6416 * Scales a vec3 by a scalar number 6417 * 6418 * @param {vec3} out the receiving vector 6419 * @param {vec3} a the vector to scale 6420 * @param {Number} b amount to scale the vector by 6421 * @returns {vec3} out 6422 */ 6423 6424function scale(out, a, b) { 6425 out[0] = a[0] * b; 6426 out[1] = a[1] * b; 6427 out[2] = a[2] * b; 6428 return out; 6429} 6430/** 6431 * Adds two vec3's after scaling the second operand by a scalar value 6432 * 6433 * @param {vec3} out the receiving vector 6434 * @param {vec3} a the first operand 6435 * @param {vec3} b the second operand 6436 * @param {Number} scale the amount to scale b by before adding 6437 * @returns {vec3} out 6438 */ 6439 6440function scaleAndAdd(out, a, b, scale) { 6441 out[0] = a[0] + b[0] * scale; 6442 out[1] = a[1] + b[1] * scale; 6443 out[2] = a[2] + b[2] * scale; 6444 return out; 6445} 6446/** 6447 * Calculates the euclidian distance between two vec3's 6448 * 6449 * @param {vec3} a the first operand 6450 * @param {vec3} b the second operand 6451 * @returns {Number} distance between a and b 6452 */ 6453 6454function distance(a, b) { 6455 var x = b[0] - a[0]; 6456 var y = b[1] - a[1]; 6457 var z = b[2] - a[2]; 6458 return Math.hypot(x, y, z); 6459} 6460/** 6461 * Calculates the squared euclidian distance between two vec3's 6462 * 6463 * @param {vec3} a the first operand 6464 * @param {vec3} b the second operand 6465 * @returns {Number} squared distance between a and b 6466 */ 6467 6468function squaredDistance(a, b) { 6469 var x = b[0] - a[0]; 6470 var y = b[1] - a[1]; 6471 var z = b[2] - a[2]; 6472 return x * x + y * y + z * z; 6473} 6474/** 6475 * Calculates the squared length of a vec3 6476 * 6477 * @param {vec3} a vector to calculate squared length of 6478 * @returns {Number} squared length of a 6479 */ 6480 6481function squaredLength(a) { 6482 var x = a[0]; 6483 var y = a[1]; 6484 var z = a[2]; 6485 return x * x + y * y + z * z; 6486} 6487/** 6488 * Negates the components of a vec3 6489 * 6490 * @param {vec3} out the receiving vector 6491 * @param {vec3} a vector to negate 6492 * @returns {vec3} out 6493 */ 6494 6495function negate(out, a) { 6496 out[0] = -a[0]; 6497 out[1] = -a[1]; 6498 out[2] = -a[2]; 6499 return out; 6500} 6501/** 6502 * Returns the inverse of the components of a vec3 6503 * 6504 * @param {vec3} out the receiving vector 6505 * @param {vec3} a vector to invert 6506 * @returns {vec3} out 6507 */ 6508 6509function inverse(out, a) { 6510 out[0] = 1.0 / a[0]; 6511 out[1] = 1.0 / a[1]; 6512 out[2] = 1.0 / a[2]; 6513 return out; 6514} 6515/** 6516 * Normalize a vec3 6517 * 6518 * @param {vec3} out the receiving vector 6519 * @param {vec3} a vector to normalize 6520 * @returns {vec3} out 6521 */ 6522 6523function normalize(out, a) { 6524 var x = a[0]; 6525 var y = a[1]; 6526 var z = a[2]; 6527 var len = x * x + y * y + z * z; 6528 6529 if (len > 0) { 6530 //TODO: evaluate use of glm_invsqrt here? 6531 len = 1 / Math.sqrt(len); 6532 } 6533 6534 out[0] = a[0] * len; 6535 out[1] = a[1] * len; 6536 out[2] = a[2] * len; 6537 return out; 6538} 6539/** 6540 * Calculates the dot product of two vec3's 6541 * 6542 * @param {vec3} a the first operand 6543 * @param {vec3} b the second operand 6544 * @returns {Number} dot product of a and b 6545 */ 6546 6547function dot(a, b) { 6548 return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; 6549} 6550/** 6551 * Computes the cross product of two vec3's 6552 * 6553 * @param {vec3} out the receiving vector 6554 * @param {vec3} a the first operand 6555 * @param {vec3} b the second operand 6556 * @returns {vec3} out 6557 */ 6558 6559function cross(out, a, b) { 6560 var ax = a[0], 6561 ay = a[1], 6562 az = a[2]; 6563 var bx = b[0], 6564 by = b[1], 6565 bz = b[2]; 6566 out[0] = ay * bz - az * by; 6567 out[1] = az * bx - ax * bz; 6568 out[2] = ax * by - ay * bx; 6569 return out; 6570} 6571/** 6572 * Performs a linear interpolation between two vec3's 6573 * 6574 * @param {vec3} out the receiving vector 6575 * @param {vec3} a the first operand 6576 * @param {vec3} b the second operand 6577 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs 6578 * @returns {vec3} out 6579 */ 6580 6581function lerp(out, a, b, t) { 6582 var ax = a[0]; 6583 var ay = a[1]; 6584 var az = a[2]; 6585 out[0] = ax + t * (b[0] - ax); 6586 out[1] = ay + t * (b[1] - ay); 6587 out[2] = az + t * (b[2] - az); 6588 return out; 6589} 6590/** 6591 * Performs a hermite interpolation with two control points 6592 * 6593 * @param {vec3} out the receiving vector 6594 * @param {vec3} a the first operand 6595 * @param {vec3} b the second operand 6596 * @param {vec3} c the third operand 6597 * @param {vec3} d the fourth operand 6598 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs 6599 * @returns {vec3} out 6600 */ 6601 6602function hermite(out, a, b, c, d, t) { 6603 var factorTimes2 = t * t; 6604 var factor1 = factorTimes2 * (2 * t - 3) + 1; 6605 var factor2 = factorTimes2 * (t - 2) + t; 6606 var factor3 = factorTimes2 * (t - 1); 6607 var factor4 = factorTimes2 * (3 - 2 * t); 6608 out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; 6609 out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; 6610 out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; 6611 return out; 6612} 6613/** 6614 * Performs a bezier interpolation with two control points 6615 * 6616 * @param {vec3} out the receiving vector 6617 * @param {vec3} a the first operand 6618 * @param {vec3} b the second operand 6619 * @param {vec3} c the third operand 6620 * @param {vec3} d the fourth operand 6621 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs 6622 * @returns {vec3} out 6623 */ 6624 6625function bezier(out, a, b, c, d, t) { 6626 var inverseFactor = 1 - t; 6627 var inverseFactorTimesTwo = inverseFactor * inverseFactor; 6628 var factorTimes2 = t * t; 6629 var factor1 = inverseFactorTimesTwo * inverseFactor; 6630 var factor2 = 3 * t * inverseFactorTimesTwo; 6631 var factor3 = 3 * factorTimes2 * inverseFactor; 6632 var factor4 = factorTimes2 * t; 6633 out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; 6634 out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; 6635 out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; 6636 return out; 6637} 6638/** 6639 * Generates a random vector with the given scale 6640 * 6641 * @param {vec3} out the receiving vector 6642 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned 6643 * @returns {vec3} out 6644 */ 6645 6646function random(out, scale) { 6647 scale = scale || 1.0; 6648 var r = _common_js__WEBPACK_IMPORTED_MODULE_0__.RANDOM() * 2.0 * Math.PI; 6649 var z = _common_js__WEBPACK_IMPORTED_MODULE_0__.RANDOM() * 2.0 - 1.0; 6650 var zScale = Math.sqrt(1.0 - z * z) * scale; 6651 out[0] = Math.cos(r) * zScale; 6652 out[1] = Math.sin(r) * zScale; 6653 out[2] = z * scale; 6654 return out; 6655} 6656/** 6657 * Transforms the vec3 with a mat4. 6658 * 4th vector component is implicitly '1' 6659 * 6660 * @param {vec3} out the receiving vector 6661 * @param {vec3} a the vector to transform 6662 * @param {mat4} m matrix to transform with 6663 * @returns {vec3} out 6664 */ 6665 6666function transformMat4(out, a, m) { 6667 var x = a[0], 6668 y = a[1], 6669 z = a[2]; 6670 var w = m[3] * x + m[7] * y + m[11] * z + m[15]; 6671 w = w || 1.0; 6672 out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w; 6673 out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w; 6674 out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w; 6675 return out; 6676} 6677/** 6678 * Transforms the vec3 with a mat3. 6679 * 6680 * @param {vec3} out the receiving vector 6681 * @param {vec3} a the vector to transform 6682 * @param {mat3} m the 3x3 matrix to transform with 6683 * @returns {vec3} out 6684 */ 6685 6686function transformMat3(out, a, m) { 6687 var x = a[0], 6688 y = a[1], 6689 z = a[2]; 6690 out[0] = x * m[0] + y * m[3] + z * m[6]; 6691 out[1] = x * m[1] + y * m[4] + z * m[7]; 6692 out[2] = x * m[2] + y * m[5] + z * m[8]; 6693 return out; 6694} 6695/** 6696 * Transforms the vec3 with a quat 6697 * Can also be used for dual quaternions. (Multiply it with the real part) 6698 * 6699 * @param {vec3} out the receiving vector 6700 * @param {vec3} a the vector to transform 6701 * @param {quat} q quaternion to transform with 6702 * @returns {vec3} out 6703 */ 6704 6705function transformQuat(out, a, q) { 6706 // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed 6707 var qx = q[0], 6708 qy = q[1], 6709 qz = q[2], 6710 qw = q[3]; 6711 var x = a[0], 6712 y = a[1], 6713 z = a[2]; // var qvec = [qx, qy, qz]; 6714 // var uv = vec3.cross([], qvec, a); 6715 6716 var uvx = qy * z - qz * y, 6717 uvy = qz * x - qx * z, 6718 uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv); 6719 6720 var uuvx = qy * uvz - qz * uvy, 6721 uuvy = qz * uvx - qx * uvz, 6722 uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w); 6723 6724 var w2 = qw * 2; 6725 uvx *= w2; 6726 uvy *= w2; 6727 uvz *= w2; // vec3.scale(uuv, uuv, 2); 6728 6729 uuvx *= 2; 6730 uuvy *= 2; 6731 uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv)); 6732 6733 out[0] = x + uvx + uuvx; 6734 out[1] = y + uvy + uuvy; 6735 out[2] = z + uvz + uuvz; 6736 return out; 6737} 6738/** 6739 * Rotate a 3D vector around the x-axis 6740 * @param {vec3} out The receiving vec3 6741 * @param {vec3} a The vec3 point to rotate 6742 * @param {vec3} b The origin of the rotation 6743 * @param {Number} c The angle of rotation 6744 * @returns {vec3} out 6745 */ 6746 6747function rotateX(out, a, b, c) { 6748 var p = [], 6749 r = []; //Translate point to the origin 6750 6751 p[0] = a[0] - b[0]; 6752 p[1] = a[1] - b[1]; 6753 p[2] = a[2] - b[2]; //perform rotation 6754 6755 r[0] = p[0]; 6756 r[1] = p[1] * Math.cos(c) - p[2] * Math.sin(c); 6757 r[2] = p[1] * Math.sin(c) + p[2] * Math.cos(c); //translate to correct position 6758 6759 out[0] = r[0] + b[0]; 6760 out[1] = r[1] + b[1]; 6761 out[2] = r[2] + b[2]; 6762 return out; 6763} 6764/** 6765 * Rotate a 3D vector around the y-axis 6766 * @param {vec3} out The receiving vec3 6767 * @param {vec3} a The vec3 point to rotate 6768 * @param {vec3} b The origin of the rotation 6769 * @param {Number} c The angle of rotation 6770 * @returns {vec3} out 6771 */ 6772 6773function rotateY(out, a, b, c) { 6774 var p = [], 6775 r = []; //Translate point to the origin 6776 6777 p[0] = a[0] - b[0]; 6778 p[1] = a[1] - b[1]; 6779 p[2] = a[2] - b[2]; //perform rotation 6780 6781 r[0] = p[2] * Math.sin(c) + p[0] * Math.cos(c); 6782 r[1] = p[1]; 6783 r[2] = p[2] * Math.cos(c) - p[0] * Math.sin(c); //translate to correct position 6784 6785 out[0] = r[0] + b[0]; 6786 out[1] = r[1] + b[1]; 6787 out[2] = r[2] + b[2]; 6788 return out; 6789} 6790/** 6791 * Rotate a 3D vector around the z-axis 6792 * @param {vec3} out The receiving vec3 6793 * @param {vec3} a The vec3 point to rotate 6794 * @param {vec3} b The origin of the rotation 6795 * @param {Number} c The angle of rotation 6796 * @returns {vec3} out 6797 */ 6798 6799function rotateZ(out, a, b, c) { 6800 var p = [], 6801 r = []; //Translate point to the origin 6802 6803 p[0] = a[0] - b[0]; 6804 p[1] = a[1] - b[1]; 6805 p[2] = a[2] - b[2]; //perform rotation 6806 6807 r[0] = p[0] * Math.cos(c) - p[1] * Math.sin(c); 6808 r[1] = p[0] * Math.sin(c) + p[1] * Math.cos(c); 6809 r[2] = p[2]; //translate to correct position 6810 6811 out[0] = r[0] + b[0]; 6812 out[1] = r[1] + b[1]; 6813 out[2] = r[2] + b[2]; 6814 return out; 6815} 6816/** 6817 * Get the angle between two 3D vectors 6818 * @param {vec3} a The first operand 6819 * @param {vec3} b The second operand 6820 * @returns {Number} The angle in radians 6821 */ 6822 6823function angle(a, b) { 6824 var tempA = fromValues(a[0], a[1], a[2]); 6825 var tempB = fromValues(b[0], b[1], b[2]); 6826 normalize(tempA, tempA); 6827 normalize(tempB, tempB); 6828 var cosine = dot(tempA, tempB); 6829 6830 if (cosine > 1.0) { 6831 return 0; 6832 } else if (cosine < -1.0) { 6833 return Math.PI; 6834 } else { 6835 return Math.acos(cosine); 6836 } 6837} 6838/** 6839 * Set the components of a vec3 to zero 6840 * 6841 * @param {vec3} out the receiving vector 6842 * @returns {vec3} out 6843 */ 6844 6845function zero(out) { 6846 out[0] = 0.0; 6847 out[1] = 0.0; 6848 out[2] = 0.0; 6849 return out; 6850} 6851/** 6852 * Returns a string representation of a vector 6853 * 6854 * @param {vec3} a vector to represent as a string 6855 * @returns {String} string representation of the vector 6856 */ 6857 6858function str(a) { 6859 return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')'; 6860} 6861/** 6862 * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) 6863 * 6864 * @param {vec3} a The first vector. 6865 * @param {vec3} b The second vector. 6866 * @returns {Boolean} True if the vectors are equal, false otherwise. 6867 */ 6868 6869function exactEquals(a, b) { 6870 return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; 6871} 6872/** 6873 * Returns whether or not the vectors have approximately the same elements in the same position. 6874 * 6875 * @param {vec3} a The first vector. 6876 * @param {vec3} b The second vector. 6877 * @returns {Boolean} True if the vectors are equal, false otherwise. 6878 */ 6879 6880function equals(a, b) { 6881 var a0 = a[0], 6882 a1 = a[1], 6883 a2 = a[2]; 6884 var b0 = b[0], 6885 b1 = b[1], 6886 b2 = b[2]; 6887 return Math.abs(a0 - b0) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)); 6888} 6889/** 6890 * Alias for {@link vec3.subtract} 6891 * @function 6892 */ 6893 6894var sub = subtract; 6895/** 6896 * Alias for {@link vec3.multiply} 6897 * @function 6898 */ 6899 6900var mul = multiply; 6901/** 6902 * Alias for {@link vec3.divide} 6903 * @function 6904 */ 6905 6906var div = divide; 6907/** 6908 * Alias for {@link vec3.distance} 6909 * @function 6910 */ 6911 6912var dist = distance; 6913/** 6914 * Alias for {@link vec3.squaredDistance} 6915 * @function 6916 */ 6917 6918var sqrDist = squaredDistance; 6919/** 6920 * Alias for {@link vec3.length} 6921 * @function 6922 */ 6923 6924var len = length; 6925/** 6926 * Alias for {@link vec3.squaredLength} 6927 * @function 6928 */ 6929 6930var sqrLen = squaredLength; 6931/** 6932 * Perform some operation over an array of vec3s. 6933 * 6934 * @param {Array} a the array of vectors to iterate over 6935 * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed 6936 * @param {Number} offset Number of elements to skip at the beginning of the array 6937 * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array 6938 * @param {Function} fn Function to call for each vector in the array 6939 * @param {Object} [arg] additional argument to pass to fn 6940 * @returns {Array} a 6941 * @function 6942 */ 6943 6944var forEach = function () { 6945 var vec = create(); 6946 return function (a, stride, offset, count, fn, arg) { 6947 var i, l; 6948 6949 if (!stride) { 6950 stride = 3; 6951 } 6952 6953 if (!offset) { 6954 offset = 0; 6955 } 6956 6957 if (count) { 6958 l = Math.min(count * stride + offset, a.length); 6959 } else { 6960 l = a.length; 6961 } 6962 6963 for (i = offset; i < l; i += stride) { 6964 vec[0] = a[i]; 6965 vec[1] = a[i + 1]; 6966 vec[2] = a[i + 2]; 6967 fn(vec, vec, arg); 6968 a[i] = vec[0]; 6969 a[i + 1] = vec[1]; 6970 a[i + 2] = vec[2]; 6971 } 6972 6973 return a; 6974 }; 6975}(); 6976 6977/***/ }), 6978
vendor: 18,402 bytes, lines 6979-7697
6979/***/ "./node_modules/gl-matrix/esm/vec4.js": 6980/*!********************************************!*\ 6981 !*** ./node_modules/gl-matrix/esm/vec4.js ***! 6982 \********************************************/ 6983/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { 6984 6985"use strict"; 6986__webpack_require__.r(__webpack_exports__); 6987/* harmony export */ __webpack_require__.d(__webpack_exports__, { 6988/* harmony export */ add: () => (/* binding */ add), 6989/* harmony export */ ceil: () => (/* binding */ ceil), 6990/* harmony export */ clone: () => (/* binding */ clone), 6991/* harmony export */ copy: () => (/* binding */ copy), 6992/* harmony export */ create: () => (/* binding */ create), 6993/* harmony export */ cross: () => (/* binding */ cross), 6994/* harmony export */ dist: () => (/* binding */ dist), 6995/* harmony export */ distance: () => (/* binding */ distance), 6996/* harmony export */ div: () => (/* binding */ div), 6997/* harmony export */ divide: () => (/* binding */ divide), 6998/* harmony export */ dot: () => (/* binding */ dot), 6999/* harmony export */ equals: () => (/* binding */ equals), 7000/* harmony export */ exactEquals: () => (/* binding */ exactEquals), 7001/* harmony export */ floor: () => (/* binding */ floor), 7002/* harmony export */ forEach: () => (/* binding */ forEach), 7003/* harmony export */ fromValues: () => (/* binding */ fromValues), 7004/* harmony export */ inverse: () => (/* binding */ inverse), 7005/* harmony export */ len: () => (/* binding */ len), 7006/* harmony export */ length: () => (/* binding */ length), 7007/* harmony export */ lerp: () => (/* binding */ lerp), 7008/* harmony export */ max: () => (/* binding */ max), 7009/* harmony export */ min: () => (/* binding */ min), 7010/* harmony export */ mul: () => (/* binding */ mul), 7011/* harmony export */ multiply: () => (/* binding */ multiply), 7012/* harmony export */ negate: () => (/* binding */ negate), 7013/* harmony export */ normalize: () => (/* binding */ normalize), 7014/* harmony export */ random: () => (/* binding */ random), 7015/* harmony export */ round: () => (/* binding */ round), 7016/* harmony export */ scale: () => (/* binding */ scale), 7017/* harmony export */ scaleAndAdd: () => (/* binding */ scaleAndAdd), 7018/* harmony export */ set: () => (/* binding */ set), 7019/* harmony export */ sqrDist: () => (/* binding */ sqrDist), 7020/* harmony export */ sqrLen: () => (/* binding */ sqrLen), 7021/* harmony export */ squaredDistance: () => (/* binding */ squaredDistance), 7022/* harmony export */ squaredLength: () => (/* binding */ squaredLength), 7023/* harmony export */ str: () => (/* binding */ str), 7024/* harmony export */ sub: () => (/* binding */ sub), 7025/* harmony export */ subtract: () => (/* binding */ subtract), 7026/* harmony export */ transformMat4: () => (/* binding */ transformMat4), 7027/* harmony export */ transformQuat: () => (/* binding */ transformQuat), 7028/* harmony export */ zero: () => (/* binding */ zero) 7029/* harmony export */ }); 7030/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common.js */ "./node_modules/gl-matrix/esm/common.js"); 7031 7032/** 7033 * 4 Dimensional Vector 7034 * @module vec4 7035 */ 7036 7037/** 7038 * Creates a new, empty vec4 7039 * 7040 * @returns {vec4} a new 4D vector 7041 */ 7042 7043function create() { 7044 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(4); 7045 7046 if (_common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE != Float32Array) { 7047 out[0] = 0; 7048 out[1] = 0; 7049 out[2] = 0; 7050 out[3] = 0; 7051 } 7052 7053 return out; 7054} 7055/** 7056 * Creates a new vec4 initialized with values from an existing vector 7057 * 7058 * @param {vec4} a vector to clone 7059 * @returns {vec4} a new 4D vector 7060 */ 7061 7062function clone(a) { 7063 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(4); 7064 out[0] = a[0]; 7065 out[1] = a[1]; 7066 out[2] = a[2]; 7067 out[3] = a[3]; 7068 return out; 7069} 7070/** 7071 * Creates a new vec4 initialized with the given values 7072 * 7073 * @param {Number} x X component 7074 * @param {Number} y Y component 7075 * @param {Number} z Z component 7076 * @param {Number} w W component 7077 * @returns {vec4} a new 4D vector 7078 */ 7079 7080function fromValues(x, y, z, w) { 7081 var out = new _common_js__WEBPACK_IMPORTED_MODULE_0__.ARRAY_TYPE(4); 7082 out[0] = x; 7083 out[1] = y; 7084 out[2] = z; 7085 out[3] = w; 7086 return out; 7087} 7088/** 7089 * Copy the values from one vec4 to another 7090 * 7091 * @param {vec4} out the receiving vector 7092 * @param {vec4} a the source vector 7093 * @returns {vec4} out 7094 */ 7095 7096function copy(out, a) { 7097 out[0] = a[0]; 7098 out[1] = a[1]; 7099 out[2] = a[2]; 7100 out[3] = a[3]; 7101 return out; 7102} 7103/** 7104 * Set the components of a vec4 to the given values 7105 * 7106 * @param {vec4} out the receiving vector 7107 * @param {Number} x X component 7108 * @param {Number} y Y component 7109 * @param {Number} z Z component 7110 * @param {Number} w W component 7111 * @returns {vec4} out 7112 */ 7113 7114function set(out, x, y, z, w) { 7115 out[0] = x; 7116 out[1] = y; 7117 out[2] = z; 7118 out[3] = w; 7119 return out; 7120} 7121/** 7122 * Adds two vec4's 7123 * 7124 * @param {vec4} out the receiving vector 7125 * @param {vec4} a the first operand 7126 * @param {vec4} b the second operand 7127 * @returns {vec4} out 7128 */ 7129 7130function add(out, a, b) { 7131 out[0] = a[0] + b[0]; 7132 out[1] = a[1] + b[1]; 7133 out[2] = a[2] + b[2]; 7134 out[3] = a[3] + b[3]; 7135 return out; 7136} 7137/** 7138 * Subtracts vector b from vector a 7139 * 7140 * @param {vec4} out the receiving vector 7141 * @param {vec4} a the first operand 7142 * @param {vec4} b the second operand 7143 * @returns {vec4} out 7144 */ 7145 7146function subtract(out, a, b) { 7147 out[0] = a[0] - b[0]; 7148 out[1] = a[1] - b[1]; 7149 out[2] = a[2] - b[2]; 7150 out[3] = a[3] - b[3]; 7151 return out; 7152} 7153/** 7154 * Multiplies two vec4's 7155 * 7156 * @param {vec4} out the receiving vector 7157 * @param {vec4} a the first operand 7158 * @param {vec4} b the second operand 7159 * @returns {vec4} out 7160 */ 7161 7162function multiply(out, a, b) { 7163 out[0] = a[0] * b[0]; 7164 out[1] = a[1] * b[1]; 7165 out[2] = a[2] * b[2]; 7166 out[3] = a[3] * b[3]; 7167 return out; 7168} 7169/** 7170 * Divides two vec4's 7171 * 7172 * @param {vec4} out the receiving vector 7173 * @param {vec4} a the first operand 7174 * @param {vec4} b the second operand 7175 * @returns {vec4} out 7176 */ 7177 7178function divide(out, a, b) { 7179 out[0] = a[0] / b[0]; 7180 out[1] = a[1] / b[1]; 7181 out[2] = a[2] / b[2]; 7182 out[3] = a[3] / b[3]; 7183 return out; 7184} 7185/** 7186 * Math.ceil the components of a vec4 7187 * 7188 * @param {vec4} out the receiving vector 7189 * @param {vec4} a vector to ceil 7190 * @returns {vec4} out 7191 */ 7192 7193function ceil(out, a) { 7194 out[0] = Math.ceil(a[0]); 7195 out[1] = Math.ceil(a[1]); 7196 out[2] = Math.ceil(a[2]); 7197 out[3] = Math.ceil(a[3]); 7198 return out; 7199} 7200/** 7201 * Math.floor the components of a vec4 7202 * 7203 * @param {vec4} out the receiving vector 7204 * @param {vec4} a vector to floor 7205 * @returns {vec4} out 7206 */ 7207 7208function floor(out, a) { 7209 out[0] = Math.floor(a[0]); 7210 out[1] = Math.floor(a[1]); 7211 out[2] = Math.floor(a[2]); 7212 out[3] = Math.floor(a[3]); 7213 return out; 7214} 7215/** 7216 * Returns the minimum of two vec4's 7217 * 7218 * @param {vec4} out the receiving vector 7219 * @param {vec4} a the first operand 7220 * @param {vec4} b the second operand 7221 * @returns {vec4} out 7222 */ 7223 7224function min(out, a, b) { 7225 out[0] = Math.min(a[0], b[0]); 7226 out[1] = Math.min(a[1], b[1]); 7227 out[2] = Math.min(a[2], b[2]); 7228 out[3] = Math.min(a[3], b[3]); 7229 return out; 7230} 7231/** 7232 * Returns the maximum of two vec4's 7233 * 7234 * @param {vec4} out the receiving vector 7235 * @param {vec4} a the first operand 7236 * @param {vec4} b the second operand 7237 * @returns {vec4} out 7238 */ 7239 7240function max(out, a, b) { 7241 out[0] = Math.max(a[0], b[0]); 7242 out[1] = Math.max(a[1], b[1]); 7243 out[2] = Math.max(a[2], b[2]); 7244 out[3] = Math.max(a[3], b[3]); 7245 return out; 7246} 7247/** 7248 * Math.round the components of a vec4 7249 * 7250 * @param {vec4} out the receiving vector 7251 * @param {vec4} a vector to round 7252 * @returns {vec4} out 7253 */ 7254 7255function round(out, a) { 7256 out[0] = Math.round(a[0]); 7257 out[1] = Math.round(a[1]); 7258 out[2] = Math.round(a[2]); 7259 out[3] = Math.round(a[3]); 7260 return out; 7261} 7262/** 7263 * Scales a vec4 by a scalar number 7264 * 7265 * @param {vec4} out the receiving vector 7266 * @param {vec4} a the vector to scale 7267 * @param {Number} b amount to scale the vector by 7268 * @returns {vec4} out 7269 */ 7270 7271function scale(out, a, b) { 7272 out[0] = a[0] * b; 7273 out[1] = a[1] * b; 7274 out[2] = a[2] * b; 7275 out[3] = a[3] * b; 7276 return out; 7277} 7278/** 7279 * Adds two vec4's after scaling the second operand by a scalar value 7280 * 7281 * @param {vec4} out the receiving vector 7282 * @param {vec4} a the first operand 7283 * @param {vec4} b the second operand 7284 * @param {Number} scale the amount to scale b by before adding 7285 * @returns {vec4} out 7286 */ 7287 7288function scaleAndAdd(out, a, b, scale) { 7289 out[0] = a[0] + b[0] * scale; 7290 out[1] = a[1] + b[1] * scale; 7291 out[2] = a[2] + b[2] * scale; 7292 out[3] = a[3] + b[3] * scale; 7293 return out; 7294} 7295/** 7296 * Calculates the euclidian distance between two vec4's 7297 * 7298 * @param {vec4} a the first operand 7299 * @param {vec4} b the second operand 7300 * @returns {Number} distance between a and b 7301 */ 7302 7303function distance(a, b) { 7304 var x = b[0] - a[0]; 7305 var y = b[1] - a[1]; 7306 var z = b[2] - a[2]; 7307 var w = b[3] - a[3]; 7308 return Math.hypot(x, y, z, w); 7309} 7310/** 7311 * Calculates the squared euclidian distance between two vec4's 7312 * 7313 * @param {vec4} a the first operand 7314 * @param {vec4} b the second operand 7315 * @returns {Number} squared distance between a and b 7316 */ 7317 7318function squaredDistance(a, b) { 7319 var x = b[0] - a[0]; 7320 var y = b[1] - a[1]; 7321 var z = b[2] - a[2]; 7322 var w = b[3] - a[3]; 7323 return x * x + y * y + z * z + w * w; 7324} 7325/** 7326 * Calculates the length of a vec4 7327 * 7328 * @param {vec4} a vector to calculate length of 7329 * @returns {Number} length of a 7330 */ 7331 7332function length(a) { 7333 var x = a[0]; 7334 var y = a[1]; 7335 var z = a[2]; 7336 var w = a[3]; 7337 return Math.hypot(x, y, z, w); 7338} 7339/** 7340 * Calculates the squared length of a vec4 7341 * 7342 * @param {vec4} a vector to calculate squared length of 7343 * @returns {Number} squared length of a 7344 */ 7345 7346function squaredLength(a) { 7347 var x = a[0]; 7348 var y = a[1]; 7349 var z = a[2]; 7350 var w = a[3]; 7351 return x * x + y * y + z * z + w * w; 7352} 7353/** 7354 * Negates the components of a vec4 7355 * 7356 * @param {vec4} out the receiving vector 7357 * @param {vec4} a vector to negate 7358 * @returns {vec4} out 7359 */ 7360 7361function negate(out, a) { 7362 out[0] = -a[0]; 7363 out[1] = -a[1]; 7364 out[2] = -a[2]; 7365 out[3] = -a[3]; 7366 return out; 7367} 7368/** 7369 * Returns the inverse of the components of a vec4 7370 * 7371 * @param {vec4} out the receiving vector 7372 * @param {vec4} a vector to invert 7373 * @returns {vec4} out 7374 */ 7375 7376function inverse(out, a) { 7377 out[0] = 1.0 / a[0]; 7378 out[1] = 1.0 / a[1]; 7379 out[2] = 1.0 / a[2]; 7380 out[3] = 1.0 / a[3]; 7381 return out; 7382} 7383/** 7384 * Normalize a vec4 7385 * 7386 * @param {vec4} out the receiving vector 7387 * @param {vec4} a vector to normalize 7388 * @returns {vec4} out 7389 */ 7390 7391function normalize(out, a) { 7392 var x = a[0]; 7393 var y = a[1]; 7394 var z = a[2]; 7395 var w = a[3]; 7396 var len = x * x + y * y + z * z + w * w; 7397 7398 if (len > 0) { 7399 len = 1 / Math.sqrt(len); 7400 } 7401 7402 out[0] = x * len; 7403 out[1] = y * len; 7404 out[2] = z * len; 7405 out[3] = w * len; 7406 return out; 7407} 7408/** 7409 * Calculates the dot product of two vec4's 7410 * 7411 * @param {vec4} a the first operand 7412 * @param {vec4} b the second operand 7413 * @returns {Number} dot product of a and b 7414 */ 7415 7416function dot(a, b) { 7417 return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; 7418} 7419/** 7420 * Returns the cross-product of three vectors in a 4-dimensional space 7421 * 7422 * @param {vec4} result the receiving vector 7423 * @param {vec4} U the first vector 7424 * @param {vec4} V the second vector 7425 * @param {vec4} W the third vector 7426 * @returns {vec4} result 7427 */ 7428 7429function cross(out, u, v, w) { 7430 var A = v[0] * w[1] - v[1] * w[0], 7431 B = v[0] * w[2] - v[2] * w[0], 7432 C = v[0] * w[3] - v[3] * w[0], 7433 D = v[1] * w[2] - v[2] * w[1], 7434 E = v[1] * w[3] - v[3] * w[1], 7435 F = v[2] * w[3] - v[3] * w[2]; 7436 var G = u[0]; 7437 var H = u[1]; 7438 var I = u[2]; 7439 var J = u[3]; 7440 out[0] = H * F - I * E + J * D; 7441 out[1] = -(G * F) + I * C - J * B; 7442 out[2] = G * E - H * C + J * A; 7443 out[3] = -(G * D) + H * B - I * A; 7444 return out; 7445} 7446; 7447/** 7448 * Performs a linear interpolation between two vec4's 7449 * 7450 * @param {vec4} out the receiving vector 7451 * @param {vec4} a the first operand 7452 * @param {vec4} b the second operand 7453 * @param {Number} t interpolation amount, in the range [0-1], between the two inputs 7454 * @returns {vec4} out 7455 */ 7456 7457function lerp(out, a, b, t) { 7458 var ax = a[0]; 7459 var ay = a[1]; 7460 var az = a[2]; 7461 var aw = a[3]; 7462 out[0] = ax + t * (b[0] - ax); 7463 out[1] = ay + t * (b[1] - ay); 7464 out[2] = az + t * (b[2] - az); 7465 out[3] = aw + t * (b[3] - aw); 7466 return out; 7467} 7468/** 7469 * Generates a random vector with the given scale 7470 * 7471 * @param {vec4} out the receiving vector 7472 * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned 7473 * @returns {vec4} out 7474 */ 7475 7476function random(out, scale) { 7477 scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a 7478 // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646. 7479 // http://projecteuclid.org/euclid.aoms/1177692644; 7480 7481 var v1, v2, v3, v4; 7482 var s1, s2; 7483 7484 do { 7485 v1 = _common_js__WEBPACK_IMPORTED_MODULE_0__.RANDOM() * 2 - 1; 7486 v2 = _common_js__WEBPACK_IMPORTED_MODULE_0__.RANDOM() * 2 - 1; 7487 s1 = v1 * v1 + v2 * v2; 7488 } while (s1 >= 1); 7489 7490 do { 7491 v3 = _common_js__WEBPACK_IMPORTED_MODULE_0__.RANDOM() * 2 - 1; 7492 v4 = _common_js__WEBPACK_IMPORTED_MODULE_0__.RANDOM() * 2 - 1; 7493 s2 = v3 * v3 + v4 * v4; 7494 } while (s2 >= 1); 7495 7496 var d = Math.sqrt((1 - s1) / s2); 7497 out[0] = scale * v1; 7498 out[1] = scale * v2; 7499 out[2] = scale * v3 * d; 7500 out[3] = scale * v4 * d; 7501 return out; 7502} 7503/** 7504 * Transforms the vec4 with a mat4. 7505 * 7506 * @param {vec4} out the receiving vector 7507 * @param {vec4} a the vector to transform 7508 * @param {mat4} m matrix to transform with 7509 * @returns {vec4} out 7510 */ 7511 7512function transformMat4(out, a, m) { 7513 var x = a[0], 7514 y = a[1], 7515 z = a[2], 7516 w = a[3]; 7517 out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; 7518 out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; 7519 out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; 7520 out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; 7521 return out; 7522} 7523/** 7524 * Transforms the vec4 with a quat 7525 * 7526 * @param {vec4} out the receiving vector 7527 * @param {vec4} a the vector to transform 7528 * @param {quat} q quaternion to transform with 7529 * @returns {vec4} out 7530 */ 7531 7532function transformQuat(out, a, q) { 7533 var x = a[0], 7534 y = a[1], 7535 z = a[2]; 7536 var qx = q[0], 7537 qy = q[1], 7538 qz = q[2], 7539 qw = q[3]; // calculate quat * vec 7540 7541 var ix = qw * x + qy * z - qz * y; 7542 var iy = qw * y + qz * x - qx * z; 7543 var iz = qw * z + qx * y - qy * x; 7544 var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat 7545 7546 out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; 7547 out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; 7548 out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; 7549 out[3] = a[3]; 7550 return out; 7551} 7552/** 7553 * Set the components of a vec4 to zero 7554 * 7555 * @param {vec4} out the receiving vector 7556 * @returns {vec4} out 7557 */ 7558 7559function zero(out) { 7560 out[0] = 0.0; 7561 out[1] = 0.0; 7562 out[2] = 0.0; 7563 out[3] = 0.0; 7564 return out; 7565} 7566/** 7567 * Returns a string representation of a vector 7568 * 7569 * @param {vec4} a vector to represent as a string 7570 * @returns {String} string representation of the vector 7571 */ 7572 7573function str(a) { 7574 return 'vec4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')'; 7575} 7576/** 7577 * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) 7578 * 7579 * @param {vec4} a The first vector. 7580 * @param {vec4} b The second vector. 7581 * @returns {Boolean} True if the vectors are equal, false otherwise. 7582 */ 7583 7584function exactEquals(a, b) { 7585 return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3]; 7586} 7587/** 7588 * Returns whether or not the vectors have approximately the same elements in the same position. 7589 * 7590 * @param {vec4} a The first vector. 7591 * @param {vec4} b The second vector. 7592 * @returns {Boolean} True if the vectors are equal, false otherwise. 7593 */ 7594 7595function equals(a, b) { 7596 var a0 = a[0], 7597 a1 = a[1], 7598 a2 = a[2], 7599 a3 = a[3]; 7600 var b0 = b[0], 7601 b1 = b[1], 7602 b2 = b[2], 7603 b3 = b[3]; 7604 return Math.abs(a0 - b0) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= _common_js__WEBPACK_IMPORTED_MODULE_0__.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)); 7605} 7606/** 7607 * Alias for {@link vec4.subtract} 7608 * @function 7609 */ 7610 7611var sub = subtract; 7612/** 7613 * Alias for {@link vec4.multiply} 7614 * @function 7615 */ 7616 7617var mul = multiply; 7618/** 7619 * Alias for {@link vec4.divide} 7620 * @function 7621 */ 7622 7623var div = divide; 7624/** 7625 * Alias for {@link vec4.distance} 7626 * @function 7627 */ 7628 7629var dist = distance; 7630/** 7631 * Alias for {@link vec4.squaredDistance} 7632 * @function 7633 */ 7634 7635var sqrDist = squaredDistance; 7636/** 7637 * Alias for {@link vec4.length} 7638 * @function 7639 */ 7640 7641var len = length; 7642/** 7643 * Alias for {@link vec4.squaredLength} 7644 * @function 7645 */ 7646 7647var sqrLen = squaredLength; 7648/** 7649 * Perform some operation over an array of vec4s. 7650 * 7651 * @param {Array} a the array of vectors to iterate over 7652 * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed 7653 * @param {Number} offset Number of elements to skip at the beginning of the array 7654 * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array 7655 * @param {Function} fn Function to call for each vector in the array 7656 * @param {Object} [arg] additional argument to pass to fn 7657 * @returns {Array} a 7658 * @function 7659 */ 7660 7661var forEach = function () { 7662 var vec = create(); 7663 return function (a, stride, offset, count, fn, arg) { 7664 var i, l; 7665 7666 if (!stride) { 7667 stride = 4; 7668 } 7669 7670 if (!offset) { 7671 offset = 0; 7672 } 7673 7674 if (count) { 7675 l = Math.min(count * stride + offset, a.length); 7676 } else { 7677 l = a.length; 7678 } 7679 7680 for (i = offset; i < l; i += stride) { 7681 vec[0] = a[i]; 7682 vec[1] = a[i + 1]; 7683 vec[2] = a[i + 2]; 7684 vec[3] = a[i + 3]; 7685 fn(vec, vec, arg); 7686 a[i] = vec[0]; 7687 a[i + 1] = vec[1]; 7688 a[i + 2] = vec[2]; 7689 a[i + 3] = vec[3]; 7690 } 7691 7692 return a; 7693 }; 7694}(); 7695 7696/***/ }), 7697
7698/***/ "./src/core/anim.js": 7699/*!**************************!*\ 7700 !*** ./src/core/anim.js ***! 7701 \**************************/ 7702/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 7703 7704"use strict"; 7705/* harmony export */ __webpack_require__.d(__webpack_exports__, { 7706/* harmony export */ Anim: () => (/* binding */ Anim) 7707/* harmony export */ }); 7708/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/eventtarget.js"); 7709/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 7710/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./src/core/utils.js"); 7711/* harmony import */ var _anim_key_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./anim_key.js */ "./src/core/anim_key.js"); 7712 7713 7714 7715 7716 7717 7718/** 7719 * Keyframed interpolated animation. 7720 * 7721 * @class 7722 * @param cfg 7723 * @example 7724 * var anim=new CABLES.Anim(); 7725 * anim.setValue(0,0); // set value 0 at 0 seconds 7726 * anim.setValue(10,1); // set value 1 at 10 seconds 7727 * anim.getValue(5); // get value at 5 seconds - this returns 0.5 7728 */ 7729 7730class Anim extends cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"] 7731{ 7732 static EVENT_KEY_DELETE = "keyDelete"; 7733 static EVENT_CHANGE = "onChange"; 7734 static EVENT_UIATTRIB_CHANGE = "uiattrchange"; 7735 7736 static LOOP_OFF = 0; 7737 static LOOP_REPEAT = 1; 7738 static LOOP_MIRROR = 2; 7739 static LOOP_OFFSET = 3; 7740 7741 static EASING_LINEAR = 0; 7742 static EASING_ABSOLUTE = 1; 7743 static EASING_SMOOTHSTEP = 2; 7744 static EASING_SMOOTHERSTEP = 3; 7745 static EASING_CUBICSPLINE = 4; 7746 7747 static EASING_CUBIC_IN = 5; 7748 static EASING_CUBIC_OUT = 6; 7749 static EASING_CUBIC_INOUT = 7; 7750 7751 static EASING_EXPO_IN = 8; 7752 static EASING_EXPO_OUT = 9; 7753 static EASING_EXPO_INOUT = 10; 7754 7755 static EASING_SIN_IN = 11; 7756 static EASING_SIN_OUT = 12; 7757 static EASING_SIN_INOUT = 13; 7758 7759 static EASING_BACK_IN = 14; 7760 static EASING_BACK_OUT = 15; 7761 static EASING_BACK_INOUT = 16; 7762 7763 static EASING_ELASTIC_IN = 17; 7764 static EASING_ELASTIC_OUT = 18; 7765 7766 static EASING_BOUNCE_IN = 19; 7767 static EASING_BOUNCE_OUT = 21; 7768 7769 static EASING_QUART_IN = 22; 7770 static EASING_QUART_OUT = 23; 7771 static EASING_QUART_INOUT = 24; 7772 7773 static EASING_QUINT_IN = 25; 7774 static EASING_QUINT_OUT = 26; 7775 static EASING_QUINT_INOUT = 27; 7776 7777 static EASINGNAMES = ["linear", "absolute", "smoothstep", "smootherstep", "Cubic In", "Cubic Out", "Cubic In Out", "Expo In", "Expo Out", "Expo In Out", "Sin In", "Sin Out", "Sin In Out", "Quart In", "Quart Out", "Quart In Out", "Quint In", "Quint Out", "Quint In Out", "Back In", "Back Out", "Back In Out", "Elastic In", "Elastic Out", "Bounce In", "Bounce Out"]; 7778 7779 #tlActive = true; 7780 uiAttribs = {}; 7781 loop = 0; 7782 onLooped = null; 7783 _timesLooped = 0; 7784 _needsSort = false; 7785 _cachedIndex = 0; 7786 7787 /** @type {AnimKey[]} */ 7788 keys = []; 7789 onChange = null; 7790 stayInTimeline = false; 7791 7792 /** 7793 * @param {AnimCfg} [cfg] 7794 */ 7795 constructor(cfg = {}) 7796 { 7797 super(); 7798 cfg = cfg || {}; 7799 this.id = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.uuid)(); 7800 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_2__["default"]("Anim"); 7801 this.name = cfg.name || null; 7802 7803 /** @type {Number} */ 7804 this.defaultEasing = cfg.defaultEasing || Anim.EASING_LINEAR; 7805 } 7806 7807 forceChangeCallback() 7808 { 7809 if (this.onChange !== null) this.onChange(); 7810 this.emitEvent(Anim.EVENT_CHANGE, this); 7811 } 7812 7813 forceChangeCallbackSoon() 7814 { 7815 if (!this.forcecbto) 7816 this.forcecbto = setTimeout(() => 7817 { 7818 this.forceChangeCallback(); 7819 this.forcecbto = null; 7820 }, 7821 50); 7822 } 7823 7824 getLoop() 7825 { 7826 return this.loop; 7827 } 7828 7829 /** 7830 * @param {number} loopType 7831 */ 7832 setLoop(loopType) 7833 { 7834 if (loopType === false)loopType = 0; 7835 if (loopType === true)loopType = 1; 7836 7837 this.loop = loopType; 7838 this.emitEvent(Anim.EVENT_CHANGE, this); 7839 } 7840 7841 /** 7842 * returns true if animation has ended at @time 7843 * checks if last key time is < time 7844 * @param {Number} time 7845 * @returns {Boolean} 7846 * @memberof Anim 7847 * @instance 7848 * @function 7849 */ 7850 hasEnded(time) 7851 { 7852 if (this._needsSort) this.sortKeys(); 7853 if (this.keys.length === 0) return true; 7854 if (this.keys[this.keys.length - 1].time <= time) return true; 7855 return false;
7856 } 7857 7858 /** 7859 * @param {number} time 7860 */ 7861 hasStarted(time) 7862 { 7863 7864 if (this._needsSort) this.sortKeys(); 7865 if (this.keys.length === 0) return false; 7866 if (time >= this.keys[0].time) return true; 7867 return false; 7868 } 7869 7870 /** 7871 * @param {number} time 7872 */ 7873 isRising(time) 7874 { 7875 if (this._needsSort) this.sortKeys(); 7876 if (this.hasEnded(time)) return false; 7877 const ki = this.getKeyIndex(time); 7878 if (this.keys[ki].value < this.keys[ki + 1].value) return true; 7879 return false; 7880 } 7881 7882 /** 7883 * remove all keys from animation before time 7884 * @param {Number} time 7885 * @memberof Anim 7886 * @instance 7887 * @function 7888 */ 7889 clearBefore(time) 7890 { 7891 if (this._needsSort) this.sortKeys(); 7892 const v = this.getValue(time); 7893 const ki = this.getKeyIndex(time); 7894 7895 this.setValue(time, v); 7896 7897 if (ki > 1) 7898 { 7899 this.keys.splice(0, ki); 7900 this._needsSort = true; 7901 } 7902 } 7903 7904 /** 7905 * remove all keys from animation 7906 * @param {Number} [time=0] set a new key at time with the old value at time 7907 * @memberof Anim 7908 * @instance 7909 * @function 7910 */ 7911 clear(time) 7912 { 7913 if (this._needsSort) this.sortKeys(); 7914 let v = 0; 7915 if (time) v = this.getValue(time); 7916 7917 for (let i = 0; i < this.keys.length; i++) 7918 this.emitEvent(Anim.EVENT_KEY_DELETE, this.keys[i]); 7919 7920 this.keys.length = 0; 7921 if (time) this.setValue(time, v); 7922 this._needsSort = true; 7923 if (this.onChange !== null) this.onChange(); 7924 this.emitEvent(Anim.EVENT_CHANGE, this); 7925 } 7926 7927 checkIsSorted() 7928 { 7929 let isSorted = true; 7930 for (let i = 0; i < this.keys.length - 1; i++) 7931 if (this.keys[i].time > this.keys[i + 1].time) 7932 { 7933 isSorted = false; 7934 break; 7935 } 7936 7937 return isSorted; 7938 } 7939 7940 sortKeys() 7941 { 7942 if (!this.checkIsSorted()) 7943 { 7944 this.keys.sort((a, b) => { return a.time - b.time; }); 7945 this._needsSort = false; 7946 if (this.keys.length > 999 && this.keys.length % 1000 == 0)console.log(this.name, this.keys.length); 7947 7948 this.emitEvent(Anim.EVENT_CHANGE); 7949 } 7950 } 7951 7952 hasDuplicates() 7953 { 7954 const test = {}; 7955 let count = 0; 7956 for (let i = 0; i < this.keys.length; i++) 7957 { 7958 test[this.keys[i].time] = 1; 7959 count++; 7960 } 7961 7962 const keys = Object.keys(test); 7963 if (keys.length != count) 7964 { 7965 return true; 7966 } 7967 return false; 7968 } 7969 7970 removeDuplicates() 7971 { 7972 if (this.hasDuplicates()) 7973 { 7974 if (this._needsSort) this.sortKeys(); 7975 let count = 0; 7976 7977 while (this.hasDuplicates()) 7978 { 7979 for (let i = 0; i < this.keys.length - 1; i++) 7980 { 7981 if (this.keys[i].time == this.keys[i + 1].time) this.keys.splice(i, 1); 7982 count++; 7983 } 7984 } 7985 this._needsSort = true; 7986 } 7987 } 7988 7989 getLengthLoop() 7990 { 7991 if (this._needsSort) this.sortKeys(); 7992 if (this.keys.length < 2) return 0; 7993 return this.lastKey.time - this.firstKey.time; 7994 } 7995 7996 getLength() 7997 { 7998 if (this._needsSort) this.sortKeys(); 7999 if (this.keys.length === 0) return 0; 8000 return this.lastKey.time; 8001 } 8002 8003 /** 8004 * @param {number} time 8005 */ 8006 getKeyIndex(time) 8007 { 8008 if (this._needsSort) this.sortKeys(); 8009 let index = 0; 8010 let start = 0; 8011 if (this._cachedIndex && this.keys.length > this._cachedIndex && time >= this.keys[this._cachedIndex].time) start = this._cachedIndex; 8012 for (let i = start; i < this.keys.length; i++) 8013 { 8014 if (time >= this.keys[i].time) index = i; 8015 if (this.keys[i].time > time) 8016 { 8017 if (time != 0) this._cachedIndex = index; 8018 return index; 8019 } 8020 } 8021 8022 return index; 8023 } 8024 8025 /** 8026 * set value at time 8027 * @param {Number} time 8028 * @param {Number} value 8029 * @param {Function} cb callback 8030 */ 8031 setValue(time, value, cb = null) 8032 { 8033 if (isNaN(value))CABLES.logStack(); 8034 8035 if (this._needsSort) this.sortKeys(); 8036 let found = null; 8037 8038 if (this.keys.length == 0 || time <= this.lastKey.time) 8039 for (let i = 0; i < this.keys.length; i++) 8040 if (this.keys[i].time == time) 8041 { 8042 found = this.keys[i]; 8043 this.keys[i].setValue(value); 8044 this.keys[i].cb = cb; 8045 break; 8046 } 8047 8048 if (!found) 8049 { 8050 found = new _anim_key_js__WEBPACK_IMPORTED_MODULE_3__.AnimKey( 8051 { 8052 "time": time, 8053 "value": value, 8054 "e": this.defaultEasing, 8055 "cb": cb, 8056 "anim": this 8057 }); 8058 this.keys.push(found); 8059 8060 // if (this.keys.length % 1000 == 0)console.log(this.name, this.keys.length); 8061 } 8062 8063 if (this.onChange) this.onChange(); 8064 this.emitEvent(Anim.EVENT_CHANGE, this); 8065 this._needsSort = true; 8066 return found; 8067 } 8068 8069 /** 8070 * @param {number} index 8071 * @param {number} easing 8072 */ 8073 setKeyEasing(index, easing) 8074 { 8075 if (this.keys[index]) 8076 { 8077 this.keys[index].setEasing(easing); 8078 this.emitEvent(Anim.EVENT_CHANGE, this); 8079 } 8080 } 8081 8082 /** 8083 * @param {object} obj 8084 * @param {boolean} [clear] 8085 */ 8086 deserialize(obj, clear) 8087 { 8088 if (obj.loop) this.loop = obj.loop; 8089 if (obj.tlActive) this.#tlActive = obj.tlActive; 8090 if (obj.height) this.uiAttribs.height = obj.height; 8091 if (clear) this.keys.length = 0; 8092 8093 for (const ani in obj.keys) 8094 this.keys.push(new _anim_key_js__WEBPACK_IMPORTED_MODULE_3__.AnimKey(obj.keys[ani], this)); 8095 8096 this.sortKeys(); 8097 } 8098 8099 /** 8100 * @returns {SerializedAnim} 8101 */ 8102 getSerialized() 8103 { 8104 8105 /** @type {SerializedAnim} */ 8106 const obj = {}; 8107 obj.keys = []; 8108 obj.loop = this.loop; 8109 if (this.#tlActive)obj.tlActive = this.tlActive; 8110 if (this.uiAttribs.height)obj.height = this.uiAttribs.height; 8111 8112 for (let i = 0; i < this.keys.length; i++) 8113 obj.keys.push(this.keys[i].getSerialized()); 8114 8115 return obj; 8116 } 8117 8118 /** 8119 * @param {number} time 8120 */ 8121 getKey(time) 8122 { 8123 if (this._needsSort) this.sortKeys(); 8124 const index = this.getKeyIndex(time); 8125 return this.keys[index]; 8126 } 8127 8128 /** 8129 * @param {number} time 8130 */ 8131 getNextKey(time) 8132 { 8133 if (this._needsSort) this.sortKeys(); 8134 let index = this.getKeyIndex(time) + 1; 8135 if (index >= this.keys.length) return null; 8136 8137 return this.keys[index]; 8138 } 8139 8140 /** 8141 * @param {number} time 8142 */ 8143 getPrevKey(time) 8144 { 8145 if (this._needsSort) this.sortKeys(); 8146 let index = this.getKeyIndex(time) - 1; 8147 if (index < 0) return null; 8148 8149 return this.keys[index]; 8150 } 8151 8152 /** 8153 * @param {number} time 8154 */ 8155 isFinished(time) 8156 { 8157 if (this._needsSort) this.sortKeys(); 8158 if (this.keys.length <= 0) return true; 8159 return time > this.lastKey.time; 8160 } 8161 8162 /** 8163 * @param {number} time 8164 */ 8165 isStarted(time) 8166 { 8167 if (this._needsSort) this.sortKeys(); 8168 if (this.keys.length <= 0) return false;
8169 return time >= this.firstKey.time; 8170 } 8171 8172 /** 8173 * @param {AnimKey} k 8174 * @param {undefined} [events] 8175 */ 8176 remove(k, events) 8177 { 8178 for (let i = 0; i < this.keys.length; i++) 8179 { 8180 if (this.keys[i] == k) 8181 { 8182 this.emitEvent(Anim.EVENT_KEY_DELETE, this.keys[i]); 8183 this.keys.splice(i, 1); 8184 this._needsSort = true; 8185 if (events === undefined) 8186 { 8187 this.emitEvent(Anim.EVENT_CHANGE, this); 8188 } 8189 return; 8190 } 8191 } 8192 } 8193 8194 get lastKey() 8195 { 8196 if (this._needsSort) this.sortKeys(); 8197 return this.keys[this.keys.length - 1]; 8198 } 8199 8200 get firstKey() 8201 { 8202 if (this._needsSort) this.sortKeys(); 8203 return this.keys[0]; 8204 } 8205 8206 /** 8207 * @param {number} time 8208 */ 8209 getLoopIndex(time) 8210 { 8211 if (this._needsSort) this.sortKeys(); 8212 if (this.keys.length < 2) return 0; 8213 return (time - this.firstKey.time) / this.getLengthLoop(); 8214 } 8215 8216 /** 8217 * get value at time 8218 * @function getValue 8219 * @memberof Anim 8220 * @instance 8221 * @param {Number} [time] time 8222 * @returns {Number} interpolated value at time 8223 */ 8224 getValue(time) 8225 { 8226 let valAdd = 0; 8227 if (this.keys.length === 0) return 0; 8228 if (this._needsSort) this.sortKeys(); 8229 8230 if (!this.loop && time > this.keys[this.keys.length - 1].time) 8231 { 8232 if (this.lastKey.cb && !this.lastKey.cbTriggered) this.lastKey.trigger(); 8233 8234 return this.lastKey.value; 8235 } 8236 8237 if (time < this.firstKey.time) return this.keys[0].value; 8238 8239 if (this.loop && this.keys.length > 1 && time > this.lastKey.time) 8240 { 8241 const currentLoop = this.getLoopIndex(time); 8242 if (currentLoop > this._timesLooped) 8243 { 8244 this._timesLooped++; 8245 if (this.onLooped) this.onLooped(); 8246 } 8247 8248 time = (time - this.firstKey.time) % (this.getLengthLoop()); 8249 8250 if (this.loop == Anim.LOOP_REPEAT) { } 8251 else if (this.loop == Anim.LOOP_MIRROR) 8252 { 8253 if (Math.floor(currentLoop) % 2 == 1)time = this.getLengthLoop() - time; 8254 } 8255 else if (this.loop == Anim.LOOP_OFFSET) 8256 { 8257 valAdd = (this.lastKey.value - this.keys[0].value) * Math.floor(currentLoop); 8258 } 8259 8260 time += this.firstKey.time; 8261 } 8262 8263 const index = this.getKeyIndex(time); 8264 if (index >= this.keys.length - 1) 8265 { 8266 if (this.lastKey.cb && !this.lastKey.cbTriggered) this.lastKey.trigger(); 8267 return this.lastKey.value; 8268 } 8269 8270 const index2 = index + 1; 8271 const key1 = this.keys[index]; 8272 const key2 = this.keys[index2]; 8273 8274 if (key1.cb && !key1.cbTriggered) key1.trigger(); 8275 8276 if (!key2) return -1; 8277 8278 const perc = (time - key1.time) / (key2.time - key1.time); 8279 8280 return key1.ease(perc, key2) + valAdd; 8281 } 8282 8283 /** 8284 * @param {AnimKey} k 8285 */ 8286 addKey(k) 8287 { 8288 if (k.time === undefined) 8289 { 8290 this._log.warn("key time undefined, ignoring!"); 8291 } 8292 else 8293 { 8294 this.keys.push(k); 8295 if (this.onChange !== null) this.onChange(); 8296 this.emitEvent(Anim.EVENT_CHANGE, this); 8297 this._needsSort = true; 8298 } 8299 } 8300 8301 sortSoon() 8302 { 8303 this._needsSort = true; 8304 } 8305 8306 /** 8307 * @param {string} str 8308 */ 8309 easingFromString(str) 8310 { 8311 // todo smarter way to map ? 8312 if (str == "linear") return Anim.EASING_LINEAR; 8313 if (str == "absolute") return Anim.EASING_ABSOLUTE; 8314 if (str == "smoothstep") return Anim.EASING_SMOOTHSTEP; 8315 if (str == "smootherstep") return Anim.EASING_SMOOTHERSTEP; 8316 8317 if (str == "Cubic In") return Anim.EASING_CUBIC_IN; 8318 if (str == "Cubic Out") return Anim.EASING_CUBIC_OUT; 8319 if (str == "Cubic In Out") return Anim.EASING_CUBIC_INOUT; 8320 8321 if (str == "Expo In") return Anim.EASING_EXPO_IN; 8322 if (str == "Expo Out") return Anim.EASING_EXPO_OUT; 8323 if (str == "Expo In Out") return Anim.EASING_EXPO_INOUT; 8324 8325 if (str == "Sin In") return Anim.EASING_SIN_IN; 8326 if (str == "Sin Out") return Anim.EASING_SIN_OUT; 8327 if (str == "Sin In Out") return Anim.EASING_SIN_INOUT; 8328 8329 if (str == "Back In") return Anim.EASING_BACK_IN; 8330 if (str == "Back Out") return Anim.EASING_BACK_OUT; 8331 if (str == "Back In Out") return Anim.EASING_BACK_INOUT; 8332 8333 if (str == "Elastic In") return Anim.EASING_ELASTIC_IN; 8334 if (str == "Elastic Out") return Anim.EASING_ELASTIC_OUT; 8335 8336 if (str == "Bounce In") return Anim.EASING_BOUNCE_IN; 8337 if (str == "Bounce Out") return Anim.EASING_BOUNCE_OUT; 8338 8339 if (str == "Quart Out") return Anim.EASING_QUART_OUT; 8340 if (str == "Quart In") return Anim.EASING_QUART_IN; 8341 if (str == "Quart In Out") return Anim.EASING_QUART_INOUT; 8342 8343 if (str == "Quint Out") return Anim.EASING_QUINT_OUT; 8344 if (str == "Quint In") return Anim.EASING_QUINT_IN; 8345 if (str == "Quint In Out") return Anim.EASING_QUINT_INOUT; 8346 8347 console.log("unknown anim easing?", str); 8348 } 8349 8350 /** 8351 * @param {Op} op 8352 * @param {string} title 8353 * @param {function} cb 8354 * @returns {Port} 8355 */ 8356 createPort(op, title, cb) 8357 { 8358 const port = op.inDropDown(title, Anim.EASINGNAMES, "linear"); 8359 port.set("linear"); 8360 port.defaultValue = 0; 8361 8362 port.onChange = () => 8363 { 8364 this.defaultEasing = this.easingFromString(port.get()); 8365 this.emitEvent("onChangeDefaultEasing", this); 8366 8367 if (cb) cb(); 8368 }; 8369 8370 return port; 8371 } 8372 8373 get tlActive() 8374 { 8375 return this.#tlActive; 8376 } 8377 8378 set tlActive(b) 8379 { 8380 if (CABLES.UI) 8381 { 8382 this.#tlActive = b; 8383 window.gui.emitEvent("tlActiveChanged", this); 8384 this.forceChangeCallbackSoon(); 8385 } 8386 } 8387 8388 /** 8389 * @param {Object} o 8390 */ 8391 setUiAttribs(o) 8392 { 8393 for (const i in o) 8394 { 8395 this.uiAttribs[i] = o[i]; 8396 if (o[i] === null) delete this.uiAttribs[i]; 8397 } 8398 8399 this.emitEvent(Anim.EVENT_UIATTRIB_CHANGE); 8400 } 8401 8402 /** 8403 * @param {number} t 8404 * @param {number} t2 8405 */ 8406 hasKeyframesBetween(t, t2) 8407 { 8408 return this.getKeyIndex(t) != this.getKeyIndex(t2); 8409 } 8410} 8411 8412// ------------------------------ 8413 8414 8415/***/ }), 8416
8417/***/ "./src/core/anim_key.js": 8418/*!******************************!*\ 8419 !*** ./src/core/anim_key.js ***! 8420 \******************************/ 8421/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 8422 8423"use strict"; 8424/* harmony export */ __webpack_require__.d(__webpack_exports__, { 8425/* harmony export */ AnimKey: () => (/* binding */ AnimKey) 8426/* harmony export */ }); 8427/* unused harmony exports easeExpoIn, easeExpoOut, easeExpoInOut, easeCubicIn, easeCubicOut, easeCubicInOut */ 8428/* harmony import */ var _anim_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./anim.js */ "./src/core/anim.js"); 8429 8430 8431class AnimKey 8432{ 8433 8434 /** @type {Anim} */ 8435 anim = null; 8436 id = CABLES.shortId(); 8437 time = 0.0; 8438 value = 0.0; 8439 selected = false; 8440 onChange = null; 8441 _easing = 0; 8442 bezCp1 = null; 8443 bezCp2 = null; 8444 bezAn = null; 8445 cb = null; 8446 cbTriggered = false; 8447 temp = {}; 8448 uiAttribs = {}; 8449 8450 /** 8451 * @param {SerializedKey} obj 8452 * @param {Anim} [an] 8453 */ 8454 constructor(obj, an) 8455 { 8456 this.anim = obj.anim || an || null; 8457 8458 this.setEasing(_anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_LINEAR); 8459 this.set(obj); 8460 } 8461 8462 emitChange() 8463 { 8464 if (!this.anim) return; 8465 this.bezAn = null; 8466 if (this.onChange !== null) this.onChange(); 8467 this.anim.forceChangeCallbackSoon(); 8468 for (let i = 0; i < this.anim.keys.length; i++) 8469 this.anim.keys[i].bezAn = null; 8470 8471 } 8472 8473 delete() 8474 { 8475 if (this.anim) this.anim.remove(this); 8476 else console.log("animkey without anim..."); 8477 } 8478 8479 /** 8480 * @param {Object} o 8481 */ 8482 setUiAttribs(o) 8483 { 8484 for (const i in o) 8485 { 8486 this.uiAttribs[i] = o[i]; 8487 if (o[i] === null) delete this.uiAttribs[i]; 8488 } 8489 if (this.anim) this.anim.emitEvent(_anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EVENT_CHANGE); 8490 } 8491 8492 /** 8493 * @param {Number} e 8494 */ 8495 setEasing(e) 8496 { 8497 let changed = false; 8498 if (this._easing != e)changed = true; 8499 this._easing = e; 8500 8501 if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_LINEAR) this.ease = this.easeLinear; 8502 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_ABSOLUTE) this.ease = this.easeAbsolute; 8503 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_SMOOTHSTEP) this.ease = AnimKey.easeSmoothStep; 8504 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_SMOOTHERSTEP) this.ease = AnimKey.easeSmootherStep; 8505 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_CUBIC_IN) this.ease = AnimKey.easeCubicIn; 8506 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_CUBIC_OUT) this.ease = AnimKey.easeCubicOut; 8507 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_CUBIC_INOUT) this.ease = AnimKey.easeCubicInOut; 8508 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_EXPO_IN) this.ease = AnimKey.easeExpoIn; 8509 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_EXPO_OUT) this.ease = AnimKey.easeExpoOut; 8510 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_EXPO_INOUT) this.ease = AnimKey.easeExpoInOut; 8511 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_SIN_IN) this.ease = AnimKey.easeSinIn; 8512 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_SIN_OUT) this.ease = AnimKey.easeSinOut; 8513 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_SIN_INOUT) this.ease = AnimKey.easeSinInOut; 8514 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_BACK_OUT) this.ease = AnimKey.easeOutBack; 8515 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_BACK_IN) this.ease = AnimKey.easeInBack; 8516 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_BACK_INOUT) this.ease = AnimKey.easeInOutBack; 8517 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_ELASTIC_IN) this.ease = AnimKey.easeInElastic; 8518 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_ELASTIC_OUT) this.ease = AnimKey.easeOutElastic; 8519 // else if (this._easing == Anim.EASING_ELASTIC_INOUT) this.ease = AnimKey.easeElasticInOut; 8520 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_BOUNCE_IN) this.ease = AnimKey.easeInBounce; 8521 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_BOUNCE_OUT) this.ease = AnimKey.easeOutBounce; 8522 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_QUART_OUT) this.ease = AnimKey.easeOutQuart; 8523 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_QUART_IN) this.ease = AnimKey.easeInQuart; 8524 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_QUART_INOUT) this.ease = AnimKey.easeInOutQuart; 8525 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_QUINT_OUT) this.ease = AnimKey.easeOutQuint; 8526 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_QUINT_IN) this.ease = AnimKey.easeInQuint; 8527 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_QUINT_INOUT) this.ease = AnimKey.easeInOutQuint; 8528 else if (this._easing == _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_CUBICSPLINE) 8529 { 8530 if (this.ease != this.easeCubicSpline) 8531 { 8532 this.ease = this.easeCubicSpline; 8533 this.bezReset(); 8534 } 8535 8536 this.bezAn = null; 8537 } 8538 else 8539 { 8540 this._easing = _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_LINEAR; 8541 this.ease = this.easeLinear; 8542 } 8543 if (changed) this.emitChange(); 8544 } 8545 8546 bezReset() 8547 { 8548 8549 let xx = 0.5; 8550 const pk = this.anim.getPrevKey(this.time); 8551 if (pk)xx = (this.time - pk.time) / 2; 8552 8553 let x2 = 0.5; 8554 const nk = this.anim.getNextKey(this.time); 8555 if (nk)x2 = (nk.time - this.time) / 2; 8556 8557 this.bezCp1 = [-Math.min(xx, x2), 0]; 8558 this.bezCp2 = [Math.min(xx, x2), 0]; 8559 this.emitChange(); 8560 } 8561 8562 trigger() 8563 { 8564 this.cb(); 8565 this.cbTriggered = true; 8566 } 8567 8568 /** 8569 * @param {number} v 8570 */ 8571 setValue(v) 8572 { 8573 this.value = v; 8574 this.emitChange(); 8575 } 8576 8577 /** 8578 * @param {number} t 8579 * @param {number} v 8580 */ 8581 setBezCp1(t, v) 8582 { 8583 this.bezCp1 = [t, v]; 8584 this.emitChange(); 8585 } 8586 8587 /** 8588 * @param {number} t 8589 * @param {number} v 8590 */ 8591 setBezCp2(t, v) 8592 { 8593 this.bezCp2 = [t, v]; 8594 this.emitChange(); 8595 } 8596 8597 /** 8598 * @param {SerializedKey} obj 8599 */ 8600 set(obj) 8601 { 8602 if (obj) 8603 { 8604 if (obj.hasOwnProperty("e")) this.setEasing(obj.e); 8605 if (obj.cb) 8606 { 8607 this.cb = obj.cb; 8608 this.cbTriggered = false;
8609 } 8610 8611 if (obj.hasOwnProperty("cp1")) 8612 { 8613 this.bezCp1 = obj.cp1; 8614 this.bezCp2 = obj.cp2; 8615 } 8616 8617 if (obj.hasOwnProperty("t")) this.time = obj.t; 8618 if (obj.hasOwnProperty("time")) this.time = obj.time; 8619 if (obj.hasOwnProperty("v")) this.value = obj.v; 8620 else if (obj.hasOwnProperty("value")) this.value = obj.value; 8621 8622 if (obj.hasOwnProperty("uiAttribs")) this.setUiAttribs(obj.uiAttribs); 8623 } 8624 this.emitChange(); 8625 } 8626 8627 /** 8628 * @returns {Object} 8629 */ 8630 getSerialized() 8631 { 8632 const obj = {}; 8633 obj.t = this.time; 8634 obj.v = this.value; 8635 obj.e = this._easing; 8636 obj.uiAttribs = this.uiAttribs; 8637 8638 if (this._easing === _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASING_CUBICSPLINE) 8639 { 8640 obj.cp1 = this.bezCp1; 8641 obj.cp2 = this.bezCp2; 8642 } 8643 8644 return obj; 8645 } 8646 8647 getEasing() 8648 { 8649 return this._easing; 8650 } 8651 8652 /** 8653 * @param {number} perc 8654 * @param {AnimKey} key2 8655 */ 8656 easeCubicSpline(perc, key2) 8657 { 8658 if (!this.bezAn) 8659 { 8660 const samples = 30; 8661 8662 // const prevKey = this.anim.getPrevKey(this.time); 8663 this.bezAn = new _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim(); 8664 for (let i = 0; i <= samples + 1; i++) 8665 { 8666 const c = AnimKey.cubicSpline(i / samples, this, key2); 8667 this.bezAn.setValue(c[0], c[1]); 8668 } 8669 } 8670 8671 return this.bezAn.getValue(this.time + perc * (key2.time - this.time)); 8672 // return AnimKey.cubicSpline(perc, this, key2); 8673 } 8674 8675 /** 8676 * @param {number} perc 8677 * @param {AnimKey} key2 8678 */ 8679 easeLinear(perc, key2) 8680 { 8681 return AnimKey.linear(perc, this, key2); 8682 } 8683 8684 easeAbsolute() 8685 { 8686 return this.value; 8687 } 8688} 8689 8690AnimKey.cubicSpline = function (t, key1, key2) 8691{ 8692 const tInv = 1 - t; 8693 const tInvSq = tInv * tInv; 8694 const tSq = t * t; 8695 8696 const c0 = tInvSq * tInv; 8697 const c1 = 3 * tInvSq * t; 8698 const c2 = 3 * tInv * tSq; 8699 const c3 = tSq * t; 8700 8701 key1.bezCp1 = key1.bezCp1 || [-0.5, 0]; 8702 key1.bezCp2 = key1.bezCp2 || [0.5, 0]; 8703 key2.bezCp1 = key2.bezCp1 || [-0.5, 0]; 8704 key2.bezCp2 = key2.bezCp2 || [0.5, 0]; 8705 8706 const x1 = Math.min(key2.time, key1.bezCp2[0] + key1.time); 8707 const xp = Math.max(key1.time, key2.bezCp1[0] + key2.time); 8708 // const xp = key2.bezCp1[0] + key2.time; 8709 // console.log("textjjjj", key2.time, key0.time); 8710 8711 // const x = c0 + c1 * (key1.bezCp2[0]) + c2 * (key2.bezCp1[0]) + c3; 8712 const x = c0 * key1.time + c1 * (x1) + c2 * (xp) + c3 * (key2.time); 8713 const y = c0 * key1.value + c1 * (key1.bezCp2[1] + key1.value) + c2 * (key2.bezCp1[1] + key2.value) + c3 * (key2.value); 8714 8715 return [x, y]; 8716}; 8717 8718AnimKey.linear = function (perc, key1, key2) 8719{ 8720 return (key1.value) + (key2.value - key1.value) * perc; 8721}; 8722 8723const easeExpoIn = function (t) 8724{ 8725 return (t = 2 ** (10 * (t - 1))); 8726}; 8727 8728AnimKey.easeExpoIn = function (t, key2) 8729{ 8730 t = easeExpoIn(t); 8731 return AnimKey.linear(t, this, key2); 8732}; 8733 8734const easeExpoOut = function (t) 8735{ 8736 t = -(2 ** (-10 * t)) + 1; 8737 return t; 8738}; 8739 8740AnimKey.easeExpoOut = function (t, key2) 8741{ 8742 t = easeExpoOut(t); 8743 return AnimKey.linear(t, this, key2); 8744}; 8745 8746const easeExpoInOut = function (t) 8747{ 8748 t *= 2; 8749 if (t < 1) 8750 { 8751 t = 0.5 * 2 ** (10 * (t - 1)); 8752 } 8753 else 8754 { 8755 t--; 8756 t = 0.5 * (-(2 ** (-10 * t)) + 2); 8757 } 8758 return t; 8759}; 8760 8761AnimKey.easeExpoInOut = function (t, key2) 8762{ 8763 t = easeExpoInOut(t); 8764 return AnimKey.linear(t, this, key2); 8765}; 8766 8767AnimKey.easeSinIn = function (t, key2) 8768{ 8769 t = -1 * Math.cos((t * Math.PI) / 2) + 1; 8770 return AnimKey.linear(t, this, key2); 8771}; 8772 8773AnimKey.easeSinOut = function (t, key2) 8774{ 8775 t = Math.sin((t * Math.PI) / 2); 8776 return AnimKey.linear(t, this, key2); 8777}; 8778 8779AnimKey.easeSinInOut = function (t, key2) 8780{ 8781 t = -0.5 * (Math.cos(Math.PI * t) - 1.0); 8782 return AnimKey.linear(t, this, key2); 8783}; 8784 8785const easeCubicIn = function (t) 8786{ 8787 t = t * t * t; 8788 return t; 8789}; 8790 8791AnimKey.easeCubicIn = function (t, key2) 8792{ 8793 t = easeCubicIn(t); 8794 return AnimKey.linear(t, this, key2); 8795}; 8796 8797// b 0 8798// c 1/2 or 1 8799// d always 1 8800// easeOutCubic: function (x, t, b, c, d) { 8801// return c*((t=t/d-1)*t*t + 1) + b; 8802 8803AnimKey.easeInQuint = function (t, key2) 8804{ 8805 t = t * t * t * t * t; 8806 return AnimKey.linear(t, this, key2); 8807}; 8808AnimKey.easeOutQuint = function (t, key2) 8809{ 8810 t = (t -= 1) * t * t * t * t + 1; 8811 return AnimKey.linear(t, this, key2); 8812}; 8813AnimKey.easeInOutQuint = function (t, key2) 8814{ 8815 if ((t /= 0.5) < 1) t = 0.5 * t * t * t * t * t; 8816 else t = 0.5 * ((t -= 2) * t * t * t * t + 2); 8817 return AnimKey.linear(t, this, key2); 8818}; 8819 8820AnimKey.easeInQuart = function (t, key2) 8821{ 8822 t = t * t * t * t; 8823 return AnimKey.linear(t, this, key2); 8824}; 8825 8826AnimKey.easeOutQuart = function (t, key2) 8827{ 8828 // return -c * ((t=t/d-1)*t*t*t - 1) + b; 8829 t = -1 * ((t -= 1) * t * t * t - 1); 8830 return AnimKey.linear(t, this, key2); 8831}; 8832 8833AnimKey.easeInOutQuart = function (t, key2) 8834{ 8835 if ((t /= 0.5) < 1) t = 0.5 * t * t * t * t; 8836 else t = -0.5 * ((t -= 2) * t * t * t - 2); 8837 return AnimKey.linear(t, this, key2); 8838}; 8839 8840AnimKey.bounce = function (t) 8841{ 8842 if ((t /= 1) < 1 / 2.75) t = 7.5625 * t * t; 8843 else if (t < 2 / 2.75) t = 7.5625 * (t -= 1.5 / 2.75) * t + 0.75; 8844 else if (t < 2.5 / 2.75) t = 7.5625 * (t -= 2.25 / 2.75) * t + 0.9375; 8845 else t = 7.5625 * (t -= 2.625 / 2.75) * t + 0.984375; 8846 return t; 8847}; 8848 8849AnimKey.easeInBounce = function (t, key2) 8850{ 8851 return AnimKey.linear(AnimKey.bounce(t), this, key2); 8852 // return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d); 8853}; 8854 8855AnimKey.easeOutBounce = function (t, key2) 8856{ 8857 return AnimKey.linear(AnimKey.bounce(t), this, key2); 8858}; 8859 8860AnimKey.easeInElastic = function (t, key2) 8861{ 8862 let s = 1.70158; 8863 let p = 0; 8864 let a = 1; 8865 8866 const b = 0; 8867 const d = 1; 8868 const c = 1; 8869 8870 if (t === 0) t = b; 8871 else if ((t /= d) == 1) t = b + c; 8872 else 8873 { 8874 if (!p) p = d * 0.3; 8875 if (a < Math.abs(c)) 8876 { 8877 a = c; 8878 s = p / 4; 8879 } 8880 else s = (p / (2 * Math.PI)) * Math.asin(c / a); 8881 t = -(a * 2 ** (10 * (t -= 1)) * Math.sin(((t * d - s) * (2 * Math.PI)) / p)) + b; 8882 } 8883 8884 return AnimKey.linear(t, this, key2); 8885}; 8886 8887AnimKey.easeOutElastic = function (t, key2) 8888{ 8889 let s = 1.70158; 8890 let p = 0; 8891 let a = 1; 8892 8893 const b = 0; 8894 const d = 1; 8895 const c = 1; 8896 8897 if (t === 0) t = b; 8898 else if ((t /= d) == 1) t = b + c; 8899 else 8900 { 8901 if (!p) p = d * 0.3; 8902 if (a < Math.abs(c)) 8903 { 8904 a = c; 8905 s = p / 4; 8906 } 8907 else s = (p / (2 * Math.PI)) * Math.asin(c / a); 8908 t = a * 2 ** (-10 * t) * Math.sin(((t * d - s) * (2 * Math.PI)) / p) + c + b; 8909 } 8910 8911 return AnimKey.linear(t, this, key2); 8912}; 8913 8914AnimKey.easeInBack = function (t, key2) 8915{ 8916 const s = 1.70158; 8917 t = t * t * ((s + 1) * t - s); 8918 8919 return AnimKey.linear(t, this, key2); 8920}; 8921 8922AnimKey.easeOutBack = function (t, key2) 8923{ 8924 const s = 1.70158;
8925 t = (t = t / 1 - 1) * t * ((s + 1) * t + s) + 1; 8926 8927 return AnimKey.linear(t, this, key2); 8928}; 8929 8930AnimKey.easeInOutBack = function (t, key2) 8931{ 8932 let s = 1.70158; 8933 const c = 1 / 2; 8934 if ((t /= 1 / 2) < 1) t = c * (t * t * (((s *= 1.525) + 1) * t - s)); 8935 else t = c * ((t -= 2) * t * (((s *= 1.525) + 1) * t + s) + 2); 8936 8937 return AnimKey.linear(t, this, key2); 8938}; 8939 8940const easeCubicOut = function (t) 8941{ 8942 t--; 8943 t = t * t * t + 1; 8944 return t; 8945}; 8946 8947AnimKey.easeCubicOut = function (t, key2) 8948{ 8949 t = easeCubicOut(t); 8950 return AnimKey.linear(t, this, key2); 8951}; 8952 8953const easeCubicInOut = function (t) 8954{ 8955 t *= 2; 8956 if (t < 1) t = 0.5 * t * t * t; 8957 else 8958 { 8959 t -= 2; 8960 t = 0.5 * (t * t * t + 2); 8961 } 8962 return t; 8963}; 8964 8965AnimKey.easeCubicInOut = function (t, key2) 8966{ 8967 t = easeCubicInOut(t); 8968 return AnimKey.linear(t, this, key2); 8969}; 8970 8971AnimKey.easeSmoothStep = function (perc, key2) 8972{ 8973 // var x = Math.max(0, Math.min(1, (perc-0)/(1-0))); 8974 const x = Math.max(0, Math.min(1, perc)); 8975 perc = x * x * (3 - 2 * x); // smoothstep 8976 return AnimKey.linear(perc, this, key2); 8977}; 8978 8979AnimKey.easeSmootherStep = function (perc, key2) 8980{ 8981 const x = Math.max(0, Math.min(1, (perc - 0) / (1 - 0))); 8982 perc = x * x * x * (x * (x * 6 - 15) + 10); // smootherstep 8983 return AnimKey.linear(perc, this, key2); 8984}; 8985 8986 8987/***/ }), 8988
8989/***/ "./src/core/constants.js": 8990/*!*******************************!*\ 8991 !*** ./src/core/constants.js ***! 8992 \*******************************/ 8993/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 8994 8995"use strict"; 8996/* harmony export */ __webpack_require__.d(__webpack_exports__, { 8997/* harmony export */ CONSTANTS: () => (/* binding */ CONSTANTS) 8998/* harmony export */ }); 8999/* harmony import */ var _anim_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./anim.js */ "./src/core/anim.js"); 9000 9001 9002const CONSTANTS = { 9003 "ANIM": { 9004 "EASINGS": _anim_js__WEBPACK_IMPORTED_MODULE_0__.Anim.EASINGNAMES, 9005 "EASING_LINEAR": 0, 9006 "EASING_ABSOLUTE": 1, 9007 "EASING_SMOOTHSTEP": 2, 9008 "EASING_SMOOTHERSTEP": 3, 9009 "EASING_CUBICSPLINE": 4, 9010 9011 "EASING_CUBIC_IN": 5, 9012 "EASING_CUBIC_OUT": 6, 9013 "EASING_CUBIC_INOUT": 7, 9014 9015 "EASING_EXPO_IN": 8, 9016 "EASING_EXPO_OUT": 9, 9017 "EASING_EXPO_INOUT": 10, 9018 9019 "EASING_SIN_IN": 11, 9020 "EASING_SIN_OUT": 12, 9021 "EASING_SIN_INOUT": 13, 9022 9023 "EASING_BACK_IN": 14, 9024 "EASING_BACK_OUT": 15, 9025 "EASING_BACK_INOUT": 16, 9026 9027 "EASING_ELASTIC_IN": 17, 9028 "EASING_ELASTIC_OUT": 18, 9029 9030 "EASING_BOUNCE_IN": 19, 9031 "EASING_BOUNCE_OUT": 21, 9032 9033 "EASING_QUART_IN": 22, 9034 "EASING_QUART_OUT": 23, 9035 "EASING_QUART_INOUT": 24, 9036 9037 "EASING_QUINT_IN": 25, 9038 "EASING_QUINT_OUT": 26, 9039 "EASING_QUINT_INOUT": 27, 9040 }, 9041 9042 "OP": { 9043 "OP_PORT_TYPE_VALUE": 0, 9044 "OP_PORT_TYPE_NUMBER": 0, 9045 "OP_PORT_TYPE_FUNCTION": 1, 9046 "OP_PORT_TYPE_TRIGGER": 1, 9047 "OP_PORT_TYPE_OBJECT": 2, 9048 "OP_PORT_TYPE_TEXTURE": 2, 9049 "OP_PORT_TYPE_ARRAY": 3, 9050 "OP_PORT_TYPE_DYNAMIC": 4, 9051 "OP_PORT_TYPE_STRING": 5, 9052 9053 "OP_VERSION_PREFIX": "_v", 9054 }, 9055 9056 "PORT": { 9057 "PORT_DIR_IN": 0, 9058 "PORT_DIR_OUT": 1, 9059 }, 9060 9061 "PACO": { 9062 "PACO_CLEAR": 0, 9063 "PACO_VALUECHANGE": 1, 9064 "PACO_OP_DELETE": 2, 9065 "PACO_UNLINK": 3, 9066 "PACO_LINK": 4, 9067 "PACO_LOAD": 5, 9068 "PACO_OP_CREATE": 6, 9069 "PACO_OP_ENABLE": 7, 9070 "PACO_OP_DISABLE": 8, 9071 "PACO_UIATTRIBS": 9, 9072 "PACO_VARIABLES": 10, 9073 "PACO_TRIGGERS": 11, 9074 "PACO_PORT_SETVARIABLE": 12, 9075 "PACO_PORT_SETANIMATED": 13, 9076 "PACO_PORT_ANIM_UPDATED": 14, 9077 "PACO_DESERIALIZE": 15, 9078 "PACO_OP_RELOAD": 16 9079 }, 9080}; 9081 9082 9083/***/ }), 9084
9085/***/ "./src/core/core_port.js": 9086/*!*******************************!*\ 9087 !*** ./src/core/core_port.js ***! 9088 \*******************************/ 9089/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 9090 9091"use strict"; 9092/* harmony export */ __webpack_require__.d(__webpack_exports__, { 9093/* harmony export */ Port: () => (/* binding */ Port) 9094/* harmony export */ }); 9095/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/eventtarget.js"); 9096/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 9097/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants.js */ "./src/core/constants.js"); 9098/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils.js */ "./src/core/utils.js"); 9099/* harmony import */ var _anim_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./anim.js */ "./src/core/anim.js"); 9100 9101 9102 9103 9104 9105 9106 9107 9108/** 9109 * @typedef PortUiAttribs 9110 * @property {String} [title] overwrite title of port (by default this is portname) 9111 * @property {String} [display] how the port is displayed and interacted in the paramerer panel 9112 * @property {Boolean} [greyout] port paramater will appear greyed out, can not be 9113 * @property {Boolean} [hidePort] port will be hidden from op 9114 * @property {Boolean} [hideParam] port params will be hidden from parameter panel 9115 * @property {Boolean} [showIndex] only for dropdowns - show value index (e.g. `0 - normal` ) 9116 * @property {String} [editorSyntax] set syntax highlighting theme for editor port 9117 * @property {Boolean} [ignoreObjTypeErrors] do not auto check object types 9118 * @property {string} [group] do not set manually - group ports, usually set by op.setPortGroup... 9119 * @property {Boolean} [isAnimated] internal: do not set manually 9120 * @property {Boolean} [useVariable] internal: do not set manually 9121 * @property {string} [variableName] internal: do not set manually 9122 * @property {Number} [order] internal: do not set manually 9123 * @property {Number} [stride] internal: do not set manually 9124 * @property {Boolean} [expose] internal: do not set manually 9125 * @property {Boolean} [multiPortManual] internal: do not set manually 9126 * @property {String} [increment] internal: do not set manually 9127 * @property {Number} [multiPortNum] internal: do not set manually 9128 * @property {String} [display] internal: do not set manually 9129 * @property {String} [axis] internal: do not set manually 9130 * @property {String} [type] internal: do not set manually 9131 * @property {String} [objType] internal: do not set manually 9132 * @property {String} [filter] internal: do not set manually 9133 * @property {boolean} [hideFormatButton] internal: do not set manually 9134 * @property {boolean} [editShortcut] internal: do not set manually 9135 * @property {String} [filter] internal: do not set manually 9136 * @property {boolean} [preview] internal: do not set manually 9137 * @property {boolean} [colorPick] internal: do not set manually 9138 * @property {Array<String>} [values] internal: do not set manually 9139 * @property {boolean} [boundToVar] internal: do not set manually 9140 * @property {boolean} [addPort] internal: do not set manually 9141 * @property {boolean} [notWorking] internal: do not set manually 9142 * @property {number} [glPortIndex] internal: do not set manually 9143 * @property {boolean} [readOnly] internal: do not set manually 9144 * @property {boolean} [multiPort] internal: do not set manually 9145 */ 9146
9147/** 9148 * data is coming into and out of ops through input and output ports 9149 * @namespace external:CABLES#Port 9150 * @module Port 9151 * @class 9152 * @example 9153 * const myPort=op.inString("String Port"); 9154 */ 9155class Port extends cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"] 9156{ 9157 static DIR_IN = 0; 9158 static DIR_OUT = 1; 9159 9160 static TYPE_VALUE = 0; 9161 static TYPE_NUMBER = 0; 9162 static TYPE_FUNCTION = 1; 9163 static TYPE_TRIGGER = 1; 9164 static TYPE_OBJECT = 2; 9165 static TYPE_TEXTURE = 2; 9166 static TYPE_ARRAY = 3; 9167 static TYPE_DYNAMIC = 4; 9168 static TYPE_STRING = 5; 9169 9170 static EVENT_UIATTRCHANGE = "onUiAttrChange"; 9171 static EVENT_VALUE_CHANGE = "change"; 9172 9173 #oldAnimVal = -5711; 9174 9175 animMuted = false; 9176 9177 lastAnimTime = 0; 9178 #uiActiveState = true; 9179 #valueBeforeLink = null; 9180 // #lastAnimFrame = -1; 9181 #animated = false; 9182 // #tempLastUiValue = null; 9183 #useVariableName = null; 9184 9185 /** 9186 * @param {Op} ___op 9187 * @param {string} name 9188 * @param {number} type 9189 * @param {PortUiAttribs} uiAttribs 9190 */ 9191 constructor(___op, name, type, uiAttribs = {}) 9192 { 9193 super(); 9194 this.data = {}; // UNUSED, DEPRECATED, only left in for backwards compatibility with userops 9195 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_1__["default"]("core_port"); 9196 9197 /** 9198 * @type {Number} 9199 * @name direction 9200 * @instance 9201 * @memberof Port 9202 * @description direction of port (input(0) or output(1)) 9203 */ 9204 this.direction = Port.DIR_IN; 9205 this.id = String(CABLES.simpleId()); 9206 9207 /** @type {Op} */ 9208 this._op = ___op; 9209 9210 /** @type {Array<Link>} */ 9211 this.links = []; 9212 9213 /** @type {any} */ 9214 this.value = 0.0; 9215 9216 this.name = name; 9217 9218 /** @type {number} */ 9219 this.type = type || Port.TYPE_VALUE; 9220 9221 /** @type {PortUiAttribs} */ 9222 this.uiAttribs = uiAttribs || {}; 9223 9224 /** @type {Anim} */ 9225 this.anim = null; 9226 9227 this.defaultValue = null; 9228 9229 this.ignoreValueSerialize = false; 9230 this.onLinkChanged = null; 9231 this.crashed = false; 9232 9233 this.onValueChanged = null; 9234 this.onTriggered = null; 9235 this.changeAlways = false; 9236 this.forceRefChange = false; 9237 9238 this.activityCounter = 0; 9239 this.apf = 0; 9240 this.activityCounterStartFrame = 0; 9241 9242 this.canLink = null; // function can be overwritten 9243 this.preserveLinks = null; 9244 this.indexPort = null; 9245 } 9246 9247 get parent() 9248 { 9249 this._log.stack("use port.op, not .parent"); 9250 return this.op; 9251 } 9252 9253 get title() 9254 { 9255 return this.uiAttribs.title || this.name; 9256 } 9257 9258 get op() 9259 { 9260 return this._op; 9261 } 9262 9263 get val() 9264 { 9265 return this.get(); 9266 } 9267 9268 set val(v) 9269 { 9270 this.setValue(v); 9271 } 9272 9273 /** 9274 * copy over a uiattrib from an external connected port to another port 9275 * @function copyLinkedUiAttrib 9276 * @memberof Port 9277 * @param {string} which attrib name 9278 * @param {Port} port source port 9279 * @instance 9280 * @example 9281 * 9282 * inArray.onLinkChanged=()=> 9283 * { 9284 * if(inArray) inArray.copyLinkedUiAttrib("stride", outArray); 9285 * }; 9286 * 9287 */ 9288 copyLinkedUiAttrib(which, port) 9289 { 9290 if (!CABLES.UI) return; 9291 if (!this.isLinked()) return; 9292 9293 const attr = {}; 9294 attr[which] = this.links[0].getOtherPort(this).getUiAttrib(which); 9295 port.setUiAttribs(attr); 9296 } 9297 9298 /* 9299 * TODO make extend class for ports, like for ops only for ui 9300 */ 9301 getValueForDisplay() 9302 { 9303 let str = this.value; 9304 9305 if (typeof this.value === "string" || this.value instanceof String) 9306 { 9307 if (str.length > 1000) 9308 { 9309 str = str.substring(0, 999); 9310 str += "..."; 9311 } 9312 if (this.uiAttribs && (this.uiAttribs.display == "boolnum")) 9313 { 9314 str += " - "; 9315 9316 if (!this.value) str += "false"; 9317 else str += "true"; 9318 } 9319 9320 str = str.replace(/[\u00A0-\u9999<>\&]/g, function (/** @type {String} */ i) 9321 {
9322 return "&#" + i.charCodeAt(0) + ";"; 9323 }); 9324 9325 if (str.length > 100) str = str.substring(0, 100); 9326 } 9327 else 9328 { 9329 str = String(this.value); 9330 } 9331 // if (this.type == Port.TYPE_NUMBER) 9332 // { 9333 // if (isNaN(this.value)) return "NaN"; 9334 9335 // } 9336 return str; 9337 } 9338 9339 /** 9340 * change listener for input value ports, overwrite to react to changes 9341 * @function onChange 9342 * @memberof Port 9343 * @instance 9344 * @example 9345 * const myPort=op.inString("MyPort"); 9346 * myPort.onChange=function() 9347 * { 9348 * console.log("was changed to: ",myPort.get()); 9349 * } 9350 * 9351 */ 9352 onAnimToggle() {} 9353 9354 _onAnimToggle() 9355 { 9356 this.onAnimToggle(); 9357 } 9358 9359 /** 9360 * @function remove 9361 * @memberof Port 9362 * @instance 9363 * @description remove port 9364 */ 9365 remove() 9366 { 9367 this.removeLinks(); 9368 this._op.removePort(this); 9369 } 9370 9371 /** 9372 * set ui attributes 9373 * @function setUiAttribs 9374 * @memberof Port 9375 * @instance 9376 * @param {PortUiAttribs} newAttribs 9377 9378 * @example 9379 * myPort.setUiAttribs({greyout:true}); 9380 */ 9381 setUiAttribs(newAttribs) 9382 { 9383 let changed = false; 9384 if (!this.uiAttribs) this.uiAttribs = {}; 9385 9386 for (const p in newAttribs) 9387 { 9388 if (newAttribs[p] === undefined) 9389 { 9390 delete this.uiAttribs[p]; 9391 continue; 9392 } 9393 if (this.uiAttribs[p] != newAttribs[p]) changed = true; 9394 this.uiAttribs[p] = newAttribs[p]; 9395 9396 if (p == "group" && this.indexPort) this.indexPort.setUiAttribs({ "group": newAttribs[p] }); 9397 } 9398 9399 if (newAttribs.hasOwnProperty("expose")) this._op.patch.emitEvent("subpatchExpose", this._op.uiAttribs.subPatch); 9400 9401 if (changed) this.emitEvent(Port.EVENT_UIATTRCHANGE, newAttribs, this); 9402 } 9403 9404 /** 9405 * get ui attributes 9406 * @function getUiAttribs 9407 * @memberof Port 9408 * @example 9409 * myPort.getUiAttribs(); 9410 */ 9411 getUiAttribs() 9412 { 9413 return this.uiAttribs; 9414 } 9415 9416 /** 9417 * get ui attribute 9418 * @function getUiAttrib 9419 * @memberof Port 9420 * @instance 9421 * @param {String} attribName 9422 * <pre> 9423 * attribName - return value of the ui-attribute, or null on unknown attribute 9424 * </pre> 9425 * @example 9426 * myPort.setUiAttribs("values"); 9427 */ 9428 getUiAttrib(attribName) 9429 { 9430 if (!this.uiAttribs || !this.uiAttribs.hasOwnProperty(attribName)) return null; 9431 return this.uiAttribs[attribName]; 9432 } 9433 9434 /** 9435 * @function get 9436 * @memberof Port 9437 * @instance 9438 * @description get value of port 9439 */ 9440 get() 9441 { 9442 if (CABLES.UI && this.#animated && this.lastAnimTime == this._op.patch.timer.getTime() && !CABLES.UI.keyframeAutoCreate) 9443 { 9444 return this.value; 9445 } 9446 if (!this.animMuted && this.#animated && this.lastAnimFrame != this._op.patch.getFrameNum()) 9447 { 9448 this.lastAnimTime = this._op.patch.timer.getTime(); 9449 this.lastAnimFrame = this._op.patch.getFrameNum(); 9450 9451 let animval = this.anim.getValue(this._op.patch.timer.getTime()); 9452 9453 if (this.value != animval) 9454 { 9455 this.value = animval; 9456 this.#oldAnimVal = this.value; 9457 this.forceChange(); 9458 } 9459 } 9460 9461 return this.value; 9462 } 9463 9464 /** 9465 * @param {object|array} v 9466 */ 9467 setRef(v) 9468 { 9469 this.forceRefChange = true; 9470 this.set(v); 9471 } 9472 9473 /** 9474 * @function setValue 9475 * @memberof Port 9476 * @instance 9477 * @description set value of port / will send value to all linked ports (only for output ports) 9478 * @param {string | number | boolean | any[]} v 9479 */ 9480 set(v) 9481 { 9482 9483 this.setValue(v); 9484 } 9485 9486 /** 9487 * @param {string|boolean|number} v 9488 */ 9489 setValue(v) 9490 { 9491 if (v === undefined) v = null; 9492 9493 if (CABLES.UI && CABLES.UI.showDevInfos) 9494 if (this.direction == _constants_js__WEBPACK_IMPORTED_MODULE_2__.CONSTANTS.PORT.PORT_DIR_OUT && this.type == Port.TYPE_OBJECT && v && !this.forceRefChange) 9495 this._log.warn("object port [" + this.name + "] uses .set [" + this.op.objName + "]"); 9496 9497 if (this._op.enabled && !this.crashed) 9498 { 9499 if (v !== this.value || this.changeAlways || this.type == Port.TYPE_TEXTURE || this.type == Port.TYPE_ARRAY) 9500 { 9501 if (CABLES.UI && this.#animated) 9502 { 9503 CABLES.UI.PREVISKEYVAL = null; 9504 if (!CABLES.UI.keyframeAutoCreate) CABLES.UI.PREVISKEYVAL = v; 9505 } 9506 9507 if (CABLES.UI && this.#animated && CABLES.UI.keyframeAutoCreate) 9508 { 9509 let t = this._op.patch.timer.getTime(); 9510 if (CABLES.UI && window.gui.glTimeline) window.gui.glTimeline.createKey(this.anim, t, v); 9511 else this.anim.setValue(t, v); 9512 } 9513 else 9514 { 9515 try 9516 { 9517 this.value = v; 9518 this.forceChange(); 9519 } 9520 catch (ex) 9521 { 9522 this.crashed = true; 9523 9524 this.setValue = function (_v) {}; 9525 this.onTriggered = function (a) {}; 9526 9527 this._log.error("exception in ", this._op); 9528 this._log.error(ex); 9529 9530 this._op.patch.emitEvent("exception", ex, this._op); 9531 } 9532 9533 if (this._op && this._op.patch && this._op.patch.isEditorMode() && this.type == Port.TYPE_TEXTURE) gui.texturePreview().updateTexturePort(this); 9534 } 9535 9536 if (this.direction == _constants_js__WEBPACK_IMPORTED_MODULE_2__.CONSTANTS.PORT.PORT_DIR_OUT) for (let i = 0; i < this.links.length; ++i) this.links[i].setValue(); 9537 } 9538 } 9539 } 9540 9541 updateAnim() 9542 { 9543 if (!this.#animated || this.animMuted) return; 9544 this.value = this.get(); 9545 9546 if (this.#oldAnimVal != this.value || this.changeAlways) 9547 { 9548 this.#oldAnimVal = this.value; 9549 this.forceChange(); 9550 } 9551 this.#oldAnimVal = this.value; 9552 9553 } 9554 9555 forceChange() 9556 { 9557 if (this.onValueChanged || this.onChange) 9558 { 9559 9560 /* 9561 * very temporary: deprecated warning!!!!!!!!! 9562 * if(params.length>0) this._log.warn('TOM: port has onchange params!',this._op.objName,this.name); 9563 */ 9564 } 9565 this._activity(); 9566 this.emitEvent(Port.EVENT_VALUE_CHANGE, this.value, this); 9567 9568 if (this.onChange) this.onChange(this, this.value); 9569 else if (this.onValueChanged) this.onValueChanged(this, this.value); // deprecated 9570 } 9571 9572 /** 9573 * @function getTypeString 9574 * @memberof Port 9575 * @instance
9576 * @description get port type as string, e.g. "Function","Value"... 9577 * @return {String} type 9578 */ 9579 getTypeString() 9580 { 9581 if (this.type == Port.TYPE_VALUE) return "Number"; 9582 if (this.type == Port.TYPE_FUNCTION) return "Trigger"; 9583 if (this.type == Port.TYPE_OBJECT) return "Object"; 9584 if (this.type == Port.TYPE_DYNAMIC) return "Dynamic"; 9585 if (this.type == Port.TYPE_ARRAY) return "Array"; 9586 if (this.type == Port.TYPE_STRING) return "String"; 9587 return "Unknown"; 9588 } 9589 9590 /** 9591 * @param {Object} objPort 9592 */ 9593 deSerializeSettings(objPort) 9594 { 9595 if (!objPort) return; 9596 if (objPort.animated) this.setAnimated(objPort.animated); 9597 if (objPort.useVariable) this.setVariableName(objPort.useVariable); 9598 if (objPort.title) this.setUiAttribs({ "title": objPort.title }); 9599 if (objPort.expose) this.setUiAttribs({ "expose": true }); 9600 if (objPort.order) this.setUiAttribs({ "order": objPort.order }); 9601 9602 if (objPort.multiPortManual) this.setUiAttribs({ "multiPortManual": objPort.multiPortManual }); 9603 if (objPort.multiPortNum) this.setUiAttribs({ "multiPortNum": objPort.multiPortNum }); 9604 9605 if (objPort.anim) 9606 { 9607 if (!this.anim) this.anim = new _anim_js__WEBPACK_IMPORTED_MODULE_3__.Anim({ "name": "port " + this.name }); 9608 this._op.hasAnimPort = true; 9609 // this.anim.on(Anim.EVENT_CHANGE, () => 9610 // { 9611 // this._op.patch.emitEvent("portAnimUpdated", this._op, this, this.anim); 9612 // }); 9613 this.anim.deserialize(objPort.anim, true); 9614 this._op.patch.emitEvent("portAnimUpdated", this._op, this, this.anim); 9615 9616 this.bindAnimListeners(); 9617 this.anim.sortKeys(); 9618 } 9619 } 9620 9621 /** 9622 * @param {any} v 9623 */ 9624 setInitialValue(v) 9625 { 9626 if (this.op.preservedPortLinks[this.name]) 9627 { 9628 for (let i = 0; i < this.op.preservedPortLinks[this.name].length; i++) 9629 { 9630 const lobj = this.op.preservedPortLinks[this.name][i]; 9631 this.op.patch._addLink( 9632 lobj.objIn, 9633 lobj.objOut, 9634 lobj.portIn, 9635 lobj.portOut); 9636 } 9637 } 9638 9639 if (this.op.preservedPortValues && this.op.preservedPortValues.hasOwnProperty(this.name) && this.op.preservedPortValues[this.name] !== undefined) 9640 { 9641 this.set(this.op.preservedPortValues[this.name]); 9642 } 9643 else 9644 if (v !== undefined) this.set(v); 9645 if (v !== undefined) this.defaultValue = v; 9646 } 9647 9648 getSerialized() 9649 { 9650 let obj = { "name": this.getName() }; 9651 9652 if (!this.ignoreValueSerialize && this.links.length === 0) 9653 { 9654 if (this.type == Port.TYPE_OBJECT && this.value && this.value.tex) {} 9655 else obj.value = this.value; 9656 } 9657 if (this.#useVariableName) obj.useVariable = this.#useVariableName; 9658 if (this.#animated) obj.animated = true; 9659 if (this.anim) obj.anim = this.anim.getSerialized(); 9660 if (this.uiAttribs.multiPortNum) obj.multiPortNum = this.uiAttribs.multiPortNum; 9661 if (this.uiAttribs.multiPortManual) obj.multiPortManual = this.uiAttribs.multiPortManual; 9662 9663 if (this.uiAttribs.display == "file") obj.display = this.uiAttribs.display; 9664 if (this.uiAttribs.expose) 9665 { 9666 obj.expose = true; 9667 if (this.uiAttribs.hasOwnProperty("order")) obj.order = this.uiAttribs.order; 9668 } 9669 if (this.uiAttribs.title) obj.title = this.uiAttribs.title; 9670 if ((this.preserveLinks || this.direction == _constants_js__WEBPACK_IMPORTED_MODULE_2__.CONSTANTS.PORT.PORT_DIR_OUT) && this.links.length > 0) 9671 { 9672 obj.links = []; 9673 for (const i in this.links) 9674 { 9675 if (!this.links[i].ignoreInSerialize && (this.links[i].portIn && this.links[i].portOut)) obj.links.push(this.links[i].getSerialized()); 9676 } 9677 } 9678 9679 if (this.direction == Port.DIR_IN && this.links.length > 0) 9680 { 9681 for (const i in this.links) 9682 { 9683 if (!this.links[i].portIn || !this.links[i].portOut) continue; 9684 9685 const otherp = this.links[i].getOtherPort(this); 9686 // check if functions exist, are defined in core_extend_ops code in ui 9687 if (otherp.op.isInBlueprint2 && this.op.isInBlueprint2) 9688 { 9689 if (otherp.op.isInBlueprint2() && !this.op.isInBlueprint2()) 9690 { 9691 obj.links = obj.links || []; 9692 obj.links.push(this.links[i].getSerialized()); 9693 } 9694 } 9695 } 9696 } 9697 9698 if (obj.links && obj.links.length == 0) delete obj.links;
9699 if (this.type === Port.TYPE_FUNCTION) delete obj.value; 9700 if (this.type === Port.TYPE_FUNCTION && this.links.length == 0) obj = null; 9701 if (obj && Object.keys(obj).length == 1 && obj.name)obj = null; // obj is null if there is no real information other than name 9702 9703 (0,_utils_js__WEBPACK_IMPORTED_MODULE_4__.cleanJson)(obj); 9704 9705 return obj; 9706 } 9707 9708 /** 9709 * will be overwritten in ui 9710 * @param {Port} port1 9711 * @param {Port} port2 9712 * @returns {boolean} 9713 */ 9714 shouldLink(port1, port2) 9715 { 9716 return !!(port1 && port2); 9717 } 9718 9719 /** 9720 * @function removeLinks 9721 * @memberof Port 9722 * @instance 9723 * @description remove all links from port 9724 */ 9725 removeLinks() 9726 { 9727 let count = 0; 9728 while (this.links.length > 0) 9729 { 9730 count++; 9731 if (count > 5000) 9732 { 9733 this._log.warn("could not delete links... / infinite loop"); 9734 this.links.length = 0; 9735 break; 9736 } 9737 this.links[0].remove(); 9738 } 9739 } 9740 9741 /** 9742 * @function removeLink 9743 * @memberof Port 9744 * @instance 9745 * @description remove all link from port 9746 * @param {Link} link 9747 */ 9748 removeLink(link) 9749 { 9750 for (let i = 0; i < this.links.length; i++) 9751 if (this.links[i] == link) 9752 this.links.splice(i, 1); 9753 9754 if (this.direction == Port.DIR_IN) 9755 { 9756 if (this.type == Port.TYPE_VALUE) this.setValue(this.#valueBeforeLink || 0); 9757 else this.setValue(this.#valueBeforeLink || null); 9758 } 9759 9760 if (CABLES.UI && this._op.checkLinkTimeWarnings) this._op.checkLinkTimeWarnings(); 9761 9762 try 9763 { 9764 if (this.onLinkChanged) this.onLinkChanged(); 9765 this.emitEvent("onLinkChanged"); 9766 this.emitEvent("onLinkRemoved"); 9767 this._op.emitEvent("onLinkChanged"); 9768 } 9769 catch (e) 9770 { 9771 this._log.error(e); 9772 } 9773 } 9774 9775 /** 9776 * @function getName 9777 * @memberof Port 9778 * @instance 9779 * @description return port name 9780 */ 9781 getName() 9782 { 9783 return this.name; 9784 } 9785 9786 /** 9787 * @function getTitle 9788 * @memberof Port 9789 * @instance 9790 * @description return port name or title 9791 */ 9792 getTitle() 9793 { 9794 if (this.uiAttribs.title) return this.uiAttribs.title; 9795 return this.name; 9796 } 9797 9798 /** 9799 * @param {Link} l 9800 */ 9801 addLink(l) 9802 { 9803 this.#valueBeforeLink = this.value; 9804 this.links.push(l); 9805 if (CABLES.UI && this._op.checkLinkTimeWarnings) this._op.checkLinkTimeWarnings(); 9806 9807 try 9808 { 9809 if (this.onLinkChanged) this.onLinkChanged(); 9810 this.emitEvent("onLinkChanged"); 9811 this._op.emitEvent("onLinkChanged"); 9812 } 9813 catch (e) 9814 { 9815 this._log.error(e); 9816 } 9817 } 9818 9819 /** 9820 * @function getLinkTo 9821 * @memberof Port 9822 * @instance 9823 * @param {Port} p2 otherPort 9824 * @description return link, which is linked to otherPort 9825 */ 9826 getLinkTo(p2) 9827 { 9828 for (const i in this.links) if (this.links[i].portIn == p2 || this.links[i].portOut == p2) return this.links[i]; 9829 } 9830 9831 /** 9832 * @function removeLinkTo 9833 * @memberof Port 9834 * @instance 9835 * @param {Port} p2 otherPort 9836 * @description removes link, which is linked to otherPort 9837 */ 9838 removeLinkTo(p2) 9839 { 9840 for (const i in this.links) 9841 { 9842 if (this.links[i].portIn == p2 || this.links[i].portOut == p2) 9843 { 9844 this.links[i].remove(); 9845 if (CABLES.UI && this._op.checkLinkTimeWarnings) this._op.checkLinkTimeWarnings(); 9846 9847 if (this.onLinkChanged) this.onLinkChanged(); 9848 this.emitEvent("onLinkChanged"); 9849 this.emitEvent("onLinkRemoved"); 9850 return; 9851 } 9852 } 9853 } 9854 9855 /** 9856 * @function isLinkedTo 9857 * @memberof Port 9858 * @instance 9859 * @param {Port} p2 otherPort 9860 * @description returns true if port is linked to otherPort 9861 */ 9862 isLinkedTo(p2) 9863 { 9864 for (const i in this.links) if (this.links[i].portIn == p2 || this.links[i].portOut == p2) return true; 9865 9866 return false;
9867 } 9868 9869 _activity() 9870 { 9871 this.activityCounter++; 9872 } 9873 9874 /** 9875 * @function trigger 9876 * @memberof Port 9877 * @instance 9878 * @description trigger the linked port (usually invoked on an output function port) 9879 */ 9880 trigger() 9881 { 9882 const linksLength = this.links.length; 9883 9884 this._activity(); 9885 if (linksLength === 0) return; 9886 if (!this._op.enabled) return; 9887 9888 let portTriggered = null; 9889 try 9890 { 9891 for (let i = 0; i < linksLength; ++i) 9892 { 9893 if (this.links[i].portIn) 9894 { 9895 portTriggered = this.links[i].portIn; 9896 9897 portTriggered.op.patch.pushTriggerStack(portTriggered); 9898 if (!portTriggered._onTriggered) 9899 { 9900 console.log(portTriggered, portTriggered._onTriggered); 9901 } 9902 portTriggered._onTriggered(null); 9903 9904 portTriggered.op.patch.popTriggerStack(); 9905 } 9906 if (this.links[i]) this.links[i].activity(); 9907 } 9908 } 9909 catch (ex) 9910 { 9911 portTriggered.op.enabled = false; 9912 9913 if (this._op.patch.isEditorMode()) 9914 { 9915 if (portTriggered.op.onError) portTriggered.op.onError(ex); 9916 } 9917 this._log.error("exception in port: ", portTriggered.name, portTriggered.op.name, portTriggered.op.id); 9918 this._log.error(ex); 9919 } 9920 } 9921 9922 call() 9923 { 9924 this._log.warn("call deprecated - use trigger() "); 9925 this.trigger(); 9926 } 9927 9928 execute() 9929 { 9930 } 9931 9932 /** 9933 * @param {string} n 9934 */ 9935 setVariableName(n) 9936 { 9937 this.#useVariableName = n; 9938 9939 this._op.patch.on("variableRename", (oldname, newname) => 9940 { 9941 if (oldname != this.#useVariableName) return; 9942 this.#useVariableName = newname; 9943 }); 9944 } 9945 9946 getVariableName() 9947 { 9948 return this.#useVariableName; 9949 } 9950 9951 /** 9952 * @param {String} v 9953 */ 9954 setVariable(v) 9955 { 9956 this.setAnimated(false); 9957 const attr = { "useVariable": false }; 9958 9959 if (this._variableIn && this._varChangeListenerId) 9960 { 9961 this._variableIn.off(this._varChangeListenerId); 9962 this._variableIn = null; 9963 } 9964 9965 if (v) 9966 { 9967 this._variableIn = this._op.patch.getVar(v); 9968 9969 if (!this._variableIn) 9970 { 9971 // this._log.warn("PORT VAR NOT FOUND!!!", v); 9972 } 9973 else 9974 { 9975 if (this.type == Port.TYPE_OBJECT) 9976 { 9977 this._varChangeListenerId = this._variableIn.on("change", () => { this.set(null); this.set(this._variableIn.getValue()); }); 9978 } 9979 else 9980 { 9981 this._varChangeListenerId = this._variableIn.on("change", this.set.bind(this)); 9982 } 9983 9984 this.set(this._variableIn.getValue()); 9985 } 9986 this.#useVariableName = v; 9987 attr.useVariable = true; 9988 attr.variableName = this.#useVariableName; 9989 } 9990 else 9991 { 9992 attr.variableName = this.#useVariableName = null; 9993 attr.useVariable = false; 9994 } 9995 9996 this.setUiAttribs(attr); 9997 this._op.patch.emitEvent("portSetVariable", this._op, this, v); 9998 } 9999 10000 /** 10001 * @param {boolean} a 10002 */ 10003 _handleNoTriggerOpAnimUpdates(a) 10004 { 10005 let hasTriggerPort = false;
10006 // for (let i = 0; i < this._op.portsIn.length; i++) 10007 // { 10008 // if (this._op.portsIn[i].type == Port.TYPE_FUNCTION) 10009 // { 10010 // hasTriggerPort = true; 10011 // break; 10012 // } 10013 // } 10014 10015 if (!hasTriggerPort) 10016 { 10017 if (a) 10018 this._notriggerAnimUpdate = this._op.patch.on("onRenderFrame", () => 10019 { 10020 this.updateAnim(); 10021 }); 10022 else if (this._notriggerAnimUpdate) this._notriggerAnimUpdate = this._op.patch.off(this._notriggerAnimUpdate); 10023 } 10024 } 10025 10026 bindAnimListeners() 10027 { 10028 this.anim.on(_anim_js__WEBPACK_IMPORTED_MODULE_3__.Anim.EVENT_CHANGE, () => 10029 { 10030 this._op.patch.emitEvent("portAnimUpdated", this._op, this, this.anim); 10031 this._op.patch.updateAnimMaxTimeSoon(); 10032 }); 10033 this.anim.on(_anim_js__WEBPACK_IMPORTED_MODULE_3__.Anim.EVENT_KEY_DELETE, () => 10034 { 10035 this._op.patch.updateAnimMaxTimeSoon(); 10036 }); 10037 10038 } 10039 10040 /** 10041 * @param {boolean} a 10042 */ 10043 setAnimated(a) 10044 { 10045 let changed = false; 10046 if (this.#animated != a) 10047 { 10048 this.#animated = a; 10049 this._op.hasAnimPort = true; 10050 changed = true; 10051 } 10052 10053 if (this.#animated && !this.anim) 10054 { 10055 this.anim = new _anim_js__WEBPACK_IMPORTED_MODULE_3__.Anim({ "name": "port " + this.name }); 10056 this.bindAnimListeners(); 10057 } 10058 10059 if (this.#animated) 10060 { 10061 let time = 0; 10062 if (window.gui && window.gui.glTimeline)time = this._op.patch.timer.getTime();// if timeline is already used otherwise create first key at 0 10063 10064 if (this.anim.keys.length == 0) this.anim.setValue(time, this.value); 10065 } 10066 else 10067 { 10068 this.anim = null; 10069 } 10070 10071 this._handleNoTriggerOpAnimUpdates(a); 10072 10073 this._op.patch.emitEvent("portAnimToggle", this._op, this, this.anim); 10074 10075 this.setUiAttribs({ "isAnimated": this.#animated }); 10076 if (changed) this._onAnimToggle(); 10077 } 10078 10079 toggleAnim() 10080 { 10081 this.setAnimated(!this.#animated); 10082 this.setUiAttribs({ "isAnimated": this.#animated }); 10083 this._op.patch.emitEvent("portAnimUpdated", this._op, this, this.anim); 10084 this._op.patch.emitEvent("portAnimToggle", this._op, this, this.anim); 10085 } 10086 10087 /** 10088 * <pre> 10089 * CABLES.Port.TYPE_VALUE = 0; 10090 * CABLES.Port.TYPE_FUNCTION = 1; 10091 * CABLES.Port.TYPE_OBJECT = 2; 10092 * CABLES.Port.TYPE_TEXTURE = 2; 10093 * CABLES.Port.TYPE_ARRAY = 3; 10094 * CABLES.Port.TYPE_DYNAMIC = 4; 10095 * CABLES.Port.TYPE_STRING = 5; 10096 * </pre> 10097 * @function getType 10098 * @memberof Port 10099 * @instance 10100 * @return {Number} type of port 10101 */ 10102 getType() 10103 { 10104 return this.type; 10105 } 10106 10107 /** 10108 * @function isLinked 10109 * @memberof Port 10110 * @instance 10111 * @return {Boolean} true if port is linked 10112 */ 10113 isLinked() 10114 { 10115 return this.links.length > 0 || this.#animated || this.#useVariableName != null; 10116 } 10117 10118 isBoundToVar() 10119 { 10120 const b = this.#useVariableName != null; 10121 this.uiAttribs.boundToVar = b; 10122 return b; 10123 } 10124 10125 /** 10126 * @return {Boolean} true if port is animated 10127 */ 10128 isAnimated() 10129 { 10130 return this.#animated; 10131 } 10132 10133 /** 10134 * @function isHidden 10135 * @memberof Port 10136 * @instance 10137 * @return {Boolean} true if port is hidden 10138 */ 10139 isHidden() 10140 { 10141 return this.uiAttribs.hidePort; 10142 } 10143 10144 /** 10145 * @function onTriggered 10146 * @memberof Port 10147 * @instance 10148 * @param {function} a onTriggeredCallback 10149 * @description set callback, which will be executed when port was triggered (usually output port) 10150 */ 10151 _onTriggered(a) 10152 { 10153 this._activity(); 10154 this._op.updateAnims(); 10155 if (this._op.enabled && this.onTriggered) this.onTriggered(a); 10156 10157 if (this._op.enabled) this.emitEvent("trigger"); 10158 } 10159 10160 /** 10161 * @param {any} v 10162 */ 10163 _onSetProfiling(v) // used in editor: profiler tab 10164 { 10165 this._op.patch.profiler.add("port", this); 10166 this.setValue(v); 10167 this._op.patch.profiler.add("port", null); 10168 } 10169 10170 _onTriggeredProfiling() // used in editor: profiler tab 10171 { 10172 if (this._op.enabled && this.onTriggered) 10173 { 10174 this._op.patch.profiler.add("port", this); 10175 this.onTriggered(); 10176 this._op.patch.profiler.add("port", null); 10177 } 10178 } 10179 10180 /** 10181 * @deprecated 10182 * @param {function} cb 10183 */ 10184 onValueChange(cb) 10185 { 10186 this.onChange = cb; 10187 } 10188 10189 /** 10190 * @deprecated 10191 */ 10192 hidePort() {} 10193 10194 /** 10195 * Returns the port type string, e.g. "value" based on the port type number 10196 * @function portTypeNumberToString 10197 * @instance 10198 * @memberof Port 10199 * @param {Number} type - The port type number 10200 * @returns {String} - The port type as string 10201 */ 10202 static portTypeNumberToString(type) 10203 { 10204 if (type == Port.TYPE_VALUE) return "value"; 10205 if (type == Port.TYPE_FUNCTION) return "function"; 10206 if (type == Port.TYPE_OBJECT) return "object"; 10207 if (type == Port.TYPE_ARRAY) return "array"; 10208 if (type == Port.TYPE_STRING) return "string"; 10209 if (type == Port.TYPE_DYNAMIC) return "dynamic"; 10210 return "unknown"; 10211 } 10212} 10213 10214 10215/***/ }), 10216
10217/***/ "./src/core/index.js": 10218/*!****************************************!*\ 10219 !*** ./src/core/index.js + 12 modules ***! 10220 \****************************************/ 10221/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 10222 10223"use strict"; 10224// ESM COMPAT FLAG 10225__webpack_require__.r(__webpack_exports__); 10226 10227// EXPORTS 10228__webpack_require__.d(__webpack_exports__, { 10229 Anim: () => (/* reexport */ anim.Anim), 10230 AnimKey: () => (/* reexport */ anim_key.AnimKey), 10231 CONSTANTS: () => (/* reexport */ constants.CONSTANTS), 10232 EMBED: () => (/* reexport */ EMBED), 10233 Link: () => (/* reexport */ Link), 10234 LoadingStatus: () => (/* reexport */ LoadingStatus), 10235 Op: () => (/* reexport */ Op), 10236 Patch: () => (/* reexport */ Patch), 10237 PatchVariable: () => (/* reexport */ PatchVariable), 10238 Port: () => (/* reexport */ core_port.Port), 10239 Profiler: () => (/* reexport */ Profiler), 10240 Timer: () => (/* reexport */ timer.Timer), 10241 "default": () => (/* binding */ core), 10242 now: () => (/* reexport */ timer.now), 10243 utils: () => (/* reexport */ utils) 10244}); 10245 10246// NAMESPACE OBJECT: ./node_modules/gl-matrix/esm/index.js 10247var esm_namespaceObject = {}; 10248__webpack_require__.r(esm_namespaceObject); 10249__webpack_require__.d(esm_namespaceObject, { 10250 glMatrix: () => (common), 10251 mat2: () => (mat2), 10252 mat2d: () => (mat2d), 10253 mat3: () => (mat3), 10254 mat4: () => (mat4), 10255 quat: () => (quat), 10256 quat2: () => (quat2), 10257 vec2: () => (vec2), 10258 vec3: () => (vec3), 10259 vec4: () => (vec4) 10260}); 10261 10262// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/common.js 10263var common = __webpack_require__("./node_modules/gl-matrix/esm/common.js"); 10264// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/mat2.js 10265var mat2 = __webpack_require__("./node_modules/gl-matrix/esm/mat2.js"); 10266// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/mat2d.js 10267var mat2d = __webpack_require__("./node_modules/gl-matrix/esm/mat2d.js"); 10268// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/mat3.js 10269var mat3 = __webpack_require__("./node_modules/gl-matrix/esm/mat3.js"); 10270// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/mat4.js 10271var mat4 = __webpack_require__("./node_modules/gl-matrix/esm/mat4.js"); 10272// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/quat.js 10273var quat = __webpack_require__("./node_modules/gl-matrix/esm/quat.js"); 10274// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/quat2.js 10275var quat2 = __webpack_require__("./node_modules/gl-matrix/esm/quat2.js"); 10276// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/vec2.js 10277var vec2 = __webpack_require__("./node_modules/gl-matrix/esm/vec2.js"); 10278// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/vec3.js 10279var vec3 = __webpack_require__("./node_modules/gl-matrix/esm/vec3.js"); 10280// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/vec4.js 10281var vec4 = __webpack_require__("./node_modules/gl-matrix/esm/vec4.js"); 10282;// CONCATENATED MODULE: ./node_modules/gl-matrix/esm/index.js 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294// EXTERNAL MODULE: ../shared/client/src/eventtarget.js + 2 modules 10295var eventtarget = __webpack_require__("../shared/client/src/eventtarget.js"); 10296// EXTERNAL MODULE: ../shared/client/src/logger.js 10297var logger = __webpack_require__("../shared/client/src/logger.js"); 10298// EXTERNAL MODULE: ./src/core/utils.js + 1 modules 10299var utils = __webpack_require__("./src/core/utils.js"); 10300// EXTERNAL MODULE: ./src/core/anim.js 10301var anim = __webpack_require__("./src/core/anim.js"); 10302// EXTERNAL MODULE: ./src/core/core_port.js 10303var core_port = __webpack_require__("./src/core/core_port.js"); 10304;// CONCATENATED MODULE: ./src/core/core_link.js 10305 10306 10307 10308 10309/** 10310 * @namespace external:CABLES#Link 10311 * @description a link is a connection between two ops/ports -> one input and one output port 10312 * @hideconstructor 10313 * @class 10314 */ 10315class Link extends eventtarget["default"] 10316{ 10317 10318 /** 10319 * @param {Patch} p 10320 */ 10321 constructor(p) 10322 { 10323 super(); 10324 10325 this.id = CABLES.simpleId(); 10326 10327 /** 10328 * @type {Port} 10329 */ 10330 this.portIn = null; 10331 10332 /** 10333 * @type {Port} 10334 */ 10335 this.portOut = null; 10336 10337 /** 10338 * @type {Patch} 10339 */ 10340 this._patch = p; 10341 this.activityCounter = 0; 10342 this.ignoreInSerialize = false;
10343 } 10344 10345 /** 10346 * @param {any} v 10347 */ 10348 setValue(v) 10349 { 10350 if (v === undefined) this._setValue(); 10351 else this.portIn.set(v); 10352 } 10353 10354 activity() 10355 { 10356 this.activityCounter++; 10357 } 10358 10359 _setValue() 10360 { 10361 if (!this.portOut) 10362 { 10363 this.remove(); 10364 return; 10365 } 10366 const v = this.portOut.get(); 10367 10368 if (v == v) // NaN is the only JavaScript value that is treated as unequal to itself 10369 { 10370 if (this.portIn.type != core_port.Port.TYPE_FUNCTION) this.activity(); 10371 10372 if (this.portIn.get() !== v) 10373 { 10374 this.portIn.set(v); 10375 } 10376 else 10377 { 10378 if (this.portIn.changeAlways) this.portIn.set(v); 10379 if (this.portOut.forceRefChange) this.portIn.forceChange(); 10380 } 10381 } 10382 } 10383 10384 /** 10385 * @function getOtherPort 10386 * @memberof Link 10387 * @instance 10388 * @param {Port} p port 10389 * @description returns the port of the link, which is not port 10390 */ 10391 getOtherPort(p) 10392 { 10393 if (p == this.portIn) return this.portOut; 10394 return this.portIn; 10395 } 10396 10397 /** 10398 * @function remove 10399 * @memberof Link 10400 * @instance 10401 * @description unlink/remove this link from all ports 10402 */ 10403 remove() 10404 { 10405 if (this.portIn) this.portIn.removeLink(this); 10406 if (this.portOut) this.portOut.removeLink(this); 10407 if (this._patch) 10408 { 10409 this._patch.emitEvent("onUnLink", this.portIn, this.portOut, this); 10410 } 10411 10412 if (this.portIn && (this.portIn.type == core_port.Port.TYPE_OBJECT || this.portIn.type == core_port.Port.TYPE_ARRAY)) 10413 { 10414 this.portIn.set(null); 10415 if (this.portIn.links.length > 0) this.portIn.set(this.portIn.links[0].getOtherPort(this.portIn).get()); 10416 } 10417 10418 if (this.portIn) this.portIn.op._checkLinksNeededToWork(); 10419 if (this.portOut) this.portOut.op._checkLinksNeededToWork(); 10420 10421 this.portIn = null; 10422 this.portOut = null; 10423 this._patch = null; 10424 } 10425 10426 /** 10427 * @function link 10428 * @memberof Link 10429 * @instance 10430 * @description link those two ports 10431 * @param {Port} p1 port1 10432 * @param {Port} p2 port2 10433 */ 10434 link(p1, p2) 10435 { 10436 if (!Link.canLink(p1, p2)) 10437 { 10438 console.warn("[core_link] cannot link ports!", p1, p2); 10439 return false; 10440 } 10441 10442 if (p1.direction == core_port.Port.DIR_IN) 10443 { 10444 this.portIn = p1; 10445 this.portOut = p2; 10446 } 10447 else 10448 { 10449 this.portIn = p2; 10450 this.portOut = p1; 10451 } 10452 10453 p1.addLink(this); 10454 p2.addLink(this); 10455 10456 this.setValue(); 10457 10458 p1.op._checkLinksNeededToWork(); 10459 p2.op._checkLinksNeededToWork(); 10460 } 10461 10462 getSerialized() 10463 { 10464 const obj = {}; 10465 10466 obj.portIn = this.portIn.getName(); 10467 obj.portOut = this.portOut.getName(); 10468 obj.objIn = this.portIn.op.id; 10469 obj.objOut = this.portOut.op.id; 10470 10471 return obj; 10472 } 10473 10474 /** 10475 * return a text message with human readable reason if ports can not be linked, or can be 10476 * 10477 * @param {Port} p1 port1 10478 * @param {Port} p2 port2 10479 */ 10480 static canLinkText(p1, p2) 10481 { 10482 if (p1.direction == p2.direction) 10483 { 10484 let txt = "(out)"; 10485 if (p2.direction == core_port.Port.DIR_IN) txt = "(in)"; 10486 return "can not link: same direction " + txt; 10487 } 10488 if (p1.op == p2.op) return "can not link: same op"; 10489 if (p1.type != core_port.Port.TYPE_DYNAMIC && p2.type != core_port.Port.TYPE_DYNAMIC) 10490 { 10491 if (p1.type != p2.type) return "can not link: different type"; 10492 } 10493 10494 if (CABLES.UI && p1.type == core_port.Port.TYPE_OBJECT && p2.type == core_port.Port.TYPE_OBJECT) 10495 { 10496 if (p1.uiAttribs.objType && p2.uiAttribs.objType) 10497 if (p1.uiAttribs.objType != p2.uiAttribs.objType) 10498 return "incompatible objects"; 10499 } 10500 10501 if (!p1) return "can not link: port 1 invalid"; 10502 if (!p2) return "can not link: port 2 invalid"; 10503 10504 if (p1.direction == core_port.Port.DIR_IN && p1.isAnimated()) return "can not link: is animated"; 10505 if (p2.direction == core_port.Port.DIR_IN && p2.isAnimated()) return "can not link: is animated"; 10506 10507 if (p1.isLinkedTo(p2)) return "ports already linked"; 10508 10509 if ((p1.canLink && !p1.canLink(p2)) || (p2.canLink && !p2.canLink(p1))) return "Incompatible"; 10510 10511 return "can link"; 10512 } 10513 10514 /** 10515 * return true if ports can be linked 10516 * 10517 * @param {Port} p1 port1 10518 * @param {Port} p2 port2 10519 * @returns {Boolean} 10520 */ 10521 static canLink(p1, p2) 10522 { 10523 if (!p1) return false;
10524 if (!p2) return false; 10525 if (p1.direction == core_port.Port.DIR_IN && p1.isAnimated()) return false; 10526 if (p2.direction == core_port.Port.DIR_IN && p2.isAnimated()) return false; 10527 10528 if (p1.isHidden() || p2.isHidden()) return false; 10529 10530 if (p1.isLinkedTo(p2)) return false; 10531 10532 if (p1.direction == p2.direction) return false; 10533 10534 if (CABLES.UI && p1.type == core_port.Port.TYPE_OBJECT && p2.type == core_port.Port.TYPE_OBJECT) 10535 { 10536 if (p1.uiAttribs.objType && p2.uiAttribs.objType) 10537 { 10538 if (p1.uiAttribs.objType.indexOf("sg_") == 0 && p2.uiAttribs.objType.indexOf("sg_") == 0) return true; 10539 if (p1.uiAttribs.objType != p2.uiAttribs.objType) 10540 return false; 10541 } 10542 } 10543 10544 if (p1.type != p2.type && (p1.type != core_port.Port.TYPE_DYNAMIC && p2.type != core_port.Port.TYPE_DYNAMIC)) return false; 10545 if (p1.type == core_port.Port.TYPE_DYNAMIC || p2.type == core_port.Port.TYPE_DYNAMIC) return true; 10546 10547 if (p1.op == p2.op) return false; 10548 10549 if (p1.canLink && !p1.canLink(p2)) return false; 10550 if (p2.canLink && !p2.canLink(p1)) return false; 10551 10552 return true; 10553 } 10554} 10555 10556// -------------------------------------------- 10557 10558// EXTERNAL MODULE: ./src/corelibs/cgl/index.js + 4 modules 10559var cgl = __webpack_require__("./src/corelibs/cgl/index.js"); 10560// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_state.js 10561var cgl_state = __webpack_require__("./src/corelibs/cgl/cgl_state.js"); 10562// EXTERNAL MODULE: ./src/core/constants.js 10563var constants = __webpack_require__("./src/core/constants.js"); 10564;// CONCATENATED MODULE: ./src/core/core_port_switch.js 10565 10566 10567class SwitchPort extends core_port.Port 10568{ 10569 constructor(__parent, name, type, uiAttribs, indexPort) 10570 { 10571 super(__parent, name, type, uiAttribs); 10572 10573 this.get = () => 10574 { 10575 let s = super.get(); 10576 10577 if (CABLES.UI) 10578 { 10579 if ( 10580 s === "" || 10581 s === null || 10582 s === undefined || 10583 (uiAttribs.values && uiAttribs.values.indexOf(String(s)) === -1) 10584 ) 10585 { 10586 this.op.setUiError("invalidswitch", "Invalid Value [" + this.name + "]: \"" + s + "\"", 1); 10587 } 10588 else this.op.setUiError("invalidswitch", null); 10589 } 10590 10591 if (s === null || s === undefined)s = ""; 10592 10593 return s; 10594 }; 10595 10596 this.indexPort = indexPort; 10597 this.indexPort.set = (value) => 10598 { 10599 const values = uiAttribs.values; 10600 10601 if (!values) 10602 { 10603 // console.log("switch port has no values", this); 10604 return; 10605 } 10606 10607 let intValue = Math.floor(value); 10608 10609 intValue = Math.min(intValue, values.length - 1); 10610 intValue = Math.max(intValue, 0); 10611 10612 this.indexPort.setValue(intValue); 10613 this.set(values[intValue]); 10614 10615 if (this.op.patch.isEditorMode() && performance.now() - (this.lastTime || 0) > 100 && window.gui && gui.patchView.isCurrentOp(this.op)) 10616 { 10617 gui.opParams.show(this.op); 10618 this.lastTime = performance.now(); 10619 } 10620 }; 10621 } 10622 10623 setUiAttribs(attribs) 10624 { 10625 const hidePort = attribs.hidePort; 10626 attribs.hidePort = true; 10627 super.setUiAttribs(attribs); 10628 if (typeof hidePort !== "undefined") 10629 { 10630 this.indexPort.setUiAttribs({ hidePort }); 10631 } 10632 } 10633} 10634 10635;// CONCATENATED MODULE: ./src/core/core_port_select.js 10636 10637 10638class ValueSelectPort extends SwitchPort 10639{ 10640 setUiAttribs(newAttribs) 10641 { 10642 // never unhide valuePort when indexPort is linked 10643 if (this.indexPort.isLinked()) 10644 { 10645 for (const p in newAttribs) 10646 { 10647 if (p == "greyout" && !newAttribs[p]) newAttribs[p] = "true"; 10648 } 10649 } 10650 super.setUiAttribs(newAttribs); 10651 } 10652} 10653 10654;// CONCATENATED MODULE: ./src/core/core_port_multi.js 10655 10656 10657 10658const MIN_NUM_PORTS = 2; 10659 10660class MultiPort extends core_port.Port 10661{ 10662 10663 /** 10664 * @param {import("./core_op.js").Op<any>} __parent 10665 * @param {string} name 10666 * @param {number} type 10667 * @param {number} dir 10668 * @param {import("./core_port.js").PortUiAttribs} uiAttribs 10669 * @param {{}} [uiAttribsPorts] 10670 */ 10671 constructor(__parent, name, type, dir, uiAttribs, uiAttribsPorts) 10672 { 10673 super(__parent, name, core_port.Port.TYPE_ARRAY, uiAttribs); 10674 10675 this.setUiAttribs({ "multiPort": true, "group": this.name, "order": -1 }); 10676 this.ports = []; 10677 this.direction = dir; 10678 this._uiAttribsPorts = uiAttribsPorts; 10679 10680 const updateArray = () => 10681 { 10682 const arr = []; 10683 10684 let ll = 1; 10685 if (this.uiAttribs.multiPortManual)ll = 0; 10686 10687 for (let i = 0; i < this.ports.length - ll; i++) 10688 arr[i] = this.ports[i]; 10689 10690 this.setRef(arr); 10691 }; 10692 10693 const updateUi = () => 10694 { 10695 let grey = !this.uiAttribs.multiPortManual || false; 10696 10697 if (this.direction == constants.CONSTANTS.PORT.PORT_DIR_OUT)grey = false;
10698 10699 for (let i = 0; i < this.ports.length; i++) 10700 { 10701 let lp; // undefined to remove/not set it 10702 // let opacity;// undefined to remove/not set it 10703 // let grey;// undefined to remove/not set it 10704 let addPort = false; 10705 let title; 10706 let o = {}; 10707 10708 // console.log("this.op.preservedPortTitles", this.op.preservedPortTitles, this.op.preservedPortTitles[po.name], po.name); 10709 if (this.op.preservedPortTitles && this.op.preservedPortTitles[this.ports[i].name]) title = this.op.preservedPortTitles[this.ports[i].name]; 10710 10711 // if (!this.uiAttribs.multiPortManual)grey = true; 10712 if (i == 0) lp = this.ports.length; 10713 10714 if (!this.uiAttribs.multiPortManual) 10715 if (i == this.ports.length - 1) 10716 { 10717 title = "add port"; 10718 addPort = true; 10719 grey = true; 10720 } 10721 10722 for (const attin in this._uiAttribsPorts) 10723 { 10724 o[attin] = this._uiAttribsPorts[attin]; 10725 } 10726 10727 o.addPort = addPort; 10728 o.longPort = lp; 10729 o.title = title; 10730 o.greyout = grey; 10731 o.group = this.name; 10732 10733 this.ports[i].setUiAttribs(o); 10734 } 10735 }; 10736 10737 this.removeInvalidPorts = () => 10738 { 10739 for (let i = 0; i < this.ports.length; i++) 10740 { 10741 if (!this.ports[i]) this.ports.splice(i, 1); 10742 } 10743 10744 if (!this.uiAttribs.multiPortManual) 10745 { 10746 if (this.ports.length > MIN_NUM_PORTS) 10747 10748 for (let i = this.ports.length - 1; i > 1; i--) 10749 { 10750 if (!this.ports[i].isLinked()) this.uiAttribs.multiPortNum = i; 10751 else break; 10752 } 10753 } 10754 10755 updateArray(); 10756 }; 10757 10758 this.countPorts = () => 10759 { 10760 if (CABLES.UI && !gui.isRemoteClient && gui.patchView && gui.patchView.patchRenderer && gui.patchView.patchRenderer.isDraggingPort()) 10761 { 10762 clearTimeout(this.retryTo); 10763 this.retryTo = setTimeout(this.countPorts.bind(this)); 10764 return; 10765 } 10766 this.retryTo = null; 10767 10768 let redo = false; 10769 this.removeListeners(); 10770 this.removeInvalidPorts(); 10771 10772 for (let i = 0; i < this.ports.length; i++) 10773 { 10774 if (this.ports[i] && this.ports[i].links.length > 1) 10775 { 10776 const po = this.ports[i + 1]; 10777 const otherPort = this.ports[i].links[0].getOtherPort(this.ports[i]); 10778 10779 if (!po || !otherPort) 10780 { 10781 this._log.warn("no port found?"); 10782 } 10783 else 10784 { 10785 this.ports[i].links[0].remove(); 10786 this.op.patch.link(this.op, po.name, otherPort.op, otherPort.name); 10787 redo = true; 10788 } 10789 break; 10790 } 10791 } 10792 10793 if (!this.uiAttribs.multiPortManual) 10794 { 10795 let foundHole = true; 10796 while (foundHole) 10797 { 10798 // console.log("search holes..."); 10799 foundHole = false; 10800 10801 for (let i = this.ports.length - 1; i > 1; i--) 10802 { 10803 if (this.ports[i] && this.ports[i].links.length > 0 && this.ports[i - 1].links.length == 0) 10804 { 10805 // console.log("found hole!"); 10806 10807 // found hole 10808 const otherPort = this.ports[i].links[0].getOtherPort(this.ports[i]); 10809 this.ports[i].links[0].remove(); 10810 10811 const po = this.ports[i - 1]; 10812 10813 if (po && this.ports[i]) 10814 { 10815 // console.log("move ", this.ports[i].name, "to", po.name); 10816 this.op.patch.link(this.op, po.name, otherPort.op, otherPort.n
10816ame); 10817 foundHole = true; 10818 redo = true; 10819 break; 10820 } 10821 } 10822 } 10823 10824 // this.checkNum(); 10825 } 10826 10827 // this.removeInvalidPorts(); 10828 } 10829 10830 if (!this.uiAttribs.multiPortManual) // if auto 10831 { 10832 while (this.ports.length > MIN_NUM_PORTS && !this.ports[this.ports.length - 1].isLinked() && !this.ports[this.ports.length - 2].isLinked()) 10833 { 10834 let i = this.ports.length - 1; 10835 if (!this.ports[i].isLinked() && this.ports[i - 1] && !this.ports[i - 1].isLinked()) 10836 { 10837 this.ports[i].setUiAttribs({ "removed": true }); 10838 this.ports[i].remove(); 10839 // this.ports[i] = null; 10840 this.ports.splice(i, 1); 10841 } 10842 } 10843 } 10844 10845 this.removeInvalidPorts(); 10846 10847 if (!this.uiAttribs.multiPortManual && this.ports.length > 0 && this.ports[this.ports.length - 1].isLinked()) this.newPort(); 10848 10849 updateArray(); 10850 updateUi(); 10851 10852 if (redo) this.countPorts(); 10853 else this.addListeners(); 10854 }; 10855 10856 this.removeListeners = () => 10857 { 10858 for (let i = 0; i < this.ports.length; i++) 10859 { 10860 const po = this.ports[i]; 10861 if (po.multiPortChangeListener) po.multiPortChangeListener = po.off(po.multiPortChangeListener); 10862 if (po.multiLinkChangeListener) po.multiLinkChangeListener = po.off(po.multiLinkChangeListener); 10863 } 10864 }; 10865 10866 this.addListeners = () => 10867 { 10868 for (let i = 0; i < this.ports.length; i++) 10869 { 10870 const po = this.ports[i]; 10871 const idx = i; 10872 10873 if (po.multiPortChangeListener)po.multiPortChangeListener = po.off(po.multiPortChangeListener); 10874 po.multiPortChangeListener = po.on("change", updateArray.bind(this)); 10875 10876 if (po.multiPortTriggerListener)po.multiPortTriggerListener = po.off(po.multiPortTriggerListener); 10877 po.multiPortTriggerListener = po.on("trigger", () => { this._onTriggered(idx); }); 10878 10879 if (po.multiLinkChangeListener)po.multiLinkChangeListener = po.off(po.multiLinkChangeListener); 10880 po.multiLinkChangeListener = po.on("onLinkChanged", () => 10881 { 10882 this.countPorts(); 10883 this.emitEvent("onLinkChanged"); 10884 }); 10885 10886 if (po.multiLinkRemoveListener)po.multiLinkRemoveListener = po.off(po.multiLinkRemoveListener); 10887 po.multiLinkRemoveListener = po.on("onLinkRemoved", () => 10888 { 10889 // this.removeInvalidPorts(); 10890 // this.checkNum(); 10891 // this.countPorts(); 10892 updateUi(); 10893 this.emitEvent("onLinkChanged"); 10894 // this.countPorts.bind(this); 10895 }); 10896 } 10897 }; 10898 10899 this.newPort = () => 10900 { 10901 const attrs = {}; 10902 // if (type == CABLES.OP_PORT_TYPE_STRING) attrs.type = "string"; 10903 attrs.type = type; 10904 const po = new core_port.Port(this.op, name + "_" + this.ports.length, type, attrs); 10905 10906 po.direction = dir; 10907 this.ports.push(po); 10908 // console.log("CONSTANTS.PORT_DIR_OUT", CONSTANTS.PORT.PORT_DIR_OUT, this.direction); 10909 if (this.direction == constants.CONSTANTS.PORT.PORT_DIR_OUT) this.op.addOutPort(po); 10910 else this.op.addInPort(po); 10911 10912 if (type == core_port.Port.TYPE_NUMBER) po.setInitialValue(0); 10913 else if (type == core_port.Port.TYPE_STRING) po.setInitialValue(""); 10914 10915 this.addListeners(); 10916 10917 updateUi(); 10918 updateArray(); 10919 this.emitEvent("onLinkChanged"); 10920 // console.log("this.op.preservedPortTitles", this.op.preservedPortTitles, this.op.preservedPortTitles[po.name], po.name); 10921 if (this.op.preservedPortTitles && this.op.preservedPortTitles[po.name]) po.setUiAttribs({ "title": this.op.preservedPortTitles[po.name] }); 10922 10923 return po; 10924 }; 10925 10926 this.initPorts = () => 10927 { 10928 for (let i = 0; i < MIN_NUM_PORTS; i++) this.newPort(); 10929 updateArray(); 10930 updateUi(); 10931 }; 10932 10933 this.checkNum = () => 10934 { 10935 this.uiAttribs.multiPortNum = Math.max(MIN_NUM_PORTS, this.uiAttribs.multiPortNum); 10936 10937 while (this.ports.length < this.uiAttribs.multiPortNum) this.newPort(); 10938 while (this.ports.length > this.uiAttribs.multiPortNum) if (this.ports[this.ports.length - 1]) this.ports.pop().remove(); 10939 10940 this.removeInvalidPorts(); 10941 }; 10942 10943 this.incDec = (incDir) => 10944 { 10945 this.uiAttribs.multiPortNum = this.uiAttribs.multiPortNum || MIN_NUM_PORTS; 10946 // console.log("this.uiAttribs.multiPortNum", this.uiAttribs.multiPortNum, this.uiAttribs.multiPortNum + incDir); 10947 this.setUiAttribs({ "multiPortNum": this.uiAttribs.multiPortNum + incDir }); 10948 this.checkNum(); 10949 10950 updateUi(); 10951 }; 10952 10953 this.toggleManual = () => 10954 { 10955 this.setUiAttribs({ "multiPortManual": !this.uiAttribs.multiPortManual }); 10956 this.op.refreshParams(); 10957 }; 10958 10959 this.on("onUiAttrChange", (attribs) => 10960 { 10961 if (attribs.hasOwnProperty("multiPortManual")) 10962 { 10963 updateUi(); 10964 this.removeInvalidPorts(); 10965 this.checkNum(); 10966 this.countPorts(); 10967 updateUi(); 10968 } 10969 }); 10970 10971 this.on("onUiAttrChange", this.checkNum.bind(this)); 10972 this.checkNum(); 10973 this.countPorts(); 10974 this.removeInvalidPorts(); 10975 updateUi(); 10976 } 10977} 10978 10979;// CONCATENATED MODULE: ./src/core/core_op.js 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991/** 10992 * @typedef Translation 10993 * @property {number} [x] 10994 * @property {number} [y] 10995 */ 10996
10997/** 10998 * configuration object for loading a patch 10999 * @typedef OpUiAttribs 11000 * @property {string} [title] overwrite op title 11001 * @property {string} [hidePort] hidePort 11002 * @property {string} [title] overwrite op title 11003 * @property {String} [title=''] overwrite title of port (by default this is portname) 11004 * @property {string} [extendTitle] extended op title, shown in grey next to op name 11005 * @property {object} [storage] 11006 * @property {boolean} [working] 11007 * @property {boolean} [bookmarked] 11008 * @property {boolean} [selected] 11009 * @property {boolean} [disabled] 11010 * @property {boolean} [loading] 11011 * @property {boolean} [resizable] 11012 * @property {boolean} [hidden] 11013 * @property {object} [uierrors] 11014 * @property {string} [color] 11015 * @property {object} [area] 11016 * @property {string} [comment] 11017 * @property {number} [height] 11018 * @property {number} [width] 11019 * @property {Translation} [translate] 11020 * @property {string|number} [subPatch] 11021 * @property {string} [comment_title] 11022 */ 11023 11024/** 11025 * @typedef CorePatch 11026 * @type Patch 11027 */ 11028 11029/** 11030 * @template {CorePatch} Patch 11031 */ 11032class Op extends eventtarget["default"] 11033{ 11034 static OP_VERSION_PREFIX = "_v"; 11035 static EVENT_INIT = "init"; 11036 static EVENT_UIATTR_CHANGE = "onUiAttribsChange"; 11037 11038 #objName = ""; 11039 _log = new logger["default"]("core_op"); 11040 // #name = ""; 11041 #shortOpName = ""; 11042 11043 opId = ""; // unique op id 11044 11045 /** @type {Array<Port>} */ 11046 portsOut = []; 11047 11048 /** @type {Patch} */ 11049 patch = null; 11050 11051 data = {}; // UNUSED, DEPRECATED, only left in for backwards compatibility with userops 11052 storage = {}; // op-specific data to be included in export 11053 11054 /** @type {Array<Port>} */ 11055 portsIn = []; 11056 portsInData = []; // original loaded patch data 11057 11058 /** @type {OpUiAttribs} */ 11059 uiAttribs = {}; 11060 enabled = true; 11061 11062 onAnimFrame = null; 11063 11064 preservedPortTitles = {}; 11065 preservedPortValues = {}; 11066 preservedPortLinks = {}; 11067 11068 linkTimeRules = { 11069 "needsLinkedToWork": [], 11070 "needsStringToWork": [], 11071 "needsParentOp": null 11072 }; 11073 11074 shouldWork = {}; 11075 hasUiErrors = 0; 11076 11077 /** @type {Object} */ 11078 uiErrors = {}; 11079 hasAnimPort = false;
11080 11081 /** @type {Port} */ 11082 patchId = null; // will be defined by subpatchops 11083 11084 /** 11085 * @param {Patch} _patch 11086 * @param {String} _objName 11087 * @param {String} _id=null 11088 */ 11089 constructor(_patch, _objName, _id = null) 11090 { 11091 super(); 11092 11093 // this.#name = _objName; 11094 this.opId = _id; 11095 this.#objName = _objName; 11096 this.patch = _patch; 11097 11098 this.#shortOpName = CABLES.getShortOpName(_objName); 11099 this.getTitle(); 11100 11101 this.id = _id || (0,utils.shortId)(); // instance id 11102 this.onAddPort = null; 11103 this.onCreate = null; 11104 this.onResize = null; 11105 this.onLoaded = null; 11106 this.onDelete = null; 11107 this.onError = null; 11108 11109 this._instances = null; 11110 11111 /** 11112 * overwrite this to prerender shader and meshes / will be called by op `loadingStatus` 11113 */ 11114 this.preRender = null; 11115 11116 /** 11117 * overwrite this to initialize your op 11118 */ 11119 this.init = null; 11120 11121 /** 11122 * Implement to render 2d canvas based graphics from in an op - optionaly defined in op instance 11123 * @param {CanvasRenderingContext2D} context of canvas 2d 11124 * @param {Object} layer info 11125 * @param {number} layer.x x position on canvas 11126 * @param {number} layer.y y position on canvas 11127 * @param {number} layer.width width of canvas 11128 * @param {number} layer.height height of canvas 11129 * @param {number} layer.scale current scaling of patchfield view 11130 */ 11131 } 11132 11133 isInBlueprint2() // will be overwritten in ui 11134 { 11135 return false; 11136 } 11137 11138 get name() 11139 { 11140 return this.getTitle(); 11141 } 11142 11143 set name(n) 11144 { 11145 this.setTitle(n); 11146 } 11147 11148 /** 11149 * @param {string} on 11150 */ 11151 set _objName(on) 11152 { 11153 this.#objName = on; 11154 this._log = new logger["default"]("op " + on); 11155 } 11156 11157 get objName() 11158 { 11159 return this.#objName; 11160 } 11161 11162 get shortName() 11163 { 11164 return this.#shortOpName; 11165 } 11166 11167 /** 11168 * op.require 11169 * 11170 * @param {String} _name - module name 11171 * @returns {Object} 11172 */ 11173 require(_name) 11174 { 11175 if (CABLES.platform && CABLES.StandaloneElectron && !CABLES.platform.frontendOptions.isElectron) 11176 this.setUiError("notstandalone", "This op will only work in cables standalone version", 3); 11177 11178 return null; 11179 } 11180 11181 checkMainloopExists() 11182 { 11183 if (!CABLES.UI) return; 11184 if (!this.patch.tempData.mainloopOp) this.setUiError("nomainloop", "patch should have a mainloop to use this op"); 11185 else this.setUiError("nomainloop", null); 11186 } 11187 11188 /** @returns {string} */ 11189 getTitle() 11190 { 11191 if (!this.uiAttribs) return "nouiattribs" + this.shortName; 11192 11193 /* 11194 * if ((this.uiAttribs.title === undefined || this.uiAttribs.title === "") && this.objName.indexOf("Ops.Ui.") == -1) 11195 * this.uiAttribs.title = this._shortOpName; 11196 */ 11197 11198 return this.uiAttribs.title || this.#shortOpName; 11199 } 11200 11201 /** 11202 * @param {string} title 11203 */ 11204 setTitle(title) 11205 { 11206 11207 /* 11208 * this._log.log("settitle", title); 11209 * this._log.log( 11210 * (new Error()).stack 11211 * ); 11212 */ 11213 11214 if (title != this.getTitle()) this._setUiAttrib({ "title": title }); 11215 } 11216 11217 /** 11218 * @param {Object} newAttribs 11219 */ 11220 setStorage(newAttribs) 11221 { 11222 if (!newAttribs) return; 11223 this.storage = this.storage || {}; 11224 11225 let changed = false; 11226 for (const p in newAttribs) 11227 { 11228 if (this.storage[p] != newAttribs[p]) changed = true; 11229 this.storage[p] = newAttribs[p]; 11230 } 11231 11232 if (changed) this.emitEvent("onStorageChange", newAttribs); 11233 } 11234 11235 isSubPatchOp() 11236 { 11237 if (this.patchId && this.storage) return (this.storage.subPatchVer || this.storage.blueprintVer || 0); 11238 return false; 11239 } 11240 11241 /** 11242 * setUiAttrib 11243 * possible values: 11244 * <pre> 11245 * warning - warning message - showing up in op parameter panel 11246 * error - error message - showing up in op parameter panel 11247 * extendTitle - op title extension, e.g. [ + ] 11248 * </pre> 11249 // * @param {OpUiAttribs} newAttribs, e.g. {"attrib":value} 11250 * @example 11251 * op.setUiAttrib({"extendTitle":str}); 11252 */ 11253 setUiAttrib(newAttribs) 11254 { 11255 this._setUiAttrib(newAttribs); 11256 } 11257 11258 /** 11259 * @param {OpUiAttribs} a 11260 */ 11261 setUiAttribs(a) 11262 { 11263 this._setUiAttrib(a); 11264 } 11265 11266 /** 11267 * @deprecated 11268 * @param {OpUiAttribs} a 11269 */ 11270 uiAttr(a) 11271 { 11272 this._setUiAttrib(a); 11273 } 11274 11275 /** 11276 * @TODO move to ui extend class..... 11277 * @param {OpUiAttribs} newAttribs 11278 */ 11279 _setUiAttrib(newAttribs) 11280 { 11281 if (!newAttribs) return; 11282 11283 if (typeof newAttribs != "object") this._log.error("op.uiAttrib attribs are not of type object"); 11284 if (!this.uiAttribs) this.uiAttribs = {}; 11285 11286 let changed = false;
11287 let emitMove = false; 11288 if ( 11289 CABLES.UI && 11290 newAttribs.hasOwnProperty("translate") && 11291 ( 11292 !this.uiAttribs.translate || 11293 this.uiAttribs.translate.x != newAttribs.translate.x || 11294 this.uiAttribs.translate.y != newAttribs.translate.y 11295 )) emitMove = true; 11296 11297 if (newAttribs.hasOwnProperty("title") && newAttribs.title != this.uiAttribs.title) 11298 { 11299 this.uiAttribs.title = newAttribs.title; 11300 changed = true; 11301 } 11302 11303 if (newAttribs.hasOwnProperty("disabled")) 11304 { 11305 changed = true; 11306 this.setEnabled(!newAttribs.disabled); 11307 } 11308 11309 for (const p in newAttribs) 11310 { 11311 if (this.uiAttribs[p] != newAttribs[p]) changed = true; 11312 this.uiAttribs[p] = newAttribs[p]; 11313 } 11314 11315 if (this.uiAttribs.hasOwnProperty("highlighted") && this.uiAttribs.highlighted == false) delete this.uiAttribs.highlighted; 11316 if (this.uiAttribs.hasOwnProperty("highlightedMore") && this.uiAttribs.highlightedMore == false) delete this.uiAttribs.highlightedMore; 11317 if (this.uiAttribs.hasOwnProperty("selected") && this.uiAttribs.selected == false) delete this.uiAttribs.selected; 11318 if (this.uiAttribs.hasOwnProperty("selected")) changed = true; 11319 11320 if (changed) 11321 { 11322 this.emitEvent(Op.EVENT_UIATTR_CHANGE, newAttribs); 11323 this.patch.emitEvent("onUiAttribsChange", this, newAttribs); 11324 } 11325 11326 if (emitMove) this.emitEvent("move"); 11327 } 11328 11329 getName() 11330 { 11331 return this.#shortOpName; 11332 } 11333 11334 /** 11335 * @param {Port} p 11336 */ 11337 addOutPort(p) 11338 { 11339 p.direction = constants.CONSTANTS.PORT.PORT_DIR_OUT; 11340 p._op = this; 11341 this.portsOut.push(p); 11342 this.emitEvent("onPortAdd", p); 11343 return p; 11344 } 11345 11346 hasDynamicPort() 11347 { 11348 let i = 0; 11349 for (i = 0; i < this.portsIn.length; i++) 11350 { 11351 if (this.portsIn[i].type == core_port.Port.TYPE_DYNAMIC) return true; 11352 if (this.portsIn[i].getName() == "dyn") return true; 11353 } 11354 for (i = 0; i < this.portsOut.length; i++) 11355 { 11356 if (this.portsOut[i].type == core_port.Port.TYPE_DYNAMIC) return true; 11357 if (this.portsOut[i].getName() == "dyn") return true; 11358 } 11359 11360 return false; 11361 } 11362 11363 /** 11364 * @param {any|Port | MultiPort} p 11365 */ 11366 addInPort(p) 11367 { 11368 p.direction = core_port.Port.DIR_IN; 11369 p._op = this; 11370 11371 this.portsIn.push(p); 11372 this.emitEvent("onPortAdd", p); 11373 11374 return p; 11375 } 11376 11377 /** 11378 * 11379 * @param {string} name 11380 * @param {string} v 11381 */ 11382 inFunction(name, v) 11383 { 11384 return this.inTrigger(name, v); 11385 } 11386 11387 /** 11388 * create a trigger input port 11389 * @param {String} name 11390 * @param {String} v 11391 * @return {Port} created port 11392 * 11393 */ 11394 inTrigger(name, v) 11395 { 11396 const p = this.addInPort(new core_port.Port(this, name, core_port.Port.TYPE_FUNCTION)); 11397 if (v !== undefined) p.set(v); 11398 return p; 11399 } 11400 11401 /** 11402 * create multiple UI trigger buttons 11403 * @param {String} name 11404 * @param {Array} v 11405 * @return {Port} created port 11406 */ 11407 inTriggerButton(name, v) 11408 { 11409 const p = this.addInPort( 11410 new core_port.Port(this, name, core_port.Port.TYPE_FUNCTION, { 11411 "display": "button" 11412 }) 11413 ); 11414 if (v !== undefined) p.set(v); 11415 return p; 11416 } 11417 11418 /** 11419 * @param {string} name 11420 * @param {any} v 11421 */ 11422 inUiTriggerButtons(name, v) 11423 { 11424 const p = this.addInPort( 11425 new core_port.Port(this, name, core_port.Port.TYPE_FUNCTION, { 11426 "display": "buttons" 11427 }) 11428 ); 11429 if (v !== undefined) p.set(v); 11430 return p; 11431 } 11432 11433 /** 11434 * @deprecated 11435 */ 11436 inValueFloat(name, v) 11437 { 11438 return this.inFloat(name, v); 11439 } 11440 11441 /** 11442 * @deprecated 11443 */ 11444 inValue(name, v) 11445 { 11446 return this.inFloat(name, v); 11447 } 11448 11449 /** 11450 * create a number value input port 11451 * @param {String} name 11452 * @param {Number} v 11453 * @return {Port} created port 11454 */ 11455 inFloat(name, v) 11456 { 11457 const p = this.addInPort(new core_port.Port(this, name, core_port.Port.TYPE_VALUE)); 11458 11459 p.setInitialValue(v); 11460 11461 return p; 11462 } 11463 11464 /** 11465 * @deprecated 11466 */ 11467 inValueBool(name, v) 11468 { 11469 return this.inBool(name, v); 11470 } 11471 11472 /** 11473 * create a boolean input port, displayed as a checkbox 11474 * @param {String} name 11475 * @param {Boolean|number} v 11476 * @return {Port} created port 11477 */ 11478 inBool(name, v) 11479 { 11480 const p = this.addInPort( 11481 new core_port.Port(this, name, core_port.Port.TYPE_NUMBER, { 11482 "display": "bool" 11483 }) 11484 ); 11485 11486 if (v === true)v = 1; 11487 if (v === false)v = 0; 11488 p.setInitialValue(v); 11489 11490 return p; 11491 } 11492 11493 /** 11494 * @param {string} name 11495 * @param {number} type 11496 */ 11497 inMultiPort(name, type) 11498 { 11499 const p = new MultiPort( 11500 this, 11501 name, 11502 type, 11503 core_port.Port.DIR_IN, 11504 { 11505 "addPort": true, 11506 "hidePort": true 11507 } 11508 ); 11509 p.ignoreValueSerialize = true; 11510 11511 this.addInPort(p); 11512 p.initPorts(); 11513 11514 return p; 11515 } 11516 11517 /** 11518 * @param {string} name 11519 * @param {number} type 11520 */ 11521 outMultiPort(name, type, uiAttribsPort = {}) 11522 { 11523 const p = new MultiPort( 11524 this, 11525 name, 11526 type, 11527 constants.CONSTANTS.PORT.PORT_DIR_OUT, 11528 { 11529 "display": "multiport", 11530 "hidePort": true 11531 }, 11532 uiAttribsPort 11533 ); 11534 p.ignoreValueSerialize = true; 11535 11536 this.addOutPort(p); 11537 p.initPorts(); 11538 11539 return p; 11540 } 11541 11542 /** 11543 * @param {string} name 11544 * @param {string} v 11545 */ 11546 inValueString(name, v) 11547 { 11548 const p = this.addInPort( 11549 new core_port.Port(this, name, core_port.Port.TYPE_VALUE, { 11550 "type": "string" 11551 }) 11552 ); 11553 p.value = ""; 11554 11555 p.setInitialValue(v); 11556 return p; 11557 } 11558 11559 /** 11560 * create a String value input port 11561 * @param {String} name 11562 * @param {String} v default value 11563 * @return {Port} created port 11564 */ 11565 inString(name, v) 11566 { 11567 const p = this.addInPort( 11568 new core_port.Port(this, name, core_port.Port.TYPE_STRING, { 11569 "type": "string" 11570 }) 11571 ); 11572 v = v || ""; 11573 11574 p.setInitialValue(v); 11575 return p; 11576 } 11577 11578 // /** 11579 // * create a String value input port displayed as TextArea 11580 // * @memberof Op 11581 // * @param {String} name 11582 // * @param {String} v default value 11583 // * @return {Port} created port 11584 // */ 11585 // inValueText(name, v) 11586 // { 11587 // const p = this.addInPort( 11588 // new Port(this, name, Port.TYPE_VALUE, { 11589 // "type": "string", 11590 // "display": "text" 11591 // }) 11592 // ); 11593 // p.value = ""; 11594 11595 // p.setInitialValue(v); 11596 11597 // /* 11598 // * if (v !== undefined) 11599 // * { 11600 // * p.set(v); 11601 // * p.defaultValue = v; 11602 // * } 11603 // */ 11604 // return p; 11605 // } 11606 11607 /** 11608 * @param {string} name 11609 * @param {string} v 11610 */ 11611 inTextarea(name, v) 11612 { 11613 const p = this.addInPort( 11614 new core_port.Port(this, name, core_port.Port.TYPE_STRING, { 11615 "type": "string", 11616 "display": "text" 11617 }) 11618 ); 11619 p.value = ""; 11620 if (v !== undefined) 11621 { 11622 p.set(v); 11623 p.defaultValue = v; 11624 } 11625 return p; 11626 } 11627 11628 /** 11629 * create a String value input port displayed as editor 11630 * @param {String} name 11631 * @param {String} v default value 11632 * @param {String} syntax language 11633 * @param {Boolean} hideFormatButton 11634 * @return {Port} created port 11635 */ 11636 inStringEditor(name, v, syntax, hideFormatButton = true) 11637 { 11638 const p = this.addInPort( 11639 new core_port.Port(this, name, core_port.Port.TYPE_STRING, { 11640 "type": "string", 11641 "display": "editor", 11642 "editShortcut": true, 11643 "editorSyntax": syntax, 11644 "hideFormatButton": hideFormatButton 11645 })); 11646 11647 p.value = ""; 11648 if (v !== undefined) 11649 { 11650 p.set(v); 11651 p.defaultValue = v; 11652 } 11653 return p; 11654 } 11655 11656 /** 11657 * 11658 * @param {string} name 11659 * @param {String} v 11660 * @param {String} syntax 11661 */ 11662 inValueEditor(name, v, syntax, hideFormatButton = true) 11663 { 11664 const p = this.addInPort( 11665 new core_port.Port(this, name, core_port.Port.TYPE_NUMBER, { 11666 "type": "string", 11667 "display": "editor", 11668 "editorSyntax": syntax, 11669 "hideFormatButton": hideFormatButton 11670 }) 11671 ); 11672 p.value = ""; 11673 if (v !== undefined) 11674 { 11675 p.set(v); 11676 p.defaultValue = v; 11677 } 11678 return p; 11679 } 11680 11681 /** 11682 * @deprecated 11683 * @param {string} name 11684 * @param {any[]} values 11685 * @param {string} v 11686 * @param {boolean} noindex 11687 */ 11688 inValueSelect(name, values, v, noindex) 11689 { 11690 return this.inDropDown(name, values, v, noindex); 11691 } 11692 11693 /** 11694 * create a string select box 11695 * @param {String} name 11696 * @param {Array} values 11697 * @param {String} v default value 11698 * @param {boolean} [noindex] 11699 * @return {Port} created port 11700 */ 11701 inDropDown(name, values, v, noindex) 11702 { 11703 let p = null; 11704 if (!noindex) 11705 { 11706 const indexPort = new core_port.Port(this, name + " index", core_port.Port.TYPE_NUMBER, { 11707 "increment": "integer", 11708 "hideParam": true 11709 }); 11710 const n = this.addInPort(indexPort); 11711 11712 if (values) for (let i = 0; i < values.length; i++) values[i] = String(values[i]); 11713 11714 const valuePort = new ValueSelectPort( 11715 this, 11716 name, 11717 core_port.Port.TYPE_NUMBER, 11718 { 11719 "display": "dropdown", 11720 "hidePort": true, 11721 "type": "string", 11722 "values": values 11723 }, 11724 n 11725 ); 11726 11727 valuePort.indexPort = indexPort; 11728 11729 valuePort.on("change", (/** @type {any} */ val, /** @type {Port} */ thePort) => 11730 { 11731 if (!thePort.indexPort.isLinked() && thePort.uiAttribs.values) 11732 { 11733 const idx = thePort.uiAttribs.values.indexOf(val); 11734 if (idx > -1) thePort.indexPort.set(idx); 11735 } 11736 }); 11737 11738 indexPort.onLinkChanged = () => 11739 { 11740 valuePort.setUiAttribs({ "greyout": indexPort.isLinked() }); 11741 }; 11742 11743 p = this.addInPort(valuePort); 11744 11745 if (v !== undefined) 11746 { 11747 p.set(v); 11748 const index = values.findIndex((item) => { return item == v; }); 11749 n.setValue(index); 11750 p.defaultValue = v; 11751 n.defaultValue = index; 11752 } 11753 } 11754 else 11755 { 11756 const valuePort = new core_port.Port(this, name, core_port.Port.TYPE_VALUE, { 11757 "display": "dropdown", 11758 "hidePort": true, 11759 "type": "string", 11760 "values": values 11761 }); 11762 11763 p = this.addInPort(valuePort); 11764 } 11765 11766 return p; 11767 } 11768 11769 /** 11770 * create a string switch box 11771 * @param {String} name 11772 * @param {Array} values 11773 * @param {String} v default value 11774 * @param {boolean} noindex 11775 * @return {Port} created port 11776 */ 11777 inSwitch(name, values, v, noindex) 11778 { 11779 let p = null; 11780 if (!noindex) 11781 { 11782 if (!v)v = values[0]; 11783 const indexPort = new core_port.Port(this, name + " index", core_port.Port.TYPE_VALUE, { 11784 "increment": "integer", 11785 "values": values, 11786 "hideParam": true 11787 }); 11788 const n = this.addInPort(indexPort); 11789 11790 if (values) for (let i = 0; i < values.length; i++) values[i] = String(values[i]); 11791 11792 const switchPort = new SwitchPort( 11793 this, 11794 name, 11795 core_port.Port.TYPE_STRING, 11796 { 11797 "display": "switch", 11798 "hidePort": true, 11799 "type": "string", 11800 "values": values 11801 }, 11802 n 11803 ); 11804 11805 switchPort.indexPort = indexPort; 11806 11807 switchPort.on("change", (val, thePort) => 11808 { 11809 if (!thePort.indexPort.isLinked() && thePort.uiAttribs.values) 11810 { 11811 const idx = thePort.uiAttribs.values.indexOf(val); 11812 if (idx > -1) thePort.indexPort.set(idx); 11813 } 11814 }); 11815 11816 indexPort.onLinkChanged = function () 11817 { 11818 switchPort.setUiAttribs({ "greyout": indexPort.isLinked() }); 11819 }; 11820 p = this.addInPort(switchPort); 11821 11822 if (v !== undefined) 11823 { 11824 p.set(v); 11825 const index = values.findIndex((item) => { return item == v; }); 11826 n.setValue(index); 11827 p.defaultValue = v; 11828 n.defaultValue = index; 11829 } 11830 } 11831 else 11832 { 11833 const switchPort = new core_port.Port(this, name, core_port.Port.TYPE_STRING, { 11834 "display": "switch", 11835 "hidePort": true, 11836 "type": "string", 11837 "values": values 11838 }); 11839 p = this.addInPort(switchPort); 11840 } 11841 11842 return p; 11843 } 11844 11845 /** 11846 * @deprecated 11847 */ 11848 inValueInt(name, v) 11849 { 11850 return this.inInt(name, v); 11851 } 11852 11853 /** 11854 * create a integer input port 11855 * @param {String} name 11856 * @param {number} v default value 11857 * @return {Port} created port 11858 */ 11859 inInt(name, v) 11860 { 11861 // old 11862 const p = this.addInPort( 11863 new core_port.Port(this, name, core_port.Port.TYPE_VALUE, { "increment": "integer" }) 11864 ); 11865 if (v !== undefined) 11866 { 11867 p.set(v); 11868 p.defaultValue = v; 11869 } 11870 return p; 11871 } 11872 11873 /** 11874 * create a file/URL input port 11875 * @param {String} name 11876 * @param {String} filter 11877 * @param {String} v 11878 * @return {Port} created port 11879 */ 11880 inFile(name, filter, v) 11881 { 11882 const p = this.addInPort( 11883 new core_port.Port(this, name, core_port.Port.TYPE_VALUE, { 11884 "display": "file", 11885 "type": "string", 11886 "filter": filter 11887 }) 11888 ); 11889 if (v !== undefined) 11890 { 11891 p.set(v); 11892 p.defaultValue = v; 11893 } 11894 return p; 11895 } 11896 11897 /** 11898 * create a file/URL input port 11899 * @param {String} name 11900 * @param {String} filter 11901 * @param {String} v 11902 * @return {Port} created port 11903 */ 11904 inUrl(name, filter, v) 11905 { 11906 const p = this.addInPort( 11907 new core_port.Port(this, name, core_port.Port.TYPE_STRING, { 11908 "display": "file", 11909 "type": "string", 11910 "filter": filter 11911 }) 11912 ); 11913 if (v !== undefined) 11914 { 11915 p.set(v); 11916 p.defaultValue = v; 11917 } 11918 return p; 11919 } 11920 11921 /** 11922 * create a texture input port 11923 * @param {String} name 11924 * @return {Port} created port 11925 */ 11926 inTexture(name, v) 11927 { 11928 const p = this.addInPort( 11929 new core_port.Port(this, name, core_port.Port.TYPE_OBJECT, { 11930 "display": "texture", 11931 "objType": "texture", 11932 "preview": true 11933 }) 11934 ); 11935 p.ignoreValueSerialize = true; 11936 if (v !== undefined) p.set(v); 11937 return p; 11938 } 11939 11940 /** 11941 * create a objec
11941t input port 11942 * @param {String} name 11943 * @param {Object} v 11944 * @param {String} objType 11945 * @return {Port} created port 11946 */ 11947 inObject(name, v, objType) 11948 { 11949 const p = this.addInPort(new core_port.Port(this, name, core_port.Port.TYPE_OBJECT, { "objType": objType })); 11950 p.ignoreValueSerialize = true; 11951 11952 if (v !== undefined) p.set(v); 11953 return p; 11954 } 11955 11956 /** 11957 * @param {string} name 11958 * @param {string} v 11959 */ 11960 inGradient(name, v) 11961 { 11962 const p = this.addInPort( 11963 new core_port.Port(this, name, core_port.Port.TYPE_VALUE, { 11964 "display": "gradient" 11965 // "hidePort": true 11966 }) 11967 ); 11968 if (v !== undefined) p.set(v); 11969 return p; 11970 } 11971 11972 /** 11973 * @param {Port} p 11974 * returns {number} 11975 */ 11976 getPortVisibleIndex(p) 11977 { 11978 let ports = this.portsIn; 11979 if (p.direction == constants.CONSTANTS.PORT_DIR_OUT)ports = this.portsOut; 11980 11981 let index = 0; 11982 for (let i = 0; i < ports.length; i++) 11983 { 11984 if (ports[i].uiAttribs.hidePort) continue; 11985 index++; 11986 if (ports[i] == p) return index; 11987 } 11988 } 11989 11990 /** 11991 * create a array input port 11992 * @param {String} name 11993 * @param {Array|Number} v 11994 * @param {Number} _stride 11995 * @return {Port} created port 11996 */ 11997 inArray(name, v = undefined, _stride = undefined) 11998 { 11999 let stride = _stride; 12000 // @ts-ignore 12001 if (!_stride && CABLES.isNumeric(v))stride = v; 12002 12003 const p = this.addInPort(new core_port.Port(this, name, core_port.Port.TYPE_ARRAY, { "stride": stride })); 12004 12005 if (v !== undefined && (Array.isArray(v) || v == null)) p.set(v); 12006 12007 return p; 12008 } 12009 12010 /** 12011 * @deprecated 12012 */ 12013 inValueSlider(name, v, min, max) 12014 { 12015 return this.inFloatSlider(name, v, min, max); 12016 } 12017 12018 /** 12019 * create a value slider input port 12020 * @param {String} name 12021 * @param {number} v 12022 * @param {number} min 12023 * @param {number} max 12024 * @return {Port} created port 12025 */ 12026 inFloatSlider(name, v, min, max) 12027 { 12028 const uiattribs = { "display": "range" }; 12029 12030 if (min != undefined && max != undefined) 12031 { 12032 uiattribs.min = min; 12033 uiattribs.max = max; 12034 } 12035 12036 const p = this.addInPort(new core_port.Port(this, name, core_port.Port.TYPE_VALUE, uiattribs)); 12037 if (v !== undefined) 12038 { 12039 p.set(v); 12040 p.defaultValue = v; 12041 } 12042 return p; 12043 } 12044 12045 /** 12046 * @deprecated 12047 */ 12048 outFunction(name, v) 12049 { 12050 return this.outTrigger(name, v); 12051 } 12052 12053 /** 12054 * create output trigger port 12055 * @param {String} name 12056 * @param {String} v 12057 * @return {Port} created port 12058 */ 12059 outTrigger(name, v) 12060 { 12061 // old 12062 const p = this.addOutPort(new core_port.Port(this, name, core_port.Port.TYPE_FUNCTION)); 12063 if (v !== undefined) p.set(v); 12064 return p; 12065 } 12066 12067 /** 12068 * @deprecated 12069 */ 12070 outValue(name, v) 12071 { 12072 return this.outNumber(name, v); 12073 } 12074 12075 /** 12076 * create output value port 12077 * @param {String} name 12078 * @param {number} v default value 12079 * @return {Port} created port 12080 */ 12081 outNumber(name, v) 12082 { 12083 const p = this.addOutPort(new core_port.Port(this, name, core_port.Port.TYPE_VALUE)); 12084 if (v !== undefined) p.set(v); 12085 return p; 12086 } 12087 12088 /** 12089 * @deprecated 12090 */ 12091 outValueBool(name, v) 12092 { 12093 return this.outBool(name, v); 12094 } 12095 12096 /** 12097 * deprecated create output boolean port 12098 * @deprecated 12099 * @param {String} name 12100 * @param {boolean} v default value 12101 * @return {Port} created port 12102 */ 12103 outBool(name, v) 12104 { 12105 // old: use outBoolNum 12106 const p = this.addOutPort( 12107 new core_port.Port(this, name, core_port.Port.TYPE_VALUE, { 12108 "display": "bool" 12109 }) 12110 ); 12111 if (v !== undefined) p.set(v); 12112 else p.set(0); 12113 return p; 12114 } 12115 12116 /** 12117 * create output boolean port,value will be converted to 0 or 1 12118 * @param {String} name 12119 * @return {Port} created port 12120 */ 12121 outBoolNum(name, v) 12122 { 12123 const p = this.addOutPort( 12124 new core_port.Port(this, name, core_port.Port.TYPE_VALUE, { 12125 "display": "boolnum" 12126 }) 12127 ); 12128 12129 p.set = function (b) 12130 { 12131 this.setValue(b ? 1 : 0); 12132 }.bind(p); 12133 12134 if (v !== undefined) p.set(v); 12135 else p.set(0); 12136 return p; 12137 } 12138 12139 /** 12140 * @deprecated 12141 * @param {string} name 12142 * @param {string} v 12143 */ 12144 outValueString(name, v) 12145 { 12146 const p = this.addOutPort( 12147 new core_port.Port(this, name, core_port.Port.TYPE_VALUE, { 12148 "type": "string" 12149 }) 12150 ); 12151 if (v !== undefined) p.set(v); 12152 return p; 12153 } 12154 12155 /** 12156 * create output string port 12157 * @param {string} name 12158 * @param {String} v 12159 * @return {Port} created port 12160 */ 12161 outString(name, v) 12162 { 12163 const p = this.addOutPort( 12164 new core_port.Port(this, name, core_port.Port.TYPE_STRING, { 12165 "type": "string" 12166 }) 12167 ); 12168 if (v !== undefined) p.set(v); 12169 else p.set(""); 12170 return p; 12171 } 12172 12173 /** 12174 * create output object port 12175 * @param {String} name 12176 * @return {Port} created port 12177 * @param {object} v 12178 * @param {string} objType 12179 */ 12180 outObject(name, v, objType) 12181 { 12182 const p = this.addOutPort(new core_port.Port(this, name, core_port.Port.TYPE_OBJECT, { "objType": objType || null })); 12183 p.set(v || null); 12184 p.ignoreValueSerialize = true; 12185 return p; 12186 } 12187 12188 /** 12189 * create output array port 12190 * @param {String} name 12191 * @return {Port} created port 12192 * @param {array|number} v 12193 * @param {number} stride 12194 */ 12195 outArray(name, v, stride) 12196 { 12197 if (!stride && CABLES.isNumeric(v))stride = v; 12198 const p = this.addOutPort(new core_port.Port(this, name, core_port.Port.TYPE_ARRAY, { "stride": stride })); 12199 if (v !== undefined && (Array.isArray(v) || v == null)) p.set(v); 12200 12201 p.ignoreValueSerialize = true; 12202 return p; 12203 } 12204 12205 /** 12206 * create output texture port 12207 * @param {String} name 12208 * @return {Port} created port 12209 * @param {any} v 12210 */ 12211 outTexture(name, v) 12212 { 12213 const p = this.addOutPort( 12214 new core_port.Port(this, name, core_port.Port.TYPE_OBJECT, { 12215 "preview": true, 12216 "objType": "texture", 12217 "display": "texture" 12218 }) 12219 ); 12220 if (v !== undefined) p.setRef(v || cgl.CGL.Texture.getEmptyTexture(this.patch.cgl)); 12221 12222 p.ignoreValueSerialize = true; 12223 return p; 12224 } 12225 12226 /** 12227 * @deprecated 12228 * @param {string} name 12229 * @param {any} filter 12230 * @param {any} options 12231 * @param {any} v 12232 */ 12233 inDynamic(name, filter, options, v) 12234 { 12235 const p = new core_port.Port(this, name, core_port.Port.TYPE_DYNAMIC, options); 12236 12237 p.shouldLink = (p1, p2) => 12238 { 12239 if (filter && CABLES.isArray(filter)) 12240 { 12241 // for (let i = 0; i < filter.length; i++) 12242 // { 12243 // if (p1 == this && p2.type === filter[i]) return true; 12244 // if (p2 == this && p1.type === filter[i]) return true; 12245 // } 12246 return false; // types do not match 12247 } 12248 return true; // no filter set 12249 }; 12250 12251 this.addInPort(p); 12252 if (v !== undefined) 12253 { 12254 p.set(v); 12255 p.defaultValue = v; 12256 } 12257 return p; 12258 } 12259 12260 removeLinks() 12261 { 12262 for (let i = 0; i < this.portsIn.length; i++) this.portsIn[i].removeLinks(); 12263 for (let i = 0; i < this.portsOut.length; i++) this.portsOut[i].removeLinks(); 12264 } 12265 12266 // @TODO should be move to extend... 12267 getSerialized() 12268 { 12269 const opObj = {}; 12270 12271 if (this.opId) opObj.opId = this.opId; 12272 if (this.patch.storeObjNames) opObj.objName = this.objName; 12273 12274 opObj.id = this.id; 12275 opObj.uiAttribs = JSON.parse(JSON.stringify(this.uiAttribs)) || {}; 12276 12277 if (this.storage && Object.keys(this.storage).length > 0) opObj.storage = JSON.parse(JSON.stringify(this.storage)); 12278 if (this.uiAttribs.hasOwnProperty("working") && this.uiAttribs.working == true) delete this.uiAttribs.working; 12279 if (opObj.uiAttribs.hasOwnProperty("uierrors")) delete opObj.uiAttribs.uierrors; 12280 if (opObj.uiAttribs.hasOwnProperty("highlighted")) delete opObj.uiAttribs.highlighted; 12281 if (opObj.uiAttribs.hasOwnProperty("highlightedMore")) delete opObj.uiAttribs.highlightedMore; 12282 12283 if (opObj.uiAttribs.title === "") delete opObj.uiAttribs.title; 12284 if (opObj.uiAttribs.color === null) delete opObj.uiAttribs.color; 12285 if (opObj.uiAttribs.comment === null) delete opObj.uiAttribs.comment; 12286 12287 if (opObj.uiAttribs.title == this.#shortOpName || 12288 (this.uiAttribs.title || "").toLowerCase() == this.#shortOpName.toLowerCase()) delete opObj.uiAttribs.title; 12289 12290 opObj.portsIn = []; 12291 opObj.portsOut = []; 12292 12293 for (let i = 0; i < this.portsIn.length; i++) 12294 { 12295 const s = this.portsIn[i].getSerialized(); 12296 if (s) opObj.portsIn.push(s); 12297 } 12298 12299 for (let i = 0; i < this.portsOut.length; i++) 12300 { 12301 const s = this.portsOut[i].getSerialized(); 12302 if (s) opObj.portsOut.push(s); 12303 } 12304 12305 if (opObj.portsIn.length == 0) delete opObj.portsIn; 12306 if (opObj.portsOut.length == 0) delete opObj.portsOut; 12307 (0,utils.cleanJson)(opObj); 12308 12309 return opObj; 12310 } 12311 12312 /** 12313 * @param {number} type 12314 */ 12315 getFirstOutPortByType(type) 12316 { 12317 for (let i = 0; i < this.portsOut.length; i++) 12318 if (this.portsOut[i].type == type) return this.portsOut[i]; 12319 } 12320 12321 /** 12322 * @param {number} type 12323 */ 12324 getFirstInPortByType(type) 12325 { 12326 for (let i = 0; i < this.portsIn.length; i++) 12327 if (this.portsIn[i].type == type) return this.portsIn[i]; 12328 } 12329 12330 /** 12331 * return port by the name portName 12332 * @param {String} name 12333 * @param {boolean} [lowerCase] 12334 * @return {Port} 12335 */ 12336 getPort(name, lowerCase = false) 12337 { 12338 return this.getPortByName(name, lowerCase); 12339 } 12340 12341 /** 12342 * @param {string} name 12343 * @param {boolean} [lowerCase] 12344 * @returns {Port} 12345 */ 12346 getPortByName(name, lowerCase = false) 12347 { 12348 if (lowerCase) 12349 { 12350 for (let ipi = 0; ipi < this.portsIn.length; ipi++) 12351 if (this.portsIn[ipi].getName().toLowerCase() == name || this.portsIn[ipi].id.toLowerCase() == name) 12352 return this.portsIn[ipi]; 12353 12354 for (let ipo = 0; ipo < this.portsOut.length; ipo++) 12355 if (this.portsOut[ipo].getName().toLowerCase() == name || this.portsOut[ipo].id.toLowerCase() == name) 12356 return this.portsOut[ipo]; 12357 } 12358 else 12359 { 12360 for (let ipi = 0; ipi < this.portsIn.length; ipi++) 12361 if (this.portsIn[ipi].getName() == name || this.portsIn[ipi].id == name) 12362 return this.portsIn[ipi]; 12363 12364 for (let ipo = 0; ipo < this.portsOut.length; ipo++) 12365 if (this.portsOut[ipo].getName() == name || this.portsOut[ipo].id == name) 12366 return this.portsOut[ipo]; 12367 } 12368 } 12369 12370 /** 12371 * return port by the name id 12372 * @param {String} id 12373 * @return {Port} 12374 */ 12375 getPortById(id) 12376 { 12377 for (let ipi = 0; ipi < this.portsIn.length; ipi++) if (this.portsIn[ipi].id == id) return this.portsIn[ipi]; 12378 for (let ipo = 0; ipo < this.portsOut.length; ipo++) if (this.portsOut[ipo].id == id) return this.portsOut[ipo]; 12379 } 12380 12381 updateAnims() 12382 { 12383 if (this.hasAnimPort) 12384 for (let i = 0; i < this.portsIn.length; i++) this.portsIn[i].updateAnim(); 12385 } 12386 12387 log() 12388 { 12389 this._log.log(...arguments); 12390 } 12391 12392 /** 12393 * @deprecated 12394 */ 12395 error() 12396 { 12397 this._log.error(...arguments); 12398 } 12399 12400 logError() 12401 { 12402 this._log.error(...arguments); 12403 } 12404 12405 /** 12406 * @deprecated 12407 */ 12408 warn() 12409 { 12410 this._log.warn(...arguments); 12411 } 12412 12413 logWarn() 12414 { 12415 this._log.warn(...arguments); 12416 } 12417 12418 /** 12419 * @deprecated 12420 */ 12421 verbose() 12422 { 12423 this._log.verbose(...arguments); 12424 } 12425 12426 logVerbose() 12427 { 12428 this._log.verbose(...arguments); 12429 } 12430 12431 profile() 12432 { 12433 for (let ipi = 0; ipi < this.portsIn.length; ipi++) 12434 { 12435 this.portsIn[ipi]._onTriggered = this.portsIn[ipi]._onTriggeredProfiling; 12436 this.portsIn[ipi].set = this.portsIn[ipi]._onSetProfiling; 12437 } 12438 } 12439 12440 // todo: check instancing stuff? 12441 cleanUp() 12442 { 12443 if (this._instances) 12444 { 12445 for (let i = 0; i < this._instances.length; i++) 12446 if (this._instances[i].onDelete) this._instances[i].onDelete(); 12447 12448 this._instances.length = 0; 12449 } 12450 12451 for (let i = 0; i < this.portsIn.length; i++) 12452 this.portsIn[i].setAnimated(false); 12453
12454 if (this.onAnimFrame) this.patch.removeOnAnimFrame(this); 12455 } 12456 12457 // todo: check instancing stuff? 12458 instanced(triggerPort) 12459 { 12460 return false; 12461 12462 /* 12463 * this._log.log("instanced", this.patch.instancing.numCycles()); 12464 * if (this.patch.instancing.numCycles() === 0) return false; 12465 */ 12466 12467 /* 12468 * let i = 0; 12469 * let ipi = 0; 12470 * if (!this._instances || this._instances.length != this.patch.instancing.numCycles()) 12471 * { 12472 * if (!this._instances) this._instances = []; 12473 * this._.log("creating instances of ", this.objName, this.patch.instancing.numCycles(), this._instances.length); 12474 * this._instances.length = this.patch.instancing.numCycles(); 12475 */ 12476 12477 /* 12478 * for (i = 0; i < this._instances.length; i++) 12479 * { 12480 * this._instances[i] = this.patch.createOp(this.objName, true); 12481 * this._instances[i].instanced () 12482 * { 12483 * return false; 12484 * }; 12485 * this._instances[i].uiAttr(this.uiAttribs); 12486 */ 12487 12488 /* 12489 * for (let ipo = 0; ipo < this.portsOut.length; ipo++) 12490 * { 12491 * if (this.portsOut[ipo].type == Port.TYPE_FUNCTION) 12492 * { 12493 * this._instances[i].getPortByName(this.portsOut[ipo].name).trigger = this.portsOut[ipo].trigger.bind(this.portsOut[ipo]); 12494 * } 12495 * } 12496 * } 12497 */ 12498 12499 /* 12500 * for (ipi = 0; ipi < this.portsIn.length; ipi++) 12501 * { 12502 * this.portsIn[ipi].onChange = null; 12503 * this.portsIn[ipi].onValueChanged = null; 12504 * } 12505 * } 12506 */ 12507 12508 /* 12509 * const theTriggerPort = null; 12510 * for (ipi = 0; ipi < this.portsIn.length; ipi++) 12511 * { 12512 * if ( 12513 * this.portsIn[ipi].type == Port.TYPE_VALUE || 12514 * this.portsIn[ipi].type == Port.TYPE_ARRAY 12515 * ) 12516 * { 12517 * this._instances[this.patch.instancing.index()].portsIn[ipi].set(this.portsIn[ipi].get()); 12518 * } 12519 * if (this.portsIn[ipi].type == Port.TYPE_FUNCTION) 12520 * { 12521 * // if(this._instances[ this.patch.instancing.index() ].portsIn[ipi].name==triggerPort.name) 12522 * // theTriggerPort=this._instances[ this.patch.instancing.index() ].portsIn[ipi]; 12523 * } 12524 * } 12525 */ 12526 12527 // if (theTriggerPort) theTriggerPort.onTriggered(); 12528 12529 /* 12530 * for (ipi = 0; ipi < this.portsOut.length; ipi++) 12531 * { 12532 * if (this.portsOut[ipi].type == Port.TYPE_VALUE) 12533 * { 12534 * this.portsOut[ipi].set(this._instances[this.patch.instancing.index()].portsOut[ipi].get()); 12535 * } 12536 * } 12537 */ 12538 12539 // return true; 12540 } 12541 12542 // todo: check instancing stuff? 12543 initInstancable() 12544 { 12545 // if(this.isInstanced) 12546 // { 12547 // this._log.log('cancel instancing'); 12548 // return; 12549 // } 12550 // this._instances=[]; 12551 // for(var ipi=0;ipi<this.portsIn.length;ipi++) 12552 // { 12553 // if(this.portsIn[ipi].type==Port.TYPE_VALUE) 12554 // { 12555 // 12556 // } 12557 // if(this.portsIn[ipi].type==Port.TYPE_FUNCTION) 12558 // { 12559 // // var piIndex=ipi; 12560 // this.portsIn[ipi].onTriggered=function(piIndex) 12561 // { 12562 // 12563 // var i=0; 12564 // // this._log.log('trigger',this._instances.length); 12565 // 12566 // }.bind(this,ipi ); 12567 // 12568 // } 12569 // }; 12570 // this._instances=null; 12571 } 12572 12573 // setValues(obj) 12574 // { 12575 // for (const i in obj) 12576 // { 12577 // const port = this.getPortByName(i); 12578 // if (port) port.set(obj[i]); 12579 // else this._log.warn("op.setValues: port not found:", i); 12580 // } 12581 // } 12582 12583 /** 12584 * return true if op has this error message id 12585 * @param {String} id 12586 * @returns {Boolean}
12586 - has id 12587 */ 12588 hasUiError(id) 12589 { 12590 return this.uiErrors.hasOwnProperty(id) && this.uiErrors[id]; 12591 } 12592 12593 /** 12594 * show op error message - set message to null to remove error message 12595 * @param {string} id error id 12596 * @param {string} txt text message 12597 * @param {number} level level 12598 */ 12599 setUiError(id, txt, level = 2, options = {}) 12600 { 12601 // overwritten in ui: core_extend_op 12602 } 12603 12604 /** 12605 * enable/disable op 12606 * @function 12607 * @param {boolean} b 12608 */ 12609 setEnabled(b) 12610 { 12611 this.enabled = b; 12612 this.emitEvent("onEnabledChange", b); 12613 } 12614 12615 /** 12616 * organize ports into a group 12617 * @function 12618 * @param {String} name 12619 * @param {Array} ports 12620 */ 12621 setPortGroup(name, ports) 12622 { 12623 for (let i = 0; i < ports.length; i++) 12624 { 12625 if (ports[i]) 12626 if (ports[i].setUiAttribs) ports[i].setUiAttribs({ "group": name }); 12627 else this._log.error("setPortGroup: invalid port!"); 12628 } 12629 } 12630 12631 /** 12632 * visually indicate ports that they are coordinate inputs 12633 * @function 12634 * @param {Port} px 12635 * @param {Port} py 12636 * @param {Port} pz 12637 */ 12638 setUiAxisPorts(px, py, pz) 12639 { 12640 if (px) px.setUiAttribs({ "axis": "X" }); 12641 if (py) py.setUiAttribs({ "axis": "Y" }); 12642 if (pz) pz.setUiAttribs({ "axis": "Z" }); 12643 } 12644 12645 /** 12646 * remove port from op 12647 * @param {Port} port to remove 12648 */ 12649 removePort(port) 12650 { 12651 for (let ipi = 0; ipi < this.portsIn.length; ipi++) 12652 { 12653 if (this.portsIn[ipi] == port) 12654 { 12655 this.portsIn.splice(ipi, 1); 12656 this.emitEvent(Op.EVENT_UIATTR_CHANGE, {}); 12657 this.emitEvent("onPortRemoved", {}); 12658 return; 12659 } 12660 } 12661 for (let ipi = 0; ipi < this.portsOut.length; ipi++) 12662 { 12663 if (this.portsOut[ipi] == port) 12664 { 12665 this.portsOut.splice(ipi, 1); 12666 this.emitEvent(Op.EVENT_UIATTR_CHANGE, {}); 12667 this.emitEvent("onPortRemoved", {}); 12668 return; 12669 } 12670 } 12671 } 12672 12673 /** 12674 * show a warning of this op is not a child of parentOpName 12675 * @function 12676 * @param {String} parentOpName 12677 */ 12678 toWorkNeedsParent(parentOpName) 12679 { 12680 this.linkTimeRules.needsParentOp = parentOpName; 12681 } 12682 12683 /** 12684 * show a warning of this op is a child of parentOpName 12685 * @function 12686 * @instance 12687 * @memberof Op 12688 * @param {String} parentOpName 12689 * @param {number} type 12690 */ 12691 toWorkShouldNotBeChild(parentOpName, type) 12692 { 12693 if (!this.patch.isEditorMode()) return; 12694 this.linkTimeRules.forbiddenParent = parentOpName; 12695 if (type != undefined) this.linkTimeRules.forbiddenParentType = type; 12696 } 12697 12698 toWorkPortsNeedsString() 12699 { 12700 if (!this.patch.isEditorMode()) return; 12701 for (let i = 0; i < arguments.length; i++) 12702 if (this.linkTimeRules.needsStringToWork.indexOf(arguments[i]) == -1) this.linkTimeRules.needsStringToWork.push(arguments[i]); 12703 } 12704 12705 /** 12706 * show a small X to indicate op is not working when given ports are not linked 12707 * @function 12708 * @instance 12709 * @memberof Op 12710 * @param {Array<Port>} port 12711 */ 12712 toWorkPortsNeedToBeLinked() 12713 { 12714 if (!this.patch.isEditorMode()) return; 12715 for (let i = 0; i < arguments.length; i++) 12716 if (this.linkTimeRules.needsLinkedToWork.indexOf(arguments[i]) == -1) this.linkTimeRules.needsLinkedToWork.push(arguments[i]); 12717 } 12718 12719 toWorkPortsNeedToBeLinkedReset() 12720 { 12721 if (!this.patch.isEditorMode()) return; 12722 this.linkTimeRules.needsLinkedToWork.length = 0; 12723 if (this.checkLinkTimeWarnings) this.checkLinkTimeWarnings(); 12724 } 12725 12726 initVarPorts() 12727 { 12728 for (let i = 0; i < this.portsIn.length; i++) 12729 if (this.portsIn[i].getVariableName()) this.portsIn[i].setVariable(this.portsIn[i].getVariableName()); 12730 } 12731 12732 checkLinkTimeWarnings() {} 12733 _checkLinksNeededToWork() { } 12734 12735 /** 12736 * refresh op parameters, if current op is selected 12737 * @function 12738 * @instance 12739 * @memberof Op 12740 */ 12741 refreshParams() 12742 { 12743 if (this.patch && this.patch.isEditorMode() && this.isCurrentUiOp()) gui.opParams.show(this); 12744 } 12745 12746 /** 12747 * Returns true if op is selected and parameter are shown in the editor, can only return true if in editor/ui 12748 * @instance 12749 * @memberof Op 12750 * @returns {Boolean} - is current ui op 12751 */ 12752 isCurrentUiOp() 12753 { 12754 if (this.patch.isEditorMode()) return gui.patchView.isCurrentOp(this); 12755 } 12756 12757 checkGraphicsApi(api = cgl_state.CglContext.API_WEBGL) 12758 { 12759 if (this.patch.isEditorMode()) 12760 if (this.patch.cg && this.patch.cg.gApi != api) 12761 this.setUiError("wronggapi", "Wrong graphics API", 2); 12762 } 12763} 12764 12765;// CONCATENATED MODULE: ./src/core/loadingstatus.js 12766 12767 12768 12769 12770 12771/** 12772 * LoadingStatus class, manages asynchronous loading jobs 12773 * 12774 * @namespace external:CABLES#LoadingStatus 12775 * @hideconstructor 12776 * @class 12777 * @param patch 12778 */ 12779 12780class LoadingStatus extends eventtarget["default"] 12781{ 12782 12783 /** 12784 * @param {Patch} patch 12785 */ 12786 constructor(patch) 12787 { 12788 super(); 12789 this._log = new logger["default"]("LoadingStatus"); 12790 this._loadingAssets = {}; 12791 this._cbFinished = []; 12792 this._assetTasks = []; 12793 this._percent = 0; 12794 this._count = 0; 12795 this._countFinished = 0; 12796 this._order = 0; 12797 this._startTime = 0; 12798 this._patch = patch; 12799 this._wasFinishedPrinted = false;
12800 this._loadingAssetTaskCb = false; 12801 } 12802 12803 /** 12804 * @param {Function} cb 12805 */ 12806 setOnFinishedLoading(cb) 12807 { 12808 this._cbFinished.push(cb); 12809 } 12810 12811 getNumAssets() 12812 { 12813 return this._countFinished; 12814 } 12815 12816 getProgress() 12817 { 12818 return this._percent; 12819 } 12820 12821 checkStatus() 12822 { 12823 this._countFinished = 0; 12824 this._count = 0; 12825 12826 for (const i in this._loadingAssets) 12827 { 12828 this._count++; 12829 if (!this._loadingAssets[i].finished) 12830 { 12831 this._countFinished++; 12832 } 12833 } 12834 12835 this._percent = (this._count - this._countFinished) / this._count; 12836 12837 if (this._countFinished === 0) 12838 { 12839 for (let j = 0; j < this._cbFinished.length; j++) 12840 { 12841 if (this._cbFinished[j]) 12842 { 12843 const cb = this._cbFinished[j]; 12844 setTimeout(() => { cb(this._patch); this.emitEvent("finishedAll"); }, 100); 12845 } 12846 } 12847 12848 if (!this._wasFinishedPrinted) 12849 { 12850 this._wasFinishedPrinted = true; 12851 this.print(); 12852 } 12853 this.emitEvent("finishedAll"); 12854 } 12855 } 12856 12857 getList() 12858 { 12859 let arr = []; 12860 for (const i in this._loadingAssets) 12861 { 12862 arr.push(this._loadingAssets[i]); 12863 } 12864 12865 return arr; 12866 } 12867 12868 getListJobs() 12869 { 12870 let arr = []; 12871 for (const i in this._loadingAssets) 12872 { 12873 if (!this._loadingAssets[i].finished)arr.push(this._loadingAssets[i].name); 12874 } 12875 12876 return arr; 12877 } 12878 12879 print() 12880 { 12881 if (this._patch.config.silent) return; 12882 12883 const rows = []; 12884 12885 for (const i in this._loadingAssets) 12886 { 12887 rows.push([ 12888 this._loadingAssets[i].order, 12889 this._loadingAssets[i].type, 12890 this._loadingAssets[i].name, 12891 (this._loadingAssets[i].timeEnd - this._loadingAssets[i].timeStart) / 1000 + "s", 12892 ]); 12893 } 12894 12895 this._log.groupCollapsed("finished loading " + this._order + " assets in " + (Date.now() - this._startTime) / 1000 + "s"); 12896 this._log.table(rows); 12897 this._log.groupEnd(); 12898 } 12899 12900 /** 12901 * @param {string} id 12902 */ 12903 finished(id) 12904 { 12905 const l = this._loadingAssets[id]; 12906 if (l) 12907 { 12908 if (l.finished) this._log.warn("loading job was already finished", l); 12909 12910 if (l.op) l.op.setUiAttribs({ "loading": false }); 12911 l.finished = true; 12912 l.timeEnd = Date.now(); 12913 } 12914 12915 this.checkStatus(); 12916 this.emitEvent("finishedTask"); 12917 return null; 12918 } 12919 12920 _startAssetTasks() 12921 { 12922 for (let i = 0; i < this._assetTasks.length; i++) this._assetTasks[i](); 12923 this._assetTasks.length = 0; 12924 } 12925 12926 /** 12927 * delay an asset loading task, mainly to wait for ui to be finished loading and showing, and only then start loading assets 12928 * @function addAssetLoadingTask 12929 * @instance 12930 * @memberof LoadingStatus 12931 * @param {function} cb callback 12932 */ 12933 addAssetLoadingTask(cb) 12934 { 12935 if (this._patch.isEditorMode() && !CABLES.UI.loaded) 12936 { 12937 this._assetTasks.push(cb); 12938 12939 if (!this._loadingAssetTaskCb)window.gui.addEventListener("uiloaded", this._startAssetTasks.bind(this)); 12940 this._loadingAssetTaskCb = true; 12941 } 12942 else 12943 { 12944 cb(); 12945 } 12946 this.emitEvent("addAssetTask"); 12947 } 12948 12949 /** 12950 * @param {string} name 12951 */ 12952 existByName(name) 12953 { 12954 for (let i in this._loadingAssets) 12955 { 12956 if (this._loadingAssets[i].name == name && !this._loadingAssets[i].finished) 12957 return true; 12958 } 12959 } 12960 12961 /** 12962 * @param {string} type 12963 * @param {string} name 12964 * @param {Op} [op] 12965 */ 12966 start(type, name, op) 12967 { 12968 if (this._startTime == 0) this._startTime = Date.now(); 12969 const id = (0,utils.generateUUID)(); 12970 12971 name = name || "unknown"; 12972 if (name.length > 100)name = name.substring(0, 100); 12973 12974 if (op)op.setUiAttrib({ "loading": true }); 12975 12976 this._loadingAssets[id] = { 12977 "id": id, 12978 "op": op, 12979 "type": type, 12980 "name": name, 12981 "finished": false, 12982 "timeStart": Date.now(), 12983 "order": this._order, 12984 }; 12985 this._order++; 12986 12987 this.emitEvent("startTask"); 12988 12989 return id; 12990 } 12991} 12992 12993// EXTERNAL MODULE: ./src/core/timer.js 12994var timer = __webpack_require__("./src/core/timer.js"); 12995;// CONCATENATED MODULE: ./src/core/core_profiler.js 12996 12997 12998 12999class Profiler 13000{ 13001 13002 /** 13003 * @param {Patch} patch 13004 */ 13005 constructor(patch) 13006 { 13007 this.startFrame = patch.getFrameNum(); 13008 this.items = {}; 13009 this.currentId = null; 13010 this.currentStart = 0; 13011 this._patch = patch; 13012 } 13013 13014 getItems() 13015 { 13016 return this.items; 13017 } 13018 13019 clear() 13020 { 13021 if (this.paused) return; 13022 this.items = {}; 13023 } 13024 13025 togglePause() 13026 { 13027 this.paused = !this.paused; 13028 if (!this.paused) 13029 { 13030 this.items = {}; 13031 this.currentStart = performance.now(); 13032 } 13033 } 13034 13035 add(type, object) 13036 { 13037 if (this.paused) return; 13038 13039 if (this.currentId !== null) 13040 { 13041 if (!object || object.id != this.currentId) 13042 { 13043 if (this.items[this.currentId]) 13044 { 13045 this.items[this.currentId].timeUsed += performance.now() - this.currentStart; 13046 13047 if (!this.items[this.currentId].peakTime || (0,timer.now)() - this.items[this.currentId].peakTime > 5000) 13048 { 13049 this.items[this.currentId].peak = 0; 13050 this.items[this.currentId].peakTime = (0,timer.now)(); 13051 } 13052 this.items[this.currentId].peak = Math.max(this.items[this.currentId].peak, performance.now() - this.currentStart); 13053 } 13054 } 13055 } 13056 13057 if (object !== null) 13058 { 13059 if (!this.items[object.id]) 13060 { 13061 this.items[object.id] = { 13062 "numTriggers": 0, 13063 "timeUsed": 0, 13064 }; 13065 } 13066 13067 if (this.items[object.id].lastFrame != this._patch.getFrameNum()) this.items[object.id].numTriggers = 0; 13068 13069 this.items[object.id].lastFrame = this._patch.getFrameNum(); 13070 this.items[object.id].numTriggers++; 13071 this.items[object.id].opid = object.op.id; 13072 this.items[object.id].title = object.op.name + "." + object.name; 13073 this.items[object.id].subPatch = object.op.uiAttribs.subPatch; 13074 13075 this.currentId = object.id; 13076 this.currentStart = performance.now(); 13077 } 13078 else 13079 { 13080 this.currentId = null; 13081 } 13082 } 13083 13084 print() 13085 { 13086 console.log("--------"); 13087 for (const i in this.items) 13088 { 13089 console.log(this.items[i].title + ": " + this.items[i].numTriggers + " / " + this.items[i].timeUsed); 13090 } 13091 } 13092} 13093 13094;// CONCATENATED MODULE: ./src/core/core_variable.js 13095 13096 13097class PatchVariable extends eventtarget["default"] 13098{ 13099 13100 /** 13101 * @param {String} name 13102 * @param {String|Number} val 13103 * @param {number} type 13104 */ 13105 constructor(name, val, type) 13106 { 13107 super(); 13108 this._name = name; 13109 this.type = type; 13110 this.setValue(val); 13111 } 13112 13113 /** 13114 * keeping this for backwards compatibility in older 13115 * exports before using eventtarget 13116 * 13117 * @param cb 13118 */ 13119 addListener(cb) 13120 { 13121 this.on("change", cb, "var"); 13122 } 13123 13124 /** 13125 * @function Variable.getValue 13126 * @memberof PatchVariable 13127 * @returns {String|Number|Boolean} 13128 */ 13129 getValue() 13130 { 13131 return this._v; 13132 } 13133 13134 /** 13135 * @function getName 13136 * @memberof PatchVariable 13137 * @instance 13138 * @returns {String|Number|Boolean} 13139 * @function 13140 */ 13141 getName() 13142 { 13143 return this._name; 13144 } 13145 13146 /** 13147 * @function setValue 13148 * @memberof PatchVariable 13149 * @instance 13150 * @param v 13151 * @returns {any} 13152 * @function 13153 */ 13154 setValue(v) 13155 { 13156 this._v = v; 13157 this.emitEvent("change", v, this); 13158 } 13159} 13160 13161;// CONCATENATED MODULE: ./src/core/core_patch.js 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173/** @global CABLES.OPS */ 13174 13175/** 13176 * @typedef {import("./core_op.js").OpUiAttribs} OpUiAttribs 13177 */ 13178
13179/** 13180 * @typedef PatchConfig 13181 * @property {String} [prefixAssetPath=''] prefix for path to assets 13182 * @property {String} [assetPath=''] path to assets 13183 * @property {String} [jsPath=''] path to javascript files 13184 * @property {String} [glCanvasId='glcanvas'] dom element id of canvas element 13185 * @property {Function} [onError=null] called when an error occurs 13186 * @property {Function} [onFinishedLoading=null] called when patch finished loading all assets 13187 * @property {Function} [onFirstFrameRendered=null] called when patch rendered it's first frame 13188 * @property {Boolean} [glCanvasResizeToWindow=false] resize canvas automatically to window size 13189 * @property {Boolean} [glCanvasResizeToParent] resize canvas automatically to parent element 13190 * @property {Boolean} [doRequestAnimation=true] do requestAnimationFrame set to false if you want to trigger exec() from outside (only do if you know what you are doing) 13191 * @property {Boolean} [clearCanvasColor=true] clear canvas in transparent color every frame 13192 * @property {Boolean} [clearCanvasDepth=true] clear depth every frame 13193 * @property {Boolean} [glValidateShader=true] enable/disable validation of shaders * 13194 * @property {Boolean} [silent=false] 13195 * @property {Number} [fpsLimit=0] 0 for maximum possible frames per second 13196 * @property {String} [glslPrecision='mediump'] default precision for glsl shader 13197 * @property {String} [prefixJsPath] 13198 * @property {Function} [onPatchLoaded] 13199 * @property {Object} [canvas] 13200 * @property {Object} [patch] 13201 * @property {String} [patchFile] 13202 * @property {String} [subPatch] internal use 13203 * @property {Number} [masterVolume] 0 for maximum possible frames per second 13204 * @property {HTMLCanvasElement} [glCanvas] 13205 * @property {HTMLElement} [containerElement] 13206*/ 13207 13208/** 13209 * @typedef CoreOp 13210 * @type Op 13211 */ 13212 13213/** 13214 * @template {CoreOp} Op 13215 * 13216 * Patch class, contains all operators,values,links etc. manages loading and running of the whole patch 13217 * 13218 * see {@link PatchConfig} 13219 * 13220 * @example 13221 * CABLES.patch=new CABLES.Patch( 13222 * { 13223 * patch:pStr, 13224 * glCanvasId:'glcanvas', 13225 * glCanvasResizeToWindow:true, 13226 * canvas:{powerPreference:"high-performance"}, 13227 * prefixAssetPath:'/assets/', 13228 * prefixJsPath:'/js/', 13229 * onError:function(e){console.log(e);} 13230 * glslPrecision:'highp' 13231 * }); 13232 */ 13233class Patch extends eventtarget["default"] 13234{ 13235 static EVENT_OP_DELETED = "onOpDelete"; 13236 static EVENT_OP_ADDED = "onOpAdd"; 13237 static EVENT_PAUSE = "pause"; 13238 static EVENT_RESUME = "resume"; 13239 static EVENT_PATCHLOADEND = "patchLoadEnd"; 13240 static EVENT_VARIABLES_CHANGED = "variablesChanged"; 13241 static EVENT_RENDER_FRAME = "onRenderFrame"; 13242 static EVENT_RENDERED_ONE_FRAME = "renderedOneFrame"; 13243 static EVENT_LINK = "onLink"; 13244 static EVENT_VALUESSET = "loadedValueSet"; 13245 static EVENT_ANIM_MAXTIME_CHANGE = "animmaxtimechange"; 13246 13247 #renderOneFrame = false; 13248 #initialDeserialize = true; 13249 13250 /** @type {Array<Op>} */ 13251 ops = []; 13252 settings = {}; 13253 animMaxTime = 0; 13254 13255 /** @param {PatchConfig} cfg */ 13256 constructor(cfg) 13257 { 13258 super(); 13259 13260 this._log = new logger["default"]("core_patch", { "onError": cfg.onError }); 13261 13262 /** @type {PatchConfig} */ 13263 this.config = cfg || 13264 { 13265 "glCanvasResizeToWindow": false, 13266 "prefixAssetPath": "", 13267 "prefixJsPath": "", 13268 "silent": true, 13269 "onError": null, 13270 "onFinishedLoading": null, 13271 "onFirstFrameRendered": null, 13272 "onPatchLoaded": null, 13273 "fpsLimit": 0, 13274 13275 }; 13276 13277 this.timer = new timer.Timer(); 13278 this.freeTimer = new timer.Timer(); 13279 this.animFrameOps = []; 13280 this.animFrameCallbacks = []; 13281 this.gui = false; 13282 CABLES.logSilent = this.silent = true; 13283 this.profiler = null; 13284 this.aborted = false; 13285 this._crashedOps = []; 13286 13287 this._animReq = null; 13288 this._opIdCache = {}; 13289 this._triggerStack = []; 13290 this.storeObjNames = false; // remove after may release 13291 13292 /** @type {LoadingStatus} */ 13293 this.loading = new LoadingStatus(this); 13294 13295 this._volumeListeners = []; 13296 this._paused = false;
13297 this._frameNum = 0; 13298 this.onOneFrameRendered = null; 13299 this.namedTriggers = {}; 13300 13301 this._origData = null; 13302 this._frameNext = 0; 13303 this._frameInterval = 0; 13304 this._lastFrameTime = 0; 13305 this._frameWasdelayed = true; 13306 this.tempData = this.frameStore = {}; 13307 this.reqAnimTimeStamp = 0; 13308 13309 this.cgCanvas = null; 13310 13311 if (!(function () { return !this; }())) console.log("not in strict mode: core patch"); 13312 13313 if (this.config.hasOwnProperty("silent")) this.silent = CABLES.logSilent = this.config.silent; 13314 if (!this.config.hasOwnProperty("doRequestAnimation")) this.config.doRequestAnimation = true; 13315 13316 if (!this.config.prefixAssetPath) this.config.prefixAssetPath = ""; 13317 if (!this.config.prefixJsPath) this.config.prefixJsPath = ""; 13318 if (!this.config.masterVolume) this.config.masterVolume = 1.0; 13319 13320 this._variables = {}; 13321 13322 this.vars = {}; 13323 if (cfg && cfg.vars) this.vars = cfg.vars; // vars is old! 13324 13325 this.cgl = new cgl.CGL.Context(this); 13326 this.cgp = null; 13327 13328 this._subpatchOpCache = {}; 13329 13330 this.cgl.setCanvas(this.config.glCanvasId || this.config.glCanvas || "glcanvas"); 13331 if (this.config.glCanvasResizeToWindow === true) this.cgl.setAutoResize("window"); 13332 if (this.config.glCanvasResizeToParent === true) this.cgl.setAutoResize("parent"); 13333 this.loading.setOnFinishedLoading(this.config.onFinishedLoading); 13334 13335 if (this.cgl.aborted) this.aborted = true; 13336 if (this.cgl.silent) this.silent = true; 13337 13338 if (!CABLES.OPS) 13339 { 13340 this.aborted = true; 13341 throw new Error("no CABLES.OPS found"); 13342 } 13343 this.freeTimer.play(); 13344 this.exec(); 13345 13346 if (!this.aborted) 13347 { 13348 if (this.config.patch) 13349 { 13350 this.deSerialize(this.config.patch); 13351 } 13352 else if (this.config.patchFile) 13353 { 13354 (0,utils.ajax)( 13355 this.config.patchFile, 13356 (err, _data) => 13357 { 13358 try 13359 { 13360 const data = JSON.parse(_data); 13361 if (err) 13362 { 13363 const txt = ""; 13364 this._log.error("err", err); 13365 this._log.error("data", data); 13366 this._log.error("data", data.msg); 13367 return; 13368 } 13369 this.deSerialize(data); 13370 } 13371 catch (e) 13372 { 13373 this._log.error("could not load/parse patch ", e); 13374 } 13375 } 13376 ); 13377 } 13378 this.timer.play(); 13379 } 13380 13381 console.log("made with https://cables.gl"); // eslint-disable-line 13382 this.cg = undefined; 13383 13384 } 13385 13386 isPlaying() 13387 { 13388 return !this._paused; 13389 } 13390 13391 /** @deprecated */ 13392 renderOneFrame() 13393 { 13394 this._paused = true; 13395 this._renderOneFrame = true; 13396 this.exec(); 13397 this._renderOneFrame = false; 13398 } 13399 13400 /** 13401 * returns true if patch is opened in editor/gui mode 13402 * @function isEditorMode 13403 * @memberof Patch 13404 * @instance 13405 * @return {Boolean} editor mode 13406 */ 13407 isEditorMode() 13408 { 13409 return this.config.editorMode === true; 13410 } 13411 13412 /** 13413 * pauses patch execution 13414 * @function pause 13415 * @memberof Patch 13416 * @instance 13417 */ 13418 pause() 13419 { 13420 cancelAnimationFrame(this._animReq); 13421 this.emitEvent(Patch.EVENT_PAUSE); 13422 this._animReq = null; 13423 this._paused = true; 13424 this.freeTimer.pause(); 13425 } 13426 13427 /** 13428 * resumes patch execution 13429 * @function resume 13430 * @memberof Patch 13431 * @instance 13432 */ 13433 resume() 13434 { 13435 if (this._paused) 13436 { 13437 cancelAnimationFrame(this._animReq); 13438 this._paused = false;
13439 this.freeTimer.play(); 13440 this.emitEvent(Patch.EVENT_RESUME); 13441 this.exec(); 13442 } 13443 } 13444 13445 /** 13446 * set volume [0-1] 13447 * @function setVolume 13448 * @param {Number} v volume 13449 * @memberof Patch 13450 * @instance 13451 */ 13452 setVolume(v) 13453 { 13454 this.config.masterVolume = v; 13455 for (let i = 0; i < this._volumeListeners.length; i++) this._volumeListeners[i].onMasterVolumeChanged(v); 13456 } 13457 13458 /** 13459 * get asset path 13460 * @function getAssetPath 13461 * @memberof Patch 13462 * @param patchId 13463 * @instance 13464 */ 13465 getAssetPath(patchId = null) 13466 { 13467 if (this.config.hasOwnProperty("assetPath")) 13468 { 13469 return this.config.assetPath; 13470 } 13471 else if (this.isEditorMode()) 13472 { 13473 let id = patchId || gui.project()._id; 13474 return "/assets/" + id + "/"; 13475 } 13476 else if (document.location.href.indexOf("cables.gl") > 0 || document.location.href.indexOf("cables.local") > 0) 13477 { 13478 const parts = document.location.pathname.split("/"); 13479 let id = patchId || parts[parts.length - 1]; 13480 return "/assets/" + id + "/"; 13481 } 13482 else 13483 { 13484 return "assets/"; 13485 } 13486 } 13487 13488 /** 13489 * get js path 13490 * @function getJsPath 13491 * @memberof Patch 13492 * @instance 13493 */ 13494 getJsPath() 13495 { 13496 if (this.config.hasOwnProperty("jsPath")) 13497 { 13498 return this.config.jsPath; 13499 } 13500 else 13501 { 13502 return "js/"; 13503 } 13504 } 13505 13506 /** 13507 * get url/filepath for a filename 13508 * this uses prefixAssetpath in exported patches 13509 * @function getFilePath 13510 * @memberof Patch 13511 * @instance 13512 * @param {String} filename 13513 * @return {String} url 13514 */ 13515 getFilePath(filename) 13516 { 13517 if (!filename) return filename; 13518 filename = String(filename); 13519 if (filename.indexOf("https:") === 0 || filename.indexOf("http:") === 0) return filename; 13520 if (filename.indexOf("data:") === 0) return filename; 13521 if (filename.indexOf("file:") === 0) return filename; 13522 filename = filename.replace("//", "/"); 13523 if (filename.startsWith(this.config.prefixAssetPath)) filename = filename.replace(this.config.prefixAssetPath, ""); 13524 return this.config.prefixAssetPath + filename + (this.config.suffixAssetPath || ""); // 13525 } 13526 13527 clear() 13528 { 13529 this.emitEvent("patchClearStart"); 13530 this.cgl.TextureEffectMesh = null; 13531 this.animFrameOps.length = 0; 13532 this.timer = new timer.Timer(); 13533 while (this.ops.length > 0) this.deleteOp(this.ops[0].id); 13534 13535 this._opIdCache = {}; 13536 this.emitEvent("patchClearEnd"); 13537 } 13538 13539 /** 13540 * @param {string} identifier 13541 * @param {string} id 13542 * @param {string} [opName] 13543 * @returns {Op} 13544 */ 13545 createOp(identifier, id, opName = null) 13546 { 13547 13548 /** 13549 * @type {Op} 13550 */ 13551 let op = null; 13552 let objName = ""; 13553 13554 try 13555 { 13556 if (!identifier) 13557 { 13558 console.error("createop identifier false", identifier); 13559 console.log((new Error()).stack); 13560 return; 13561 } 13562 if (identifier.indexOf("Ops.") === -1) 13563 { 13564 13565 /* 13566 * this should be a uuid, not a namespace 13567 * creating ops by id should be the default way from now on! 13568 */ 13569 const opId = identifier; 13570 13571 if (CABLES.OPS[opId]) 13572 { 13573 objName = CABLES.OPS[opId].objName; 13574 op = new CABLES.OPS[opId].f(this, objName, id, opId); 13575 op.opId = opId; 13576 } 13577 else 13578 { 13579 if (opName) 13580 { 13581 identifier = opName; 13582 this._log.warn("could not find op by id: " + opId); 13583 } 13584 else 13585 { 13586 throw new Error("could not find op by id: " + opId, { "cause": "opId:" + opId }); 13587 } 13588 } 13589 } 13590 13591 if (!op) 13592 { 13593 // fallback: create by objname! 13594 objName = identifier; 13595 const parts = identifier.split("."); 13596 const opObj = Patch.getOpClass(objName); 13597 13598 if (!opObj) 13599 { 13600 this.emitEvent("criticalError", { "title": "Unknown op: " + objName, "text": "Unknown op: " + objName }); 13601 13602 this._log.error("unknown op: " + objName); 13603 throw new Error("unknown op: " + objName); 13604 } 13605 else 13606 { 13607 if (parts.length == 2) op = new window[parts[0]][parts[1]](this, objName, id); 13608 else if (parts.length == 3) op = new window[parts[0]][parts[1]][parts[2]](this, objName, id); 13609 else if (parts.length == 4) op = new window[parts[0]][parts[1]][parts[2]][parts[3]](this, objName, id); 13610 else if (parts.length == 5) op = new window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]](this, objName, id); 13611 else if (parts.length == 6) op = new window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]][parts[5]](this, objName, id); 13612 else if (parts.length == 7) op = new window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]][parts[5]][parts[6]](this, objName, id); 13613 else if (parts.length == 8) op = new window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]][parts[5]][parts[6]][parts[7]](this, objName, id); 13614 else if (parts.length == 9) op = new window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]][parts[5]][parts[6]][parts[7]][parts[8]](this, objName, id); 13615 else if (parts.length == 10) op = new window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]][parts[5]][parts[6]][parts[7]][parts[8]][parts[9]](this, objName, id); 13616 else console.log("parts.length", parts.length); 13617 } 13618 13619 if (op) 13620 { 13621 op.opId = null; 13622 for (const i in CABLES.OPS) 13623 { 13624 if (CABLES.OPS[i].objName == objName) op.opId = i; 13625 } 13626 } 13627 } 13628 } 13629 catch (e) 13630 { 13631 this._crashedOps.push(objName); 13632 13633 this._log.error("[instancing error] " + objName, e); 13634 13635 if (!this.isEditorMode()) 13636 { 13637 this._log.error("INSTANCE_ERR", "Instancing Error: " + objName, e); 13638 13639 // throw new Error("instancing error 1" + objName); 13640 } 13641 else 13642 { 13643 if (this.#initialDeserialize) gui.patchView.store.opCrashed = true; 13644 } 13645 } 13646 13647 if (op) 13648 { 13649 op._objName = objName; 13650 op.patch = this; 13651 } 13652 else 13653 { 13654 this._log.log("no op was created!?", identifier, id); 13655 } 13656 return op; 13657 } 13658 13659 /** 13660 * create a new op in patch 13661 * @function addOp 13662 * @memberof Patch 13663 * @instance 13664 * @param {string} opIdentifier uuid or name, e.g. Ops.Math.Sum 13665 * @param {OpUiAttribs} uiAttribs Attributes 13666 * @param {string} [id] 13667 * @param {boolean} [fromDeserialize] 13668 * @param {string} [opName] e.g. Ops.Math.Sum 13669 * @example 13670 * // add invisible op 13671 * patch.addOp('Ops.Math.Sum', { showUiAttribs: false }); 13672 */ 13673 addOp(opIdentifier, uiAttribs, id, fromDeserialize = false, opName = null) 13674 { 13675 const op = this.createOp(opIdentifier, id, opName); 13676 13677 if (op) 13678 { 13679 uiAttribs = uiAttribs || {}; 13680 if (uiAttribs.hasOwnProperty("errors")) delete uiAttribs.errors; 13681 if (uiAttribs.hasOwnProperty("error")) delete uiAttribs.error; 13682 uiAttribs.subPatch = uiAttribs.subPatch || 0;
13683 op.setUiAttribs(uiAttribs); 13684 if (op.onCreate) op.onCreate(); 13685 13686 if (op.hasOwnProperty("onAnimFrame")) this.addOnAnimFrame(op); 13687 if (op.hasOwnProperty("onMasterVolumeChanged")) this._volumeListeners.push(op); 13688 13689 if (this._opIdCache[op.id]) 13690 { 13691 this._log.warn("opid with id " + op.id + " already exists in patch!"); 13692 this.deleteOp(op.id); // strange with subpatch ops: why is this needed, somehow ops get added twice ???..... 13693 // return; 13694 } 13695 13696 this.ops.push(op); 13697 this._opIdCache[op.id] = op; 13698 13699 if (this._subPatchCacheAdd) this._subPatchCacheAdd(uiAttribs.subPatch, op); 13700 this.emitEvent(Patch.EVENT_OP_ADDED, op, fromDeserialize); 13701 13702 if (op.init) op.init(); 13703 13704 op.emitEvent(Op.EVENT_INIT, fromDeserialize); 13705 } 13706 else 13707 { 13708 this._log.error("addop: op could not be created: ", opIdentifier); 13709 } 13710 13711 return op; 13712 } 13713
13714 addOnAnimFrame(op) 13715 { 13716 for (let i = 0; i < this.animFrameOps.length; i++) if (this.animFrameOps[i] == op) { return; } 13717 13718 this.animFrameOps.push(op); 13719 } 13720 13721 removeOnAnimFrame(op) 13722 { 13723 for (let i = 0; i < this.animFrameOps.length; i++) 13724 { 13725 if (this.animFrameOps[i] == op) 13726 { 13727 this.animFrameOps.splice(i, 1); 13728 return; 13729 } 13730 } 13731 } 13732 13733 addOnAnimFrameCallback(cb) 13734 { 13735 this.animFrameCallbacks.push(cb); 13736 } 13737 13738 removeOnAnimCallback(cb) 13739 { 13740 for (let i = 0; i < this.animFrameCallbacks.length; i++) 13741 { 13742 if (this.animFrameCallbacks[i] == cb) 13743 { 13744 this.animFrameCallbacks.splice(i, 1); 13745 return; 13746 } 13747 } 13748 } 13749 13750 updateAnimMaxTimeSoon() 13751 { 13752 if (this.toAnimMaxTime)clearTimeout(this.toAnimMaxTime); 13753 this.toAnimMaxTime = setTimeout(() => 13754 { 13755 this.updateAnimMaxTime(); 13756 }, 50); 13757 } 13758 13759 updateAnimMaxTime() 13760 { 13761 let maxTime = 0; 13762 for (let i = 0; i < this.ops.length; i++) 13763 { 13764 if (this.ops[i].hasAnimPort) 13765 { 13766 for (let j = 0; j < this.ops[i].portsIn.length; j++) 13767 { 13768 if (this.ops[i].portsIn[j].anim) 13769 { 13770 if (this.ops[i].portsIn[j].anim.lastKey && this.ops[i].portsIn[j].anim.lastKey.time > maxTime) 13771 { 13772 maxTime = this.ops[i].portsIn[j].anim.lastKey.time; 13773 } 13774 } 13775 } 13776 } 13777 } 13778 if (maxTime != this.animMaxTime) 13779 { 13780 this.animMaxTime = maxTime; 13781 this.emitEvent(Patch.EVENT_ANIM_MAXTIME_CHANGE); 13782 } 13783 } 13784 13785 deleteOp(opid, tryRelink, reloadingOp) 13786 { 13787 let found = false; 13788 for (let i = 0; i < this.ops.length; i++) 13789 { 13790 if (this.ops[i].id == opid) 13791 { 13792 const op = this.ops[i]; 13793 13794 /** @type {Port} */ 13795 let reLinkP1 = null; 13796 13797 /** @type {Port} */ 13798 let reLinkP2 = null; 13799 13800 if (op) 13801 { 13802 found = true; 13803 if (tryRelink) 13804 { 13805 if (op.portsIn.length > 0 && op.portsIn[0].isLinked() && (op.portsOut.length > 0 && op.portsOut[0].isLinked())) 13806 { 13807 if (op.portsIn[0].getType() == op.portsOut[0].getType() && op.portsIn[0].links[0]) 13808 { 13809 reLinkP1 = op.portsIn[0].links[0].getOtherPort(op.portsIn[0]); 13810 reLinkP2 = op.portsOut[0].links[0].getOtherPort(op.portsOut[0]); 13811 } 13812 } 13813 } 13814 13815 const opToDelete = this.ops[i]; 13816 opToDelete.removeLinks(); 13817 13818 this.ops.splice(i, 1); 13819 opToDelete.emitEvent("delete", opToDelete); 13820 this.emitEvent(Patch.EVENT_OP_DELETED, opToDelete, reloadingOp); 13821 13822 if (this.clearSubPatchCache) this.clearSubPatchCache(opToDelete.uiAttribs.subPatch); 13823 13824 if (opToDelete.onDelete) opToDelete.onDelete(reloadingOp); 13825 opToDelete.cleanUp(); 13826 13827 if (reLinkP1 !== null && reLinkP2 !== null) 13828 { 13829 this.link(reLinkP1.op, reLinkP1.getName(), reLinkP2.op, reLinkP2.getName()); 13830 } 13831 13832 delete this._opIdCache[opid]; 13833 break; 13834 } 13835 } 13836 } 13837 13838 if (!found) this._log.warn("core patch deleteop: not found...", opid); 13839 } 13840 13841 getFrameNum() 13842 { 13843 return this._frameNum; 13844 } 13845 13846 /** 13847 * @param {number} time 13848 * @param {number} delta 13849 */ 13850 emitOnAnimFrameEvent(time, delta) 13851 { 13852 time = time || this.timer.getTime(); 13853 13854 for (let i = 0; i < this.animFrameCallbacks.length; ++i) 13855 if (this.animFrameCallbacks[i]) 13856 this.animFrameCallbacks[i](time, this._frameNum, delta); 13857 13858 for (let i = 0; i < this.animFrameOps.length; ++i) 13859 if (this.animFrameOps[i].onAnimFrame)
13860 this.animFrameOps[i].onAnimFrame(time, this._frameNum, delta); 13861 } 13862 13863 renderFrame(timestamp) 13864 { 13865 this.timer.update(this.reqAnimTimeStamp); 13866 this.freeTimer.update(this.reqAnimTimeStamp); 13867 const time = this.timer.getTime(); 13868 const startTime = performance.now(); 13869 this.cgl.frameStartTime = this.timer.getTime(); 13870 13871 const delta = timestamp - this.reqAnimTimeStamp || timestamp; 13872 13873 this.emitOnAnimFrameEvent(null, delta); 13874 13875 this.cgl.profileData.profileFrameDelta = delta; 13876 this.reqAnimTimeStamp = timestamp; 13877 this.cgl.profileData.profileOnAnimFrameOps = performance.now() - startTime; 13878 13879 this.emitEvent(Patch.EVENT_RENDER_FRAME, time); 13880 13881 this._frameNum++; 13882 if (this._frameNum == 1) 13883 { 13884 if (this.config.onFirstFrameRendered) this.config.onFirstFrameRendered(); 13885 } 13886 } 13887 13888 /** 13889 * @param {number} [timestamp] 13890 */ 13891 exec(timestamp) 13892 { 13893 if (!this.#renderOneFrame && (this._paused || this.aborted)) return; 13894 this.emitEvent("reqAnimFrame"); 13895 cancelAnimationFrame(this._animReq); 13896 13897 this.config.fpsLimit = this.config.fpsLimit || 0; 13898 if (this.config.fpsLimit) 13899 { 13900 this._frameInterval = 1000 / this.config.fpsLimit; 13901 } 13902 13903 const now = CABLES.now(); 13904 const frameDelta = now - this._frameNext; 13905 13906 if (this.isEditorMode()) 13907 { 13908 if (!this.#renderOneFrame) 13909 { 13910 if (now - this._lastFrameTime >= 500 && this._lastFrameTime !== 0 && !this._frameWasdelayed) 13911 { 13912 this._lastFrameTime = 0; 13913 setTimeout(this.exec.bind(this), 500); 13914 this.emitEvent("renderDelayStart"); 13915 this._frameWasdelayed = true; 13916 return; 13917 } 13918 } 13919 } 13920 13921 if (this.#renderOneFrame || this.config.fpsLimit === 0 || frameDelta > this._frameInterval || this._frameWasdelayed) 13922 { 13923 this.renderFrame(timestamp); 13924 13925 if (this._frameInterval) this._frameNext = now - (frameDelta % this._frameInterval); 13926 } 13927 13928 if (this._frameWasdelayed) 13929 { 13930 this.emitEvent("renderDelayEnd"); 13931 this._frameWasdelayed = false; 13932 } 13933 13934 if (this.#renderOneFrame) 13935 { 13936 if (this.onOneFrameRendered) this.onOneFrameRendered(); // todo remove everywhere and use propper event... 13937 this.emitEvent(Patch.EVENT_RENDERED_ONE_FRAME); 13938 this._renderOneFrame = false; 13939 } 13940 13941 if (this.config.doRequestAnimation) this._animReq = this.cgl.canvas.ownerDocument.defaultView.requestAnimationFrame(this.exec.bind(this)); 13942 } 13943 13944 /** 13945 * link two ops/ports 13946 * @function link 13947 * @memberof Patch 13948 * @instance 13949 * @param {Op} op1 13950 * @param {String} port1Name 13951 * @param {Op} op2 13952 * @param {String} port2Name 13953 * @param {boolean} lowerCase 13954 * @param {boolean} fromDeserialize 13955 */ 13956 link(op1, port1Name, op2, port2Name, lowerCase = false, fromDeserialize = false) 13957 { 13958 if (!op1) return this._log.warn("link: op1 is null "); 13959 if (!op2) return this._log.warn("link: op2 is null"); 13960 13961 const port1 = op1.getPort(port1Name, lowerCase); 13962 const port2 = op2.getPort(port2Name, lowerCase); 13963 13964 if (!port1) return this._log.warn("port1 not found! " + port1Name + " (" + op1.objName + ")"); 13965 if (!port2) return this._log.warn("port2 not found! " + port2Name + " of " + op2.name + "(" + op2.objName + ")", op2); 13966 13967 if (!port1.shouldLink(port1, port2) || !port2.shouldLink(port1, port2)) return false; 13968 13969 if (Link.canLink(port1, port2)) 13970 { 13971 const link = new Link(this); 13972 link.link(port1, port2); 13973 13974 this.emitEvent(Patch.EVENT_LINK, port1, port2, link, fromDeserialize); 13975 return link; 13976 } 13977 } 13978 13979 /** 13980 * @param {Object} options 13981 * @returns {Object|String} 13982 */ 13983 serialize(options) 13984 { 13985 const obj = {}; 13986 13987 options = options || {}; 13988 obj.ops = []; 13989 obj.settings = this.settings; 13990 for (let i = 0; i < this.ops.length; i++) 13991 { 13992 const op = this.ops[i]; 13993 if (op && op.getSerialized)obj.ops.push(op.getSerialized()); 13994 } 13995 13996 (0,utils.cleanJson)(obj); 13997 13998 if (options.asObject) return obj; 13999 return JSON.stringify(obj); 14000 } 14001 14002 getOpsByRefId(refId) // needed for instancing ops ? 14003 { 14004 const perf = gui.uiProfiler.start("[corepatchetend] getOpsByRefId"); 14005 const refOps = []; 14006 const ops = gui.corePatch().ops; 14007 for (let i = 0; i < ops.length; i++) 14008 if (ops[i].storage && ops[i].storage.ref == refId) refOps.push(ops[i]); 14009 perf.finish(); 14010 return refOps; 14011 } 14012 14013 /** 14014 * @param {String} opid 14015 * @returns {Op} 14016 */ 14017 getOpById(opid) 14018 { 14019 return this._opIdCache[opid]; 14020 } 14021 14022 /** 14023 * @param {String} name 14024 */ 14025 getOpsByObjName(name) 14026 { 14027 const arr = []; 14028 // for (const i in this.ops 14029 for (let i = 0; i < this.ops.length; i++) 14030 if (this.ops[i].objName == name) arr.push(this.ops[i]); 14031 return arr; 14032 } 14033 14034 /** 14035 * @param {String} opid 14036 */ 14037 getOpsByOpId(opid) 14038 { 14039 const arr = []; 14040 // for (const i in this.ops) 14041 for (let i = 0; i < this.ops.length; i++) 14042 if (this.ops[i].opId == opid) arr.push(this.ops[i]); 14043 return arr; 14044 } 14045 14046 getSubPatchOpsByName(patchId, objName) 14047 { 14048 const arr = []; 14049 // for (const i in this.ops) 14050 for (let i = 0; i < this.ops.length; i++) 14051 if (this.ops[i].uiAttribs && this.ops[i].uiAttribs.subPatch == patchId && this.ops[i].objName == objName) 14052 arr.push(this.ops[i]); 14053 14054 return arr; 14055 } 14056 14057 getSubPatchOp(patchId, objName) 14058 { 14059 return this.getFirstSubPatchOpByName(patchId, objName); 14060 } 14061 14062 /** 14063 * @param {string} patchId 14064 * @param {string} objName 14065 * @returns {Op} 14066 */ 14067 getFirstSubPatchOpByName(patchId, objName) 14068 { 14069 for (let i = 0; i < this.ops.length; i++) 14070 if (this.ops[i].uiAttribs && this.ops[i].uiAttribs.subPatch == patchId && this.ops[i].objName == objName) 14071 return this.ops[i]; 14072 14073 return null; 14074 } 14075
14076 _addLink(opinid, opoutid, inName, outName) 14077 { 14078 return this.link(this.getOpById(opinid), inName, this.getOpById(opoutid), outName, false, true); 14079 } 14080 14081 /** 14082 * @param {String} s 14083 */ 14084 logStartup(s) 14085 { 14086 if (window.logStartup)window.logStartup(s); 14087 } 14088 14089 /** 14090 * @typedef DeserializeOptions 14091 * @property {boolean} [genIds] 14092 * @property {boolean} [createRef] 14093 */ 14094 14095 /** 14096 * Description 14097 * @param {Object} obj 14098 * @param {DeserializeOptions} options 14099 * @returns {any} 14100 */ 14101 deSerialize(obj, options = { "genIds": false, "createRef": false }) 14102 { 14103 if (this.aborted) return; 14104 const newOps = []; 14105 const loadingId = this.loading.start("core", "deserialize"); 14106 14107 if (typeof obj === "string") obj = JSON.parse(obj); 14108 14109 if (this.#initialDeserialize) 14110 { 14111 this.namespace = obj.namespace || ""; 14112 this.name = obj.name || ""; 14113 this.settings = obj.settings; 14114 } 14115 14116 this.emitEvent("patchLoadStart"); 14117 14118 obj.ops = obj.ops || []; 14119 14120 this.logStartup("add " + obj.ops.length + " ops... "); 14121 14122 const addedOps = []; 14123 14124 // add ops... 14125 for (let iop = 0; iop < obj.ops.length; iop++) 14126 { 14127 const start = CABLES.now(); 14128 const opData = obj.ops[iop]; 14129 let op = null; 14130 14131 try 14132 { 14133 if (opData.opId) op = this.addOp(opData.opId, opData.uiAttribs, opData.id, true, opData.objName); 14134 else op = this.addOp(opData.objName, opData.uiAttribs, opData.id, true); 14135 } 14136 catch (e) 14137 { 14138 this._log.error("[instancing error] op data:", opData, e); 14139 // throw new Error("could not create op by id: <b>" + (opData.objName || opData.opId) + "</b> (" + opData.id + ")"); 14140 } 14141 14142 if (op) 14143 { 14144 addedOps.push(op); 14145 if (options.genIds) op.id = (0,utils.shortId)(); 14146 op.portsInData = opData.portsIn; 14147 op._origData = JSON.parse(JSON.stringify(opData)); 14148 op.storage = opData.storage; 14149 // if (opData.hasOwnProperty("disabled"))op.setEnabled(!opData.disabled); 14150 14151 // for (const ipi in opData.portsIn) 14152 if (opData.portsIn) 14153 for (let ipi = 0; ipi < opData.portsIn.length; ipi++) 14154 { 14155 const objPort = opData.portsIn[ipi]; 14156 if (objPort && objPort.hasOwnProperty("name")) 14157 { 14158 const port = op.getPort(objPort.name); 14159 14160 if (port && (port.uiAttribs.display == "bool" || port.uiAttribs.type == "bool") && !isNaN(objPort.value)) objPort.value = objPort.value == true ? 1 : 0; 14161 if (port && objPort.value !== undefined && port.type != core_port.Port.TYPE_TEXTURE) port.set(objPort.value); 14162 14163 if (port) 14164 { 14165 port.deSerializeSettings(objPort); 14166 } 14167 else 14168 { 14169 14170 /* 14171 * if (port.uiAttribs.hasOwnProperty("title")) 14172 * { 14173 * op.preservedPortTitles = op.preservedPortTitles || {}; 14174 * op.preservedPortTitles[port.name] = port.uiAttribs.title; 14175 * } 14176 */ 14177 op.preservedPortValues = op.preservedPortValues || {}; 14178 op.preservedPortValues[objPort.name] = objPort.value; 14179 } 14180 } 14181 } 14182 14183 // for (const ipo in opData.portsOut) 14184 if (opData.portsOut) 14185 for (let ipo = 0; ipo < opData.portsOut.length; ipo++) 14186 { 14187 const objPort = opData.portsOut[ipo]; 14188 if (objPort && objPort.hasOwnProperty("name")) 14189 { 14190 const port2 = op.getPort(objPort.name); 14191 14192 if (port2) 14193 { 14194 port2.deSerializeSettings(objPort); 14195 14196 if (port2.uiAttribs.hasOwnProperty("title")) 14197 { 14198 op.preservedPortTitles = op.preservedPortTitles || {}; 14199 op.preservedPortTitles[port2.name] = port2.uiAttribs.title; 14200 } 14201 14202 if (port2.type != core_port.Port.TYPE_TEXTURE && objPort.hasOwnProperty("value")) 14203 port2.set(obj.ops[iop].portsOut[ipo].value); 14204
14205 if (objPort.expose) port2.setUiAttribs({ "expose": true }); 14206 } 14207 } 14208 } 14209 newOps.push(op); 14210 } 14211 14212 const timeused = Math.round(100 * (CABLES.now() - start)) / 100; 14213 if (!this.silent && timeused > 5) console.log("long op init ", obj.ops[iop].objName, timeused); 14214 } 14215 this.logStartup("add ops done"); 14216 14217 // for (const i in this.ops) 14218 for (let i = 0; i < this.ops.length; i++) 14219 { 14220 // deprecated use event 14221 if (this.ops[i].onLoadedValueSet) 14222 { 14223 this.ops[i].onLoadedValueSet(this.ops[i]._origData); 14224 this.ops[i].onLoadedValueSet = null; 14225 this.ops[i]._origData = null; 14226 } 14227 14228 // this is only emited when the patch is loaded from serializid data, e.g. loading from api 14229 // NOT when op is created by hand! 14230 this.ops[i].emitEvent(Patch.EVENT_VALUESSET); 14231 } 14232 14233 this.logStartup("creating links"); 14234 14235 if (options.opsCreated)options.opsCreated(addedOps); 14236 // create links... 14237 if (obj.ops) 14238 { 14239 for (let iop = 0; iop < obj.ops.length; iop++) 14240 { 14241 if (obj.ops[iop].portsIn) 14242 { 14243 for (let ipi2 = 0; ipi2 < obj.ops[iop].portsIn.length; ipi2++) 14244 { 14245 if (obj.ops[iop].portsIn[ipi2] && obj.ops[iop].portsIn[ipi2].links) 14246 { 14247 for (let ili = 0; ili < obj.ops[iop].portsIn[ipi2].links.length; ili++) 14248 { 14249 this._addLink( 14250 obj.ops[iop].portsIn[ipi2].links[ili].objIn, 14251 obj.ops[iop].portsIn[ipi2].links[ili].objOut, 14252 obj.ops[iop].portsIn[ipi2].links[ili].portIn, 14253 obj.ops[iop].portsIn[ipi2].links[ili].portOut); 14254 14255 /* 14256 * const took = performance.now - startTime; 14257 * if (took > 100)console.log(obj().ops[iop].portsIn[ipi2].links[ili].objIn, obj.ops[iop].portsIn[ipi2].links[ili].objOut, took); 14258 */ 14259 } 14260 } 14261 } 14262 } 14263 if (obj.ops[iop].portsOut) 14264 for (let ipi2 = 0; ipi2 < obj.ops[iop].portsOut.length; ipi2++) 14265 if (obj.ops[iop].portsOut[ipi2] && obj.ops[iop].portsOut[ipi2].links) 14266 { 14267 for (let ili = 0; ili < obj.ops[iop].portsOut[ipi2].links.length; ili++) 14268 { 14269 if (obj.ops[iop].portsOut[ipi2].links[ili]) 14270 { 14271 if (obj.ops[iop].portsOut[ipi2].links[ili].subOpRef) 14272 { 14273 // lost link 14274 const outOp = this.getOpById(obj.ops[iop].portsOut[ipi2].links[ili].objOut); 14275 let dstOp = null; 14276 let theSubPatch = 0; 14277 14278 for (let i = 0; i < this.ops.length; i++) 14279 { 14280 if ( 14281 this.ops[i].storage && 14282 this.ops[i].storage.ref == obj.ops[iop].portsOut[ipi2].links[ili].subOpRef && 14283 outOp.uiAttribs.subPatch == this.ops[i].uiAttribs.subPatch 14284 ) 14285 { 14286 theSubPatch = this.ops[i].patchId.get(); 14287 break; 14288 } 14289 } 14290 14291 for (let i = 0; i < this.ops.length; i++) 14292 { 14293 if ( 14294 this.ops[i].storage && 14295 this.ops[i].storage.ref == obj.ops[iop].portsOut[ipi2].links[ili].refOp && 14296 this.ops[i].uiAttribs.subPatch == theSubPatch) 14297 { 14298 dstOp = this.ops[i]; 14299 break; 14300 } 14301 } 14302 14303 if (!dstOp) this._log.warn("could not find op for lost link"); 14304 else 14305 { 14306 this._addLink( 14307 dstOp.id, 14308 obj.ops[iop].portsOut[ipi2].links[ili].objOut, 14309 14310 obj.ops[iop].portsOut[ipi2].links[ili].portIn, 14311 obj.ops[iop].portsOut[ipi2].links[ili].portOut); 14312 } 14313 } 14314 else 14315 { 14316 const l = this._addLink(obj.ops[iop].portsOut[ipi2].links[ili].objIn, obj.ops[iop].portsOut[ipi2].links[ili].objOut, obj.ops[iop].portsOut[ipi2].links[ili].portIn, obj.ops[iop].portsOut[ipi2].links[ili].portOut); 14317 14318 if (!l) 14319 { 14320 const op1 = this.getOpById(obj.ops[iop].portsOut[ipi2].links[ili].objIn); 14321 const op2 = this.getOpById(obj.ops[iop].portsOut[ipi2].links[ili].objOut); 14322 14323 if (!op1)console.log("could not find link o
14323p1"); 14324 if (!op2)console.log("could not find link op2"); 14325 14326 const p1Name = obj.ops[iop].portsOut[ipi2].links[ili].portIn; 14327 14328 if (op1 && !op1.getPort(p1Name)) 14329 { 14330 // console.log("PRESERVE port 1 not found", p1Name); 14331 14332 op1.preservedPortLinks[p1Name] = op1.preservedPortLinks[p1Name] || []; 14333 op1.preservedPortLinks[p1Name].push(obj.ops[iop].portsOut[ipi2].links[ili]); 14334 } 14335 14336 const p2Name = obj.ops[iop].portsOut[ipi2].links[ili].portOut; 14337 if (op2 && !op2.getPort(p2Name)) 14338 { 14339 // console.log("PRESERVE port 2 not found", obj.ops[iop].portsOut[ipi2].links[ili].portOut); 14340 op2.preservedPortLinks[p1Name] = op2.preservedPortLinks[p1Name] || []; 14341 op2.preservedPortLinks[p1Name].push(obj.ops[iop].portsOut[ipi2].links[ili]); 14342 } 14343 } 14344 } 14345 } 14346 } 14347 } 14348 } 14349 } 14350 14351 this.logStartup("calling ops onloaded"); 14352 14353 // for (const i in this.ops) 14354 for (let i = 0; i < this.ops.length; i++) 14355 { 14356 if (this.ops[i].onLoaded) 14357 { 14358 // TODO: deprecated - use even 14359 this.ops[i].onLoaded(); 14360 this.ops[i].onLoaded = null; 14361 } 14362 } 14363 14364 this.logStartup("initializing ops..."); 14365 for (let i = 0; i < this.ops.length; i++) 14366 // for (const i in this.ops) 14367 { 14368 if (this.ops[i].init) 14369 { 14370 try 14371 { 14372 this.ops[i].init(); 14373 this.ops[i].init = null; 14374 } 14375 catch (e) 14376 { 14377 console.error("op.init crash", e); 14378 } 14379 } 14380 } 14381 14382 this.logStartup("initializing vars..."); 14383 14384 if (this.config.variables) 14385 for (const varName in this.config.variables) 14386 this.setVarValue(varName, this.config.variables[varName]); 14387 14388 this.logStartup("initializing var ports"); 14389 14390 // for (const i in this.ops) 14391 for (let i = 0; i < this.ops.length; i++) 14392 { 14393 this.ops[i].initVarPorts(); 14394 delete this.ops[i].uiAttribs.pasted; 14395 } 14396 14397 setTimeout(() => { this.loading.finished(loadingId); }, 100); 14398 14399 this.updateAnimMaxTime(); 14400 if (this.config.onPatchLoaded) this.config.onPatchLoaded(this); 14401 14402 this.emitEvent(Patch.EVENT_PATCHLOADEND, newOps, obj, options.genIds); 14403 this.#initialDeserialize = false; 14404 } 14405 14406 profile(enable) 14407 { 14408 this.profiler = new Profiler(this); 14409 // for (const i in this.ops) 14410 for (let i = 0; i < this.ops.length; i++) 14411 this.ops[i].profile(); 14412 } 14413 14414 // ---------------------- 14415 14416 /** 14417 * set variable value 14418 * @function setVariable 14419 * @memberof Patch 14420 * @instance 14421 * @param {String} name of variable 14422 * @param {Number|String|Boolean} val value 14423 */ 14424 setVariable(name, val) 14425 { 14426 if (this._variables[name] !== undefined) 14427 { 14428 this._variables[name].setValue(val); 14429 } 14430 else 14431 { 14432 this._log.warn("variable " + name + " not found!"); 14433 } 14434 } 14435 14436 _sortVars() 14437 { 14438 if (!this.isEditorMode()) return; 14439 const ordered = {}; 14440 Object.keys(this._variables).sort( 14441 (a, b) => 14442 { return a.localeCompare(b, "en", { "sensitivity": "base" }); } 14443 ).forEach((key) => 14444 { 14445 ordered[key] = this._variables[key]; 14446 }); 14447 this._variables = ordered; 14448 } 14449 14450 /** 14451 * has variable 14452 * @function hasVariable 14453 * @memberof Patch 14454 * @instance 14455 * @param {String} name of variable 14456 */ 14457 hasVar(name) 14458 { 14459 return this._variables[name] !== undefined; 14460 } 14461 14462 // used internally 14463 /** 14464 * @param {string} name 14465 * @param {string | number} val 14466 * @param {number} [type] 14467 */ 14468 setVarValue(name, val, type) 14469 { 14470 if (this.hasVar(name)) 14471 { 14472 this._variables[name].setValue(val); 14473 } 14474 else 14475 { 14476 this._variables[name] = new PatchVariable(name, val, type); 14477 this._sortVars(); 14478 this.emitEvent(Patch.EVENT_VARIABLES_CHANGED); 14479 } 14480 return this._variables[name]; 14481 } 14482 14483 // old? 14484 getVarValue(name, val) 14485 { 14486 if (this._variables.hasOwnProperty(name)) return this._variables[name].getValue(); 14487 } 14488 14489 /** 14490 * @function getVar 14491 * @memberof Patch 14492 * @instance 14493 * @param {String} name 14494 * @return {PatchVariable} variable 14495 */ 14496 getVar(name) 14497 { 14498 if (this._variables.hasOwnProperty(name)) return this._variables[name]; 14499 } 14500 14501 deleteVar(name) 14502 { 14503 for (let i = 0; i < this.ops.length; i++) 14504 for (let j = 0; j < this.ops[i].portsIn.length; j++) 14505 if (this.ops[i].portsIn[j].getVariableName() == name) 14506 this.ops[i].portsIn[j].setVariable(null); 14507 14508 delete this._variables[name]; 14509 this.emitEvent("variableDeleted", name); 14510 this.emitEvent("variablesChanged"); 14511 } 14512 14513 /** 14514 * @param {number} t 14515 * @returns {Object} 14516 */ 14517 getVars(t) 14518 { 14519 if (t === undefined) return this._variables; 14520 if (t === 1) return {}; 14521 14522 const perf = gui.uiProfiler.start("[corepatchetend] getVars"); 14523 14524 const vars = []; 14525 let tStr = ""; 14526 if (t == core_port.Port.TYPE_STRING) tStr = "string"; 14527 else if (t == core_port.Port.TYPE_VALUE) tStr = "number"; 14528 else if (t == core_port.Port.TYPE_ARRAY) tStr = "array"; 14529 else if (t == core_port.Port.TYPE_OBJECT) tStr = "object"; 14530 else if (t == core_port.Port.TYPE_DYNAMIC) tStr = "dynamic"; 14531 else 14532 { 14533 console.log("unknown port type", t); 14534 console.log(new Error().stack); 14535 } 14536 14537 for (const i in this._variables) 14538 { 14539 if (!this._variables[i].type || this._variables[i].type == tStr || this._variables[i].type == t) vars.push(this._variables[i]); 14540 } 14541 14542 perf.finish(); 14543 14544 return vars; 14545 } 14546 14547 // getVars(t) 14548 // { 14549 // if (t === undefined) return this._variables; 14550 14551 // const vars = []; 14552 // let tStr = ""; 14553 // if (t == Port.TYPE_STRING) tStr = "string"; 14554 // if (t == Port.TYPE_VALUE) tStr = "number"; 14555 // if (t == Port.TYPE_ARRAY) tStr = "array"; 14556 // if (t == Port.TYPE_OBJECT) tStr = "object"; 14557 14558 // for (const i in this._variables) 14559 // { 14560 // if (!this._variables[i].type || this._variables[i].type == tStr || this._variables[i].type == t) vars.push(this._variables[i]); 14561 // } 14562 // return vars; 14563 // } 14564 14565 /** 14566 * @function preRenderOps 14567 * @memberof Patch 14568 * @instance
14569 * @description invoke pre rendering of ops 14570 * @function 14571 */ 14572 preRenderOps() 14573 { 14574 this._log.log("prerendering..."); 14575 14576 for (let i = 0; i < this.ops.length; i++) 14577 { 14578 if (this.ops[i].preRender) 14579 { 14580 this.ops[i].preRender(); 14581 this._log.log("prerender " + this.ops[i].objName); 14582 } 14583 } 14584 } 14585 14586 /** 14587 * @function dispose 14588 * @memberof Patch 14589 * @instance 14590 * @description stop, dispose and cleanup patch 14591 */ 14592 dispose() 14593 { 14594 this.pause(); 14595 this.clear(); 14596 this.cgl.dispose(); 14597 } 14598 14599 pushTriggerStack(p) 14600 { 14601 this._triggerStack.push(p); 14602 } 14603 14604 popTriggerStack() 14605 { 14606 this._triggerStack.pop(); 14607 } 14608 14609 printTriggerStack() 14610 { 14611 if (this._triggerStack.length == 0) 14612 { 14613 // console.log("stack length", this._triggerStack.length); // eslint-disable-line 14614 return; 14615 } 14616 console.groupCollapsed( // eslint-disable-line 14617 "trigger port stack " + this._triggerStack[this._triggerStack.length - 1].op.objName + "." + this._triggerStack[this._triggerStack.length - 1].name, 14618 ); 14619 14620 const rows = []; 14621 for (let i = 0; i < this._triggerStack.length; i++) 14622 { 14623 rows.push(i + ". " + this._triggerStack[i].op.objName + " " + this._triggerStack[i].name); 14624 } 14625 14626 console.table(rows); // eslint-disable-line 14627 console.groupEnd(); // eslint-disable-line 14628 } 14629 14630 get containerElement() 14631 { 14632 return this.config.containerElement || this.cgl.canvas.parentElement || null; 14633 } 14634 14635 /** 14636 * returns document object of the patch could be != global document object when opening canvas ina popout window 14637 * @function getDocument 14638 * @memberof Patch 14639 * @instance 14640 * @return {Object} document 14641 */ 14642 getDocument() 14643 { 14644 return this.containerElement.ownerDocument; 14645 // return this.cgl.canvas.ownerDocument; 14646 } 14647} 14648 14649Patch.getOpClass = function (objName) 14650{ 14651 const parts = objName.split("."); 14652 let opObj = null; 14653 14654 try 14655 { 14656 if (parts.length == 2) opObj = window[parts[0]][parts[1]]; 14657 else if (parts.length == 3) opObj = window[parts[0]][parts[1]][parts[2]]; 14658 else if (parts.length == 4) opObj = window[parts[0]][parts[1]][parts[2]][parts[3]]; 14659 else if (parts.length == 5) opObj = window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]]; 14660 else if (parts.length == 6) opObj = window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]][parts[5]]; 14661 else if (parts.length == 7) opObj = window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]][parts[5]][parts[6]]; 14662 else if (parts.length == 8) opObj = window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]][parts[5]][parts[6]][parts[7]]; 14663 else if (parts.length == 9) opObj = window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]][parts[5]][parts[6]][parts[7]][parts[8]]; 14664 else if (parts.length == 10) opObj = window[parts[0]][parts[1]][parts[2]][parts[3]][parts[4]][parts[5]][parts[6]][parts[7]][parts[8]][parts[9]]; 14665 return opObj; 14666 } 14667 catch (e) 14668 { 14669 return null; 14670 } 14671}; 14672 14673Patch.replaceOpIds = function (json, options) 14674{ 14675 const opids = {}; 14676 for (const i in json.ops) 14677 { 14678 opids[json.ops[i].id] = json.ops[i]; 14679 } 14680 14681 for (const j in json.ops) 14682 { 14683 for (const k in json.ops[j].portsOut) 14684 { 14685 const links = json.ops[j].portsOut[k].links; 14686 if (links) 14687 { 14688 let l = links.length; 14689 14690 while (l--) 14691 { 14692 if (links[l] && (!opids[links[l].objIn] || !opids[links[l].objOut])) 14693 { 14694 if (!options.doNotUnlinkLostLinks) 14695 { 14696 links.splice(l, 1); 14697 } 14698 else 14699 { 14700 if (options.fixLostLinks) 14701 { 14702 const op = gui.corePatch().getOpById(links[l].objIn); 14703 if (!op) console.log("op not found!"); 14704 else 14705 { 14706 const outerOp = gui.patchView.getSubPatchOuterOp(op.uiAttribs.subPatch); 14707 if (outerOp) 14708 { 14709 op.storage = op.storage || {}; 14710 op.storage.ref = op.storage.ref || (0,utils.shortId)(); 14711 links[l].refOp = op.storage.ref; 14712 links[l].subOpRef = outerOp.storage.ref; 14713 } 14714 } 14715 } 14716 } 14717 } 14718 } 14719 } 14720 } 14721 } 14722 14723 for (const i in json.ops) 14724 { 14725 const op = json.ops[i]; 14726 const oldId = op.id; 14727 let newId = (0,utils.shortId)(); 14728 14729 if (options.prefixHash) newId = (0,utils.prefixedHash)(options.prefixHash + oldId); 14730 14731 else if (options.prefixId) newId = options.prefixId + oldId; 14732 else if (options.refAsId) // when saving json 14733 { 14734 if (op.storage && op.storage.ref) 14735 { 14736 newId = op.storage.ref; 14737 delete op.storage.ref; 14738 } 14739 else 14740 { 14741 op.storage = op.storage || {}; 14742 op.storage.ref = newId = (0,utils.shortId)(); 14743 } 14744 } 14745 14746 const newID = op.id = newId; 14747 14748 if (options.oldIdAsRef) // when loading json 14749 { 14750 op.storage = op.storage || {}; 14751 op.storage.ref = oldId; 14752 } 14753 14754 for (const j in json.ops) 14755 { 14756 if (json.ops[j].portsIn) 14757 for (const k in json.ops[j].portsIn) 14758 { 14759 if (json.ops[j].portsIn[k].links) 14760 { 14761 let l = json.ops[j].portsIn[k].links.length; 14762 14763 while (l--) if (json.ops[j].portsIn[k].links[l] === null) json.ops[j].portsIn[k].links.splice(l, 1); 14764 14765 for (l in json.ops[j].portsIn[k].links) 14766 { 14767 if (json.ops[j].portsIn[k].links[l].objIn === oldId) json.ops[j].portsIn[k].links[l].objIn = newID; 14768 if (json.ops[j].portsIn[k].links[l].objOut === oldId) json.ops[j].portsIn[k].links[l].objOut = newID; 14769 } 14770 } 14771 } 14772 14773 if (json.ops[j].portsOut) 14774 for (const k in json.ops[j].portsOut) 14775 { 14776 if (json.ops[j].portsOut[k].links) 14777 { 14778 let l = json.ops[j].portsOut[k].links.length; 14779 14780 while (l--) if (json.ops[j].portsOut[k].links[l] === null) json.ops[j].portsOut[k].links.splice(l, 1); 14781 14782 for (l in json.ops[j].portsOut[k].links) 14783 { 14784 if (json.ops[j].portsOut[k].links[l].objIn === oldId) json.ops[j].portsOut[k].links[l].objIn = newID; 14785 if (json.ops[j].portsOut[k].links[l].objOut === oldId) json.ops[j].portsOut[k].links[l].objOut = newID; 14786 } 14787 } 14788 } 14789 } 14790 } 14791 14792 // set correct subpatch 14793 const subpatchIds = []; 14794 const fixedSubPatches = []; 14795 14796 for (let i = 0; i < json.ops.length; i++) 14797 { 14798 // if (CABLES.Op.isSubPatchOpName(json.ops[i].objName)) 14799 if (json.ops[i].storage && json.ops[i].storage.subPatchVer) 14800 { 14801 // for (const k in json.ops[i].portsInckkkkk 14802 for (let k = 0; k < json.ops[i].portsIn.length; k++) 14803 { 14804 if (json.ops[i].portsIn[k].name === "patchId") 14805 { 14806 let newId = (0,utils.shortId)(); 14807 14808 if (options.prefixHash) newId = (0,utils.prefixedHash)(options.prefixHash + json.ops[i].portsIn[k].value); 14809 14810 const oldSubPatchId = json.ops[i].portsIn[k].value; 14811 const newSubPatchId = json.ops[i].portsIn[k].value = newId; 14812 14813 subpatchIds.push(newSubPatchId); 14814 14815 for (let j = 0; j < json.ops.length; j++) 14816 { 14817 // op has no uiAttribs in export, we don't care about subpatches in export though 14818 if (json.ops[j].uiAttribs) 14819 { 14820 if (json.ops[j].uiAttribs.subPatch === oldSubPatchId) 14821 { 14822 json.ops[j].uiAttribs.subPatch = newSubPatchId; 14823 fixedSubPatches.push(json.ops[j].id); 14824 } 14825 } 14826 } 14827 } 14828 } 14829 } 14830 } 14831 14832 for (const kk in json.ops) 14833 { 14834 let found = false;
14835 for (let j = 0; j < fixedSubPatches.length; j++) 14836 { 14837 if (json.ops[kk].id === fixedSubPatches[j]) 14838 { 14839 found = true; 14840 break; 14841 } 14842 } 14843 // op has no uiAttribs in export, we don't care about subpatches in export though 14844 if (!found && json.ops[kk].uiAttribs && options.parentSubPatchId != null) 14845 json.ops[kk].uiAttribs.subPatch = options.parentSubPatchId; 14846 } 14847 14848 return json; 14849}; 14850 14851/** 14852 * remove an eventlistener 14853 * @instance 14854 * @function addEventListener 14855 * @param {String} name of event 14856 * @param {function} callback 14857 */ 14858 14859/** 14860 * remove an eventlistener 14861 * @instance 14862 * @function removeEventListener 14863 * @param {String} name of event 14864 * @param {function} callback 14865 */ 14866 14867/** 14868 * op added to patch event 14869 * @event onOpAdd 14870 * 14871 * @memberof Patch 14872 * @type {Object} 14873 * @property {Op} op new op 14874 */ 14875 14876/** 14877 * op deleted from patch 14878 * @event onOpDelete 14879 * @memberof Patch 14880 * @type {Object} 14881 * @property {Op} op that will be deleted 14882 */ 14883 14884/** 14885 * link event - two ports will be linked 14886 * @event onLink 14887 * @memberof Patch 14888 * @type {Object} 14889 * @property {Port} port1 14890 * @property {Port} port2 14891 */ 14892 14893/** 14894 * unlink event - a link was deleted 14895 * @event onUnLink 14896 * @memberof Patch 14897 * @type {Object} 14898 */ 14899 14900/** 14901 * variables has been changed / a variable has been added to the patch 14902 * @event variablesChanged 14903 * @memberof Patch 14904 * @type {Object} 14905 * @property {Port} port1 14906 * @property {Port} port2 14907 */ 14908 14909;// CONCATENATED MODULE: ./src/core/embedding.js 14910 14911 14912 14913const EMBED = {}; 14914 14915/** 14916 * add patch into html element (will create canvas and set size to fill containerElement) 14917 * @name CABLES.EMBED#addPatch 14918 * @param {object|string} _element containerElement dom element or id of element 14919 * @param {Object} options patch options 14920 * @function 14921 */ 14922EMBED.addPatch = function (_element, options) 14923{ 14924 let el = _element; 14925 let id = (0,utils.generateUUID)(); 14926 if (typeof _element == "string") 14927 { 14928 id = _element; 14929 el = document.getElementById(id); 14930 14931 if (!el) 14932 { 14933 console.error(id + " Polyshape Container Element not found!"); 14934 return; 14935 } 14936 } 14937 14938 const canvEl = document.createElement("canvas"); 14939 canvEl.id = "glcanvas_" + id; 14940 canvEl.width = el.clientWidth; 14941 canvEl.height = el.clientHeight; 14942 14943 window.addEventListener( 14944 "resize", 14945 function () 14946 { 14947 this.setAttribute("width", el.clientWidth); 14948 this.height = el.clientHeight; 14949 }.bind(canvEl), 14950 ); 14951 14952 el.appendChild(canvEl); 14953 14954 options = options || {}; 14955 options.glCanvasId = canvEl.id; 14956 14957 if (!options.onError) 14958 { 14959 options.onError = function (err) 14960 { 14961 console.error(err); 14962 }; 14963 } 14964 14965 CABLES.patch = new Patch(options); 14966 return canvEl; 14967}; 14968 14969 14970 14971;// CONCATENATED MODULE: ./src/core/sessionvar.js 14972// todo: old... remove this from ops... 14973 14974/** 14975 * todo: old... remove this from ops... 14976 * 14977 * @class 14978 */ 14979const Variable = function () 14980{ 14981 let value = null; 14982 const changedCallbacks = []; 14983 14984 this.onChanged = function (f) 14985 { 14986 changedCallbacks.push(f); 14987 }; 14988 14989 this.getValue = function () 14990 { 14991 return value; 14992 }; 14993 14994 this.setValue = function (v) 14995 { 14996 value = v; 14997 this.emitChanged(); 14998 }; 14999 15000 this.emitChanged = function () 15001 { 15002 for (let i = 0; i < changedCallbacks.length; i++) 15003 { 15004 changedCallbacks[i](); 15005 } 15006 }; 15007}; 15008 15009 15010 15011// EXTERNAL MODULE: ./src/core/anim_key.js 15012var anim_key = __webpack_require__("./src/core/anim_key.js"); 15013;// CONCATENATED MODULE: ./src/core/index.js 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032CABLES = CABLES || {}; 15033CABLES = { 15034 ...CABLES, 15035 ...constants.CONSTANTS.PORT, 15036 ...constants.CONSTANTS.PACO, 15037 ...constants.CONSTANTS.ANIM, 15038 ...constants.CONSTANTS.OP 15039}; 15040 15041CABLES.EMBED = EMBED; 15042CABLES.Link = Link; 15043CABLES.Port = core_port.Port; 15044CABLES.Op = Op; 15045CABLES.Profiler = Profiler; 15046CABLES.Patch = Patch; 15047CABLES.Timer = timer.Timer; 15048CABLES.Variable = Variable; 15049CABLES.LoadingStatus = LoadingStatus; 15050CABLES.now = timer.now; 15051CABLES.internalNow = timer.internalNow; 15052CABLES.Anim = anim.Anim; 15053CABLES.AnimKey = anim_key.AnimKey; 15054 15055CABLES.shortId = utils.shortId; 15056CABLES.uuid = utils.uuid; 15057CABLES.getShortOpName = utils.getShortOpName; 15058CABLES.simpleId = utils.simpleId; 15059CABLES.clamp = utils.clamp; 15060CABLES.map = utils.map; 15061CABLES.shuffleArray = utils.shuffleArray; 15062CABLES.generateUUID = utils.generateUUID; 15063CABLES.prefixedHash = utils.prefixedHash; 15064CABLES.smoothStep = utils.smoothStep;
15065CABLES.smootherStep = utils.smootherStep; 15066CABLES.cacheBust = utils.cacheBust; 15067CABLES.copyArray = utils.copyArray; 15068CABLES.basename = utils.basename; 15069CABLES.logStack = utils.logStack; 15070CABLES.filename = utils.filename; 15071CABLES.ajax = utils.ajax; 15072CABLES.request = utils.request; 15073CABLES.logErrorConsole = utils.logErrorConsole; 15074CABLES.isNumeric = utils.isNumeric; 15075CABLES.uniqueArray = utils.uniqueArray; 15076 15077/** @type {Array<Op>} */ 15078CABLES.OPS = []; 15079CABLES.utils = utils; 15080CABLES.CONSTANTS = constants.CONSTANTS; 15081 15082CABLES.GLMatrix = esm_namespaceObject; 15083CABLES.SHARED = {}; 15084CABLES.SHARED.Events = eventtarget["default"]; 15085CABLES.SHARED.Logger = logger["default"]; 15086 15087/* harmony default export */ const core = (CABLES); 15088 15089 15090if (!(function () { return !this; }())) console.warn("not in strict mode: index core"); // eslint-disable-line 15091 15092 15093/***/ }), 15094
15095/***/ "./src/core/timer.js": 15096/*!***************************!*\ 15097 !*** ./src/core/timer.js ***! 15098 \***************************/ 15099/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 15100 15101"use strict"; 15102/* harmony export */ __webpack_require__.d(__webpack_exports__, { 15103/* harmony export */ Timer: () => (/* binding */ Timer), 15104/* harmony export */ internalNow: () => (/* binding */ internalNow), 15105/* harmony export */ now: () => (/* binding */ now) 15106/* harmony export */ }); 15107/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/eventtarget.js"); 15108 15109 15110/** 15111 * @namespace CABLES 15112 */ 15113 15114const internalNow = function () 15115{ 15116 return window.performance.now(); 15117}; 15118 15119/* 15120 * current time in milliseconds 15121 * @memberof CABLES 15122 * @function now 15123 * @static 15124 * 15125 */ 15126const now = function () 15127{ 15128 return internalNow(); 15129}; 15130 15131/** 15132 * Measuring time 15133 * @namespace external:CABLES#Timer 15134 * @hideconstructor 15135 * @class 15136 */ 15137class Timer extends cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"] 15138{ 15139 static EVENT_PLAY_PAUSE = "playPause"; 15140 static EVENT_TIME_CHANGED = "timeChanged"; 15141 15142 constructor() 15143 { 15144 super(); 15145 15146 /** 15147 * @private 15148 */ 15149 this._timeStart = internalNow(); 15150 this._timeOffset = 0; 15151 this._currentTime = 0; 15152 this._lastTime = 0; 15153 this._paused = true; 15154 this._delay = 0; 15155 this.overwriteTime = -1; 15156 } 15157 15158 _internalNow() 15159 { 15160 if (this._ts) return this._ts; 15161 return internalNow(); 15162 } 15163 15164 _getTime() 15165 { 15166 this._lastTime = (this._internalNow() - this._timeStart) / 1000; 15167 return this._lastTime + this._timeOffset; 15168 } 15169 15170 /** 15171 * @param {number} d 15172 */ 15173 setDelay(d) 15174 { 15175 this._delay = d; 15176 this.emitEvent(Timer.EVENT_TIME_CHANGED); 15177 } 15178 15179 /** 15180 * @function 15181 * @memberof Timer 15182 * @instance 15183 * @description returns true if timer is playing 15184 * @return {Boolean} value 15185 */ 15186 isPlaying() 15187 { 15188 return !this._paused; 15189 } 15190 15191 /** 15192 * @function 15193 * @memberof Timer 15194 * @instance 15195 * @param {any} ts 15196 * @description update timer 15197 * @return {Number} time 15198 */ 15199 update(ts) 15200 { 15201 if (ts) this._ts = ts; 15202 if (this._paused) return; 15203 this._currentTime = this._getTime(); 15204 15205 return this._currentTime; 15206 } 15207 15208 /** 15209 * @function 15210 * @memberof Timer 15211 * @instance 15212 * @return {Number} time in milliseconds 15213 */ 15214 getMillis() 15215 { 15216 return this.get() * 1000; 15217 } 15218 15219 /** 15220 * @function 15221 * @memberof Timer 15222 * @instance 15223 * @return {Number} value time in seconds 15224 */ 15225 get() 15226 { 15227 return this.getTime(); 15228 } 15229 15230 getTime() 15231 { 15232 if (this.overwriteTime >= 0) return this.overwriteTime - this._delay; 15233 return this._currentTime - this._delay; 15234 } 15235 15236 /** 15237 * toggle between play/pause state 15238 * @function 15239 * @memberof Timer 15240 * @instance 15241 */ 15242 togglePlay() 15243 { 15244 if (this._paused) this.play(); 15245 else this.pause(); 15246 } 15247 15248 /** 15249 * set current time 15250 * @function 15251 * @memberof Timer 15252 * @instance 15253 * @param {Number} t 15254 */ 15255 setTime(t) 15256 { 15257 if (isNaN(t) || t < 0) t = 0; 15258 this._timeStart = this._internalNow(); 15259 this._timeOffset = t; 15260 this._currentTime = t; 15261 this.emitEvent((Timer.EVENT_TIME_CHANGED)); 15262 } 15263 15264 setOffset(val) 15265 { 15266 if (this._currentTime + val < 0) 15267 { 15268 this._timeStart = this._internalNow(); 15269 this._timeOffset = 0; 15270 this._currentTime = 0; 15271 } 15272 else 15273 { 15274 this._timeOffset += val; 15275 this._currentTime = this._lastTime + this._timeOffset; 15276 } 15277 this.emitEvent(Timer.EVENT_TIME_CHANGED); 15278 } 15279 15280 /** 15281 * (re)starts the timer 15282 * @function 15283 * @memberof Timer 15284 * @instance 15285 */ 15286 play() 15287 { 15288 this._timeStart = this._internalNow(); 15289 this._paused = false;
15290 this.emitEvent(Timer.EVENT_PLAY_PAUSE); 15291 } 15292 15293 /** 15294 * pauses the timer 15295 * @function 15296 * @memberof Timer 15297 * @instance 15298 */ 15299 pause() 15300 { 15301 this._timeOffset = this._currentTime; 15302 this._paused = true; 15303 this.emitEvent(Timer.EVENT_PLAY_PAUSE); 15304 } 15305 15306 static now() 15307 { 15308 return window.performance.now(); 15309 } 15310} 15311 15312 15313 15314 15315/***/ }), 15316
15317/***/ "./src/core/utils.js": 15318/*!***************************************!*\ 15319 !*** ./src/core/utils.js + 1 modules ***! 15320 \***************************************/ 15321/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 15322 15323"use strict"; 15324// ESM COMPAT FLAG 15325__webpack_require__.r(__webpack_exports__); 15326 15327// EXPORTS 15328__webpack_require__.d(__webpack_exports__, { 15329 ajax: () => (/* binding */ ajax), 15330 basename: () => (/* binding */ basename), 15331 cacheBust: () => (/* binding */ cacheBust), 15332 clamp: () => (/* binding */ clamp), 15333 cleanJson: () => (/* binding */ cleanJson), 15334 copyArray: () => (/* binding */ copyArray), 15335 escapeHTML: () => (/* binding */ escapeHTML), 15336 filename: () => (/* binding */ filename), 15337 float32Concat: () => (/* binding */ float32Concat), 15338 generateUUID: () => (/* binding */ generateUUID), 15339 getShortOpName: () => (/* binding */ getShortOpName), 15340 isNumeric: () => (/* binding */ isNumeric), 15341 logErrorConsole: () => (/* binding */ logErrorConsole), 15342 logStack: () => (/* binding */ logStack), 15343 map: () => (/* binding */ map), 15344 prefixedHash: () => (/* binding */ prefixedHash), 15345 request: () => (/* binding */ request), 15346 shortId: () => (/* binding */ shortId), 15347 shuffleArray: () => (/* binding */ shuffleArray), 15348 simpleId: () => (/* binding */ simpleId), 15349 smoothStep: () => (/* binding */ smoothStep), 15350 smootherStep: () => (/* binding */ smootherStep), 15351 uniqueArray: () => (/* binding */ uniqueArray), 15352 uuid: () => (/* binding */ uuid) 15353}); 15354 15355// EXTERNAL MODULE: ./src/core/constants.js 15356var constants = __webpack_require__("./src/core/constants.js"); 15357;// CONCATENATED MODULE: ./src/core/extendjs.js 15358/** 15359 * extend javascript functionality 15360 */ 15361 15362/** 15363 * @external Math 15364 */ 15365 15366/** 15367 * set random seed for seededRandom() 15368 * @type Number 15369 * @static 15370 */ 15371Math.randomSeed = 1; 15372 15373/** 15374 * @function external:Math#setRandomSeed 15375 * @param {number} seed 15376 */ 15377Math.setRandomSeed = function (seed) 15378{ 15379 // https://github.com/cables-gl/cables_docs/issues/622 15380 Math.randomSeed = seed * 50728129; 15381 if (seed != 0) 15382 { 15383 Math.randomSeed = Math.seededRandom() * 17624813; 15384 Math.randomSeed = Math.seededRandom() * 9737333; 15385 } 15386}; 15387 15388/** 15389 * generate a seeded random number 15390 * @function seededRandom 15391 * @memberof Math 15392 * @param {Number} max minimum possible random number 15393 * @param {Number} min maximum possible random number 15394 * @return {Number} random value 15395 * @static 15396 */ 15397Math.seededRandom = function (max, min) 15398{ 15399 if (Math.randomSeed === 0) Math.randomSeed = Math.random() * 999; 15400 max = max || 1; 15401 min = min || 0; 15402 15403 Math.randomSeed = (Math.randomSeed * 9301 + 49297) % 233280; 15404 const rnd = Math.randomSeed / 233280.0; 15405 15406 return min + rnd * (max - min); 15407}; 15408 15409/** 15410 * @namespace String 15411 */ 15412 15413/** 15414 * append a linebreak to a string 15415 * @this {String} 15416 * @returns {string} string with newline appended 15417*/ 15418String.prototype.endl = function () 15419{ 15420 return this + "\n"; 15421}; 15422 15423String.prototype.contains = function (str) 15424{ 15425 console.warn("string.contains deprecated, use string.includes"); 15426 console.log((new Error()).stack); 15427 return this.includes(str); 15428 15429}; 15430 15431function extendJs() {} 15432 15433;// CONCATENATED MODULE: ./src/core/utils.js 15434/** 15435 * @namespace external:CABLES#Utils 15436 */ 15437 15438 15439 15440 15441extendJs(); 15442 15443/** 15444 * Merge two Float32Arrays. 15445 * @function float32Concat 15446 * @param {Float32Array} first Left-hand side array 15447 * @param {Float32Array} second Right-hand side array 15448 * @return {Float32Array} 15449 * @static 15450 */ 15451function float32Concat(first, second) 15452{ 15453 if (!(first instanceof Float32Array)) first = new Float32Array(first); 15454 if (!(second instanceof Float32Array)) second = new Float32Array(second); 15455 15456 const result = new Float32Array(first.length + second.length); 15457 15458 result.set(first); 15459 result.set(second, first.length); 15460 15461 return result; 15462} 15463 15464/** 15465 * get op shortname: only last part of fullname and without version 15466 * @function getShortOpName 15467 * @memberof CABLES 15468 * @param {string} fullname full op name 15469 * @static 15470 */ 15471const getShortOpName = function (fullname) 15472{ 15473 let name = fullname.split(".")[fullname.split(".").length - 1]; 15474 15475 if (name.includes(constants.CONSTANTS.OP.OP_VERSION_PREFIX)) 15476 { 15477 const n = name.split(constants.CONSTANTS.OP.OP_VERSION_PREFIX)[1]; 15478 name = name.substring(0, name.length - (constants.CONSTANTS.OP.OP_VERSION_PREFIX + n).length); 15479 } 15480 return name; 15481}; 15482 15483/** 15484 * randomize order of an array 15485 * @function shuffleArray 15486 * @param {Array|Float32Array} array {Array} original 15487 * @return {Array|Float32Array} shuffled array 15488 * @static 15489 */ 15490const shuffleArray = function (array) 15491{ 15492 for (let i = array.length - 1; i > 0; i--) 15493 { 15494 const j = Math.floor(Math.seededRandom() * (i + 1)); 15495 const temp = array[i]; 15496 array[i] = array[j]; 15497 array[j] = temp; 15498 } 15499 return array; 15500}; 15501 15502/** 15503 * generate a short "relativly unique" id 15504 * @function shortId 15505 * @return {String} generated ID 15506 * @static 15507 */ 15508 15509const _shortIds = {}; 15510const shortId = function () 15511{ 15512 let str = Math.random().toString(36).substr(2, 9); 15513 15514 if (_shortIds.hasOwnProperty(str)) str = shortId(); 15515 _shortIds[str] = true; 15516 return str; 15517}; 15518 15519/** 15520 * @typedef {String} UUID 15521*/ 15522 15523/** 15524 * generate a UUID 15525 * @function uuid 15526 * @return {UUID} generated UUID 15527 * @static 15528 */ 15529const uuid = function () 15530{ 15531 let d = new Date().getTime(); 15532 const uuidStr = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => 15533 { 15534 const r = (d + Math.random() * 16) % 16 | 0; 15535 d = Math.floor(d / 16); 15536 return (c == "x" ? r : (r & 0x3) | 0x8).toString(16); 15537 }); 15538 return uuidStr; 15539}; 15540const generateUUID = uuid; 15541 15542function cleanJson(obj) 15543{ 15544 for (const i in obj) 15545 { 15546 if (obj[i] && typeof objValue === "object" && obj[i].constructor === Object) obj[i] = cleanJson(obj[i]); 15547 15548 if (obj[i] === null || obj[i] === undefined) delete obj[i]; 15549 else if (Array.isArray(obj[i]) && obj[i].length == 0) delete obj[i]; 15550 } 15551 15552 return obj; 15553} 15554 15555/** 15556 * @see http://stackoverflow.com/q/7616461/940217 15557 * @param {string} str 15558 * @param {string} prefix 15559 * @return {string} 15560 */ 15561const prefixedHash = function (str, prefix = "id") 15562{ 15563 let hash = 0; 15564 if (str.length > 0) 15565 { 15566 for (let i = 0; i < str.length; i++) 15567 { 15568 let character = str.charCodeAt(i); 15569 hash = ((hash << 5) - hash) + character; 15570 hash &= hash; // Convert to 32bit integer 15571 } 15572 } 15573 return prefix + "" + hash; 15574}; 15575 15576/** 15577 * generate a simple ID 15578 * @return {Number} new id 15579 * @static 15580 */ 15581let simpleIdCounter = 0; 15582const simpleId = function () 15583{ 15584 simpleIdCounter++; 15585 return simpleIdCounter; 15586}; 15587 15588/** 15589 * smoothStep a value 15590 * @param {Number} perc value value to be smoothed [0-1] 15591 * @return {Number} smoothed value 15592 * @static 15593 */ 15594const smoothStep = function (perc) 15595{ 15596 const x = Math.max(0, Math.min(1, (perc - 0) / (1 - 0))); 15597 perc = x * x * (3 - 2 * x); // smoothstep 15598 return perc; 15599}; 15600 15601/** 15602 * smootherstep a value 15603 * @param {Number} perc value to be smoothed [0-1] 15604 * @return {Number} smoothed value 15605 * @static 15606 */
15607const smootherStep = function (perc) 15608{ 15609 const x = Math.max(0, Math.min(1, (perc - 0) / (1 - 0))); 15610 perc = x * x * x * (x * (x * 6 - 15) + 10); // smootherstep 15611 return perc; 15612}; 15613 15614/** 15615 * clamp number / make sure its between min/max 15616 * @param {Number} value value to be mapped 15617 * @param {Number} min minimum value 15618 * @param {Number} max maximum value 15619 * @static 15620 */ 15621const clamp = function (value, min, max) 15622{ 15623 return Math.min(Math.max(value, min), max); 15624}; 15625 15626/** 15627 * map a value in a range to a value in another range 15628 * @param {Number} x value to be mapped 15629 * @param {Number} _oldMin old range minimum value 15630 * @param {Number} _oldMax old range maximum value 15631 * @param {Number} _newMin new range minimum value 15632 * @param {Number} _newMax new range maximum value 15633 * @param {Number} _easing 15634 * @return {Number} mapped value 15635 * @static 15636 */ 15637const map = function (x, _oldMin, _oldMax, _newMin, _newMax, _easing = 0, clamp = true) 15638{ 15639 if (clamp) 15640 { 15641 if (x >= _oldMax) return _newMax; 15642 if (x <= _oldMin) return _newMin; 15643 } 15644 15645 let reverseInput = false; 15646 const oldMin = Math.min(_oldMin, _oldMax); 15647 const oldMax = Math.max(_oldMin, _oldMax); 15648 if (oldMin != _oldMin) reverseInput = true; 15649 15650 let reverseOutput = false; 15651 const newMin = Math.min(_newMin, _newMax); 15652 const newMax = Math.max(_newMin, _newMax); 15653 if (newMin != _newMin) reverseOutput = true; 15654 15655 let portion = 0; 15656 let r = 0; 15657 15658 if (reverseInput) portion = ((oldMax - x) * (newMax - newMin)) / (oldMax - oldMin); 15659 else portion = ((x - oldMin) * (newMax - newMin)) / (oldMax - oldMin); 15660 15661 if (reverseOutput) r = newMax - portion; 15662 else r = portion + newMin; 15663 15664 if (!_easing) return r; 15665 if (_easing == 1) 15666 { 15667 // smoothstep 15668 x = Math.max(0, Math.min(1, (r - _newMin) / (_newMax - _newMin))); 15669 return _newMin + x * x * (3 - 2 * x) * (_newMax - _newMin); 15670 } 15671 if (_easing == 2) 15672 { 15673 // smootherstep 15674 x = Math.max(0, Math.min(1, (r - _newMin) / (_newMax - _newMin))); 15675 return _newMin + x * x * x * (x * (x * 6 - 15) + 10) * (_newMax - _newMin); 15676 } 15677 15678 return r; 15679}; 15680 15681// ---------------------------------------------------------------- 15682 15683/** 15684 * returns true if parameter is a number 15685 * @param {any} n value The value to check. 15686 * @return {Boolean} 15687 * @static 15688 */ 15689function isNumeric(n) 15690{ 15691 return !isNaN(parseFloat(n)) && isFinite(n); 15692} 15693 15694// ---------------------------------------------------------------- 15695 15696/** 15697 * append a unique/random parameter to a url, so the browser is forced to reload the file, even if its cached 15698 * @static 15699 * @param {String} url The url to append the cachebuster parameter to. 15700 * @return {String} url with cachebuster parameter 15701 */ 15702const cacheBust = function (url = "") 15703{ 15704 if (!url) return ""; 15705 if (url.startsWith("data:")) return; 15706 if (url.includes("?")) url += "&"; 15707 else url += "?"; 15708 return url + "cache=" + CABLES.uuid(); 15709}; 15710 15711/** 15712 * copy the content of an array 15713 * @static 15714 * @param {Array} src sourceArray 15715 * @param {Array} dst optional 15716 * @return {Array} dst 15717 */ 15718const copyArray = function (src, dst) 15719{ 15720 if (!src) return null; 15721 dst = dst || []; 15722 dst.length = src.length; 15723 for (let i = 0; i < src.length; i++) 15724 dst[i] = src[i]; 15725 15726 return dst; 15727}; 15728 15729/** 15730 * return the filename part of a url without extension 15731 * @static 15732 * @param {String} url 15733 * @return {String} just the filename 15734 */ 15735const basename = function (url) 15736{ 15737 let name = CABLES.filename(url); 15738 15739 const parts2 = name.split("."); 15740 name = parts2[0]; 15741 15742 return name; 15743}; 15744 15745/** 15746 * output a stacktrace to the console 15747 * @static 15748 */ 15749const logStack = function () 15750{ 15751 console.log("logstack", (new Error()).stack); 15752}; 15753 15754/** 15755 * return the filename part of a url 15756 * @static 15757 * @param {String} url 15758 * @return {String} just the filename 15759 */ 15760const filename = function (url) 15761{ 15762 let name = ""; 15763 if (!url) return ""; 15764 15765 if (url.startsWith("data:") && url.includes(":")) 15766 { 15767 const parts = url.split(","); 15768 return parts[0]; 15769 } 15770 15771 let parts = (url + "").split("/"); 15772 if (parts.length > 0) 15773 { 15774 const str = parts[parts.length - 1]; 15775 let parts2 = str.split("?"); 15776 name = parts2[0]; 15777 } 15778 15779 return name || ""; 15780}; 15781 15782/** 15783 * make an ajax request 15784 * @static 15785 * @function ajax 15786 * @param url 15787 * @param cb 15788 * @param method 15789 * @param post 15790 * @param contenttype 15791 * @param jsonP 15792 * @param headers 15793 * @param options 15794 */ 15795const ajax = function (url, cb, method, post, contenttype, jsonP, headers = {}, options = {}) 15796{ 15797 const requestOptions = { 15798 "url": url, 15799 "cb": cb, 15800 "method": method, 15801 "data": post, 15802 "contenttype": contenttype, 15803 "sync": false, 15804 "jsonP": jsonP, 15805 "headers": headers, 15806 }; 15807 if (options && options.credentials) requestOptions.credentials = options.credentials; 15808 request(requestOptions); 15809}; 15810 15811const request = function (options) 15812{ 15813 if (!options.hasOwnProperty("asynch")) options.asynch = true; 15814 15815 let xhr; 15816 try 15817 { 15818 xhr = new XMLHttpRequest(); 15819 } 15820 catch (e) {} 15821 15822 xhr.onreadystatechange = function () 15823 { 15824 if (xhr.readyState != 4) return; 15825 15826 if (options.cb) 15827 { 15828 if (xhr.status == 200 || xhr.status == 0) options.cb(false, xhr.responseText, xhr); 15829 else options.cb(true, xhr.responseText, xhr); 15830 } 15831 }; 15832 15833 try 15834 { 15835 xhr.open(options.method ? options.method.toUpperCase() : "GET", options.url, !options.sync); 15836 } 15837 catch (e) 15838 { 15839 if (options.cb && e) options.cb(true, e.msg, xhr); 15840 } 15841 15842 if (typeof options.headers === "object") 15843 { 15844 if (options.headers) 15845 {
15846 const keys = Object.keys(options.headers); 15847 for (let i = 0; i < keys.length; i++) 15848 { 15849 const name = keys[i]; 15850 const value = options.headers[name]; 15851 xhr.setRequestHeader(name, value); 15852 } 15853 } 15854 } 15855 15856 if (options.credentials && options.credentials !== "omit") 15857 { 15858 xhr.withCredentials = true; 15859 } 15860 15861 try 15862 { 15863 if (!options.post && !options.data) 15864 { 15865 xhr.send(); 15866 } 15867 else 15868 { 15869 xhr.setRequestHeader( 15870 "Content-type", 15871 options.contenttype ? options.contenttype : "application/x-www-form-urlencoded", 15872 ); 15873 xhr.send(options.data || options.post); 15874 } 15875 } 15876 catch (e) 15877 { 15878 if (options.cb) options.cb(true, e.msg, xhr); 15879 } 15880}; 15881 15882// ---------------------------------------------------------------- 15883 15884const logErrorConsole = function (initiator) 15885{ 15886 CABLES.errorConsole = CABLES.errorConsole || { "log": [] }; 15887 CABLES.errorConsole.log.push({ "initiator": initiator, "arguments": arguments }); 15888 15889 if (!CABLES.errorConsole.ele) 15890 { 15891 const ele = document.createElement("div"); 15892 ele.id = "cablesErrorConsole"; 15893 ele.style.width = "90%"; 15894 ele.style.height = "300px"; 15895 ele.style.zIndex = "9999999"; 15896 ele.style.display = "inline-block"; 15897 ele.style.position = "absolute"; 15898 ele.style.padding = "10px"; 15899 ele.style.fontFamily = "monospace"; 15900 ele.style.color = "red"; 15901 ele.style.backgroundColor = "#200"; 15902 15903 CABLES.errorConsole.ele = ele; 15904 document.body.appendChild(ele); 15905 } 15906 15907 let logHtml = "ERROR<br/>for more info, open your browsers dev tools console (Ctrl+Shift+I or Command+Alt+I)<br/>"; 15908 15909 for (let l = 0; l < CABLES.errorConsole.log.length; l++) 15910 { 15911 logHtml += CABLES.errorConsole.log[l].initiator + " "; 15912 for (let i = 1; i < CABLES.errorConsole.log[l].arguments.length; i++) 15913 { 15914 if (i > 2)logHtml += ", "; 15915 let arg = CABLES.errorConsole.log[l].arguments[i]; 15916 if (arg.constructor.name.indexOf("Error") > -1 || arg.constructor.name.indexOf("error") > -1) 15917 { 15918 let txt = "Uncaught ErrorEvent "; 15919 if (arg.message)txt += " message: " + arg.message; 15920 logHtml += txt; 15921 } 15922 else if (typeof arg == "string") 15923 logHtml += arg; 15924 else if (typeof arg == "number") 15925 logHtml += String(arg) + " "; 15926 } 15927 logHtml += "<br/>"; 15928 } 15929 15930 CABLES.errorConsole.ele.innerHTML = logHtml; 15931}; 15932 15933/** 15934 * @param {Array<any>} arr 15935 */ 15936function uniqueArray(arr) 15937{ 15938 const u = {}, a = []; 15939 for (let i = 0, l = arr.length; i < l; ++i) 15940 { 15941 if (!u.hasOwnProperty(arr[i])) 15942 { 15943 a.push(arr[i]); 15944 u[arr[i]] = 1; 15945 } 15946 } 15947 return a; 15948} 15949 15950const htmlEscapes = { 15951 "&": "&", 15952 "<": "<", 15953 ">": ">", 15954 "\"": """, 15955 "'": "'", 15956}; 15957 15958/** Used to match HTML entities and HTML characters. */ 15959const reUnescapedHtml = /[&<>"']/g; 15960const reHasUnescapedHtml = RegExp(reUnescapedHtml.source); 15961 15962// from https://github.com/lodash/lodash/blob/master/escape.js 15963/* eslint-disable */ 15964const escapeHTML = function(string) 15965{ 15966 return string && reHasUnescapedHtml.test(string) ? 15967 string.replace(reUnescapedHtml, function(chr) { return htmlEscapes[chr]; }) 15968 : string || ""; 15969} 15970/* eslint-enable */ 15971 15972 15973/***/ }), 15974
15975/***/ "./src/corelibs/cg/cg_boundingbox.js": 15976/*!*******************************************!*\ 15977 !*** ./src/corelibs/cg/cg_boundingbox.js ***! 15978 \*******************************************/ 15979/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 15980 15981"use strict"; 15982/* harmony export */ __webpack_require__.d(__webpack_exports__, { 15983/* harmony export */ BoundingBox: () => (/* binding */ BoundingBox) 15984/* harmony export */ }); 15985/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/vec3.js"); 15986/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/mat4.js"); 15987/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables */ "./src/core/utils.js"); 15988 15989 15990 15991 15992 15993/** 15994 * bounding box 15995 * 15996 * @namespace external:CGL 15997 * @param {Geometry} geometry or bounding box 15998 */ 15999class BoundingBox 16000{ 16001 16002 /** 16003 * @param {Geometry} [geom] 16004 */ 16005 constructor(geom) 16006 { 16007 this._init(); 16008 this._first = true; 16009 this._wireMesh = null; 16010 16011 if (geom) this.applyGeom(geom); 16012 } 16013 16014 _init() 16015 { 16016 this._max = [-0, -0, -0]; 16017 this._min = [0, 0, 0]; 16018 this._center = [0, 0, 0]; 16019 this._size = [0, 0, 0]; 16020 this._maxAxis = 0.0; 16021 this._first = true; 16022 } 16023 16024 /** 16025 * get biggest number of maxX,maxY,maxZ 16026 * @type {Number} 16027 */ 16028 get maxAxis() { return this._maxAxis || 1; } 16029 16030 /** 16031 * size of bounding box 16032 * @type {vec3} 16033 */ 16034 get size() { return this._size; } 16035 16036 /** 16037 * center of bounding box 16038 * @type {vec3} 16039 */ 16040 get center() { return this._center; } 16041 16042 /** 16043 * center x 16044 * @type {Number} 16045 */ 16046 get x() { return this._center[0]; } 16047 16048 /** 16049 * center y 16050 * @type {Number} 16051 */ 16052 get y() { return this._center[1]; } 16053 16054 /** 16055 * center z 16056 * @type {Number} 16057 */ 16058 get z() { return this._center[2]; } 16059 16060 /** 16061 * minimum x 16062 * @type {Number} 16063 */ 16064 get minX() { return this._min[0]; } 16065 16066 /** 16067 * minimum y 16068 * @type {Number} 16069 */ 16070 get minY() { return this._min[1]; } 16071 16072 /** 16073 * minimum z 16074 * @type {Number} 16075 */ 16076 get minZ() { return this._min[2]; } 16077 16078 /** 16079 * maximum x 16080 * @type {Number} 16081 */ 16082 get maxX() { return this._max[0]; } 16083 16084 /** 16085 * maximum y 16086 * @type {Number} 16087 */ 16088 get maxY() { return this._max[1]; } 16089 16090 /** 16091 * maximum z 16092 * @type {Number} 16093 */ 16094 get maxZ() { return this._max[2]; } 16095 16096 /** 16097 * @deprecated 16098 * @param {Geometry} geom 16099 */ 16100 apply(geom) 16101 { 16102 return this.applyGeom(geom); 16103 } 16104 16105 /** 16106 * @param {Geometry} geom 16107 */ 16108 applyGeom(geom) 16109 { 16110 if (!geom) return; 16111 16112 if (geom instanceof BoundingBox) 16113 { 16114 const bb = geom; 16115 16116 this.applyPos(bb.maxX, bb.maxY, bb.maxZ); 16117 this.applyPos(bb.minX, bb.minY, bb.minZ); 16118 } 16119 else 16120 { 16121 if (geom.isGeometry) 16122 for (let i = 0; i < geom.vertices.length; i += 3) 16123 this.applyPos(geom.vertices[i], geom.vertices[i + 1], geom.vertices[i + 2]); 16124 } 16125 this.calcCenterSize(); 16126 } 16127 16128 /** 16129 * returns a copy of the bounding box 16130 * @function copy 16131 * @memberof BoundingBox 16132 * @instance 16133 */ 16134 copy() 16135 { 16136 return new BoundingBox(this); 16137 } 16138 16139 get changed() 16140 { 16141 return !(this._max[0] == -Number.MAX_VALUE && this._max[1] == -Number.MAX_VALUE && this._max[2] == -Number.MAX_VALUE); 16142 } 16143 16144 /** 16145 * @param {number} x 16146 * @param {number} y 16147 * @param {number} z 16148 */ 16149 applyPos(x, y, z) 16150 { 16151 if (x == Number.MAX_VALUE || x == -Number.MAX_VALUE || 16152 y == Number.MAX_VALUE || y == -Number.MAX_VALUE || 16153 z == Number.MAX_VALUE || z == -Number.MAX_VALUE) return; 16154 16155 if (!cables__WEBPACK_IMPORTED_MODULE_0__.isNumeric(x) || !cables__WEBPACK_IMPORTED_MODULE_0__.isNumeric(y) || !cables__WEBPACK_IMPORTED_MODULE_0__.isNumeric(z)) return; 16156 16157 if (this._first) 16158 { 16159 this._max[0] = x; 16160 this._max[1] = y; 16161 this._max[2] = z; 16162 16163 this._min[0] = x; 16164 this._min[1] = y; 16165 this._min[2] = z; 16166 this._first = false;
16167 return; 16168 } 16169 16170 this._max[0] = Math.max(this._max[0], x); 16171 this._max[1] = Math.max(this._max[1], y); 16172 this._max[2] = Math.max(this._max[2], z); 16173 16174 this._min[0] = Math.min(this._min[0], x); 16175 this._min[1] = Math.min(this._min[1], y); 16176 this._min[2] = Math.min(this._min[2], z); 16177 } 16178 16179 calcCenterSize() 16180 { 16181 if (this._first) return; 16182 16183 this._size[0] = this._max[0] - this._min[0]; 16184 this._size[1] = this._max[1] - this._min[1]; 16185 this._size[2] = this._max[2] - this._min[2]; 16186 16187 this._center[0] = (this._min[0] + this._max[0]) / 2; 16188 this._center[1] = (this._min[1] + this._max[1]) / 2; 16189 this._center[2] = (this._min[2] + this._max[2]) / 2; 16190 16191 this._maxAxis = Math.max(this._size[2], Math.max(this._size[0], this._size[1])); 16192 } 16193 16194 /** 16195 * @param {mat4} m 16196 */ 16197 mulMat4(m) 16198 { 16199 if (this._first) 16200 { 16201 this._max[0] = 0; 16202 this._max[1] = 0; 16203 this._max[2] = 0; 16204 16205 this._min[0] = 0; 16206 this._min[1] = 0; 16207 this._min[2] = 0; 16208 this._first = false; 16209 } 16210 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.transformMat4(this._max, this._max, m); 16211 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.transformMat4(this._min, this._min, m); 16212 this.calcCenterSize(); 16213 } 16214 16215 /** 16216 * @param {CglContext} cgl 16217 * @param {Shader} _shader 16218 * @param {Op} op 16219 */ 16220 render(cgl, _shader, op) 16221 { 16222 if (!this._wireMesh) this._wireMesh = new CGL.WireCube(cgl); 16223 16224 cgl.pushModelMatrix(); 16225 gl_matrix__WEBPACK_IMPORTED_MODULE_2__.translate(cgl.mMatrix, cgl.mMatrix, this._center); 16226 16227 if (CABLES.UI && op) 16228 { 16229 CABLES.UI.OverlayMeshes.drawCube(op, this._size[0] / 2, this._size[1] / 2, this._size[2] / 2); 16230 } 16231 16232 cgl.popModelMatrix(); 16233 } 16234} 16235 16236 16237/***/ }), 16238
16239/***/ "./src/corelibs/cg/cg_canvas.js": 16240/*!**************************************!*\ 16241 !*** ./src/corelibs/cg/cg_canvas.js ***! 16242 \**************************************/ 16243/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 16244 16245"use strict"; 16246/* harmony export */ __webpack_require__.d(__webpack_exports__, { 16247/* harmony export */ CgCanvas: () => (/* binding */ CgCanvas) 16248/* harmony export */ }); 16249/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 16250 16251 16252class CgCanvas 16253{ 16254 hasFocus = false; 16255 16256 forceAspect = 0; 16257 pixelDensity = 1; 16258 _oldWidthRp = -1; 16259 _oldHeightRp = -1; 16260 16261 /** 16262 * @param {{ canvasEle: any; cg: any; }} options 16263 */ 16264 constructor(options) 16265 { 16266 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"]("CgCanvas"); 16267 if (!options) 16268 { 16269 this._log.error("CgCanvas no options"); 16270 } 16271 else 16272 { 16273 this._canvasEle = options.canvasEle; 16274 } 16275 16276 if (!options.cg) this._log.error("CgCanvas options has no cg"); 16277 // if (!options.canvasEle) this._log.error("CgCanvas options has no canvasEle"); 16278 16279 this._cg = options.cg; 16280 if (this.canvasEle) 16281 { 16282 this.canvasWidth = this.canvasEle.clientWidth; 16283 this.canvasHeight = this.canvasEle.clientHeight; 16284 16285 this.setSize(this.canvasWidth, this.canvasHeight); 16286 this.canvasEle.addEventListener("focus", () => { this.hasFocus = true; }); 16287 this.canvasEle.addEventListener("blur", () => { this.hasFocus = false; }); 16288 } 16289 } 16290 16291 /** 16292 * @returns {HTMLElement} 16293 */ 16294 get canvasEle() { return this._canvasEle; } 16295 16296 /** 16297 * @param {Number} w 16298 * @param {Number} h 16299 * @param {any} ignorestyle 16300 * @returns {any} 16301 */ 16302 setSize(w, h, ignorestyle = false) 16303 { 16304 let offY = 0; 16305 if (this.forceAspect) 16306 { 16307 let nh = w / this.forceAspect; 16308 if (nh < h)offY = (h - nh) / 2; 16309 h = nh; 16310 } 16311 16312 if (this._oldWidthRp != w * this.pixelDensity || this._oldHeightRp != h * this.pixelDensity) 16313 { 16314 this._oldWidthRp = this.canvasEle.width = w * this.pixelDensity; 16315 this._oldHeightRp = this.canvasEle.height = h * this.pixelDensity; 16316 16317 if (!ignorestyle) 16318 { 16319 this.canvasEle.style.width = w + "px"; 16320 this.canvasEle.style.height = h + "px"; 16321 this.canvasEle.style.marginTop = offY + "px"; 16322 } 16323 16324 this.updateSize(); 16325 16326 this._cg.emitEvent("resize"); 16327 } 16328 } 16329 16330 updateSize() 16331 { 16332 this.canvasEle.width = this.canvasWidth = Math.ceil(this.canvasEle.clientWidth * this.pixelDensity); 16333 this.canvasEle.height = this.canvasHeight = Math.ceil(this.canvasEle.clientHeight * this.pixelDensity); 16334 // console.log("text", this.canvasEle.width, this.canvasEle.clientWidth, this.canvasEle.getBoundingClientRect().width); 16335 } 16336 16337 dispose() 16338 { 16339 if (this._canvasEle) this._canvasEle.remove(); 16340 this._canvasEle = null; 16341 } 16342} 16343 16344 16345/***/ }), 16346
16347/***/ "./src/corelibs/cg/cg_context.js": 16348/*!***************************************!*\ 16349 !*** ./src/corelibs/cg/cg_context.js ***! 16350 \***************************************/ 16351/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 16352 16353"use strict"; 16354/* harmony export */ __webpack_require__.d(__webpack_exports__, { 16355/* harmony export */ CgContext: () => (/* binding */ CgContext) 16356/* harmony export */ }); 16357/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/eventtarget.js"); 16358/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 16359/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/vec3.js"); 16360/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/mat4.js"); 16361/* harmony import */ var _cg_canvas_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./cg_canvas.js */ "./src/corelibs/cg/cg_canvas.js"); 16362/* harmony import */ var _cg_matrixstack_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cg_matrixstack.js */ "./src/corelibs/cg/cg_matrixstack.js"); 16363/* harmony import */ var _cgl_cgl_profiledata_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../cgl/cgl_profiledata.js */ "./src/corelibs/cgl/cgl_profiledata.js"); 16364/* harmony import */ var _cg_fpscounter_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./cg_fpscounter.js */ "./src/corelibs/cg/cg_fpscounter.js"); 16365 16366 16367 16368 16369 16370 16371 16372 16373class CgContext extends cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"] 16374{ 16375 16376 static API_UNKNOWN = 0; 16377 static API_WEBGL = 1; 16378 static API_WEBGPU = 2; 16379 16380 static EVENT_RESIZE = "resize"; 16381 16382 gApi = 0; 16383 16384 _textureslots = []; 16385 _pMatrixStack = new _cg_matrixstack_js__WEBPACK_IMPORTED_MODULE_1__.MatrixStack(); 16386 _mMatrixStack = new _cg_matrixstack_js__WEBPACK_IMPORTED_MODULE_1__.MatrixStack(); 16387 _vMatrixStack = new _cg_matrixstack_js__WEBPACK_IMPORTED_MODULE_1__.MatrixStack(); 16388 canvasScale = 1; // this is not pixeldensity, this is only for command "scale canvas" 16389 16390 /** 16391 * Description 16392 * @param {Patch} _patch 16393 */ 16394 constructor(_patch) 16395 { 16396 super(); 16397 16398 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_2__["default"]("cg_context", { "onError": _patch.config.onError }); 16399 16400 /** @type {object} */ 16401 this.tempData = this.frameStore = this.frameStore || {}; 16402 this.fpsCounter = new _cg_fpscounter_js__WEBPACK_IMPORTED_MODULE_3__.FpsCounter(); 16403 this._identView = gl_matrix__WEBPACK_IMPORTED_MODULE_4__.create(); 16404 this._ident = gl_matrix__WEBPACK_IMPORTED_MODULE_4__.create(); 16405 gl_matrix__WEBPACK_IMPORTED_MODULE_4__.set(this._identView, 0, 0, -2); 16406 gl_matrix__WEBPACK_IMPORTED_MODULE_4__.set(this._ident, 0, 0, 0); 16407 this._onetimeCallbacks = []; 16408 this.maxTexSize = 2048; 16409 this._viewPort = [0, 0, 1, 1]; 16410 this._viewPortStack = []; 16411 this.patch = _patch; 16412 this.autoReSize = true; 16413 16414 this.DEPTH_COMPARE_FUNC_NEVER = 0; 16415 this.DEPTH_COMPARE_FUNC_LESS = 1; 16416 this.DEPTH_COMPARE_FUNC_EQUAL = 2; 16417 this.DEPTH_COMPARE_FUNC_LESSEQUAL = 3; 16418 this.DEPTH_COMPARE_FUNC_GREATER = 4; 16419 this.DEPTH_COMPARE_FUNC_NOTEQUAL = 5; 16420 this.DEPTH_COMPARE_FUNC_GREATEREQUAL = 6; 16421 this.DEPTH_COMPARE_FUNC_ALWAYS = 7; 16422 16423 this.profileData = new _cgl_cgl_profiledata_js__WEBPACK_IMPORTED_MODULE_5__.ProfileData(this); 16424 16425 /** 16426 * Current projection matrix 16427 * @memberof Context 16428 * @instance 16429 * @type {mat4} 16430 */ 16431 this.pMatrix = gl_matrix__WEBPACK_IMPORTED_MODULE_6__.create(); 16432 16433 /** 16434 * Current model matrix 16435 * @memberof Context 16436 * @instance 16437 * @type {mat4} 16438 */ 16439 this.mMatrix = gl_matrix__WEBPACK_IMPORTED_MODULE_6__.create(); 16440 16441 /** 16442 * Current view matrix 16443 * @memberof Context 16444 * @instance 16445 * @type {mat4} 16446 */ 16447 this.vMatrix = gl_matrix__WEBPACK_IMPORTED_MODULE_6__.create(); 16448 16449 gl_matrix__WEBPACK_IMPORTED_MODULE_6__.identity(this.mMatrix); 16450 gl_matrix__WEBPACK_IMPORTED_MODULE_6__.identity(this.vMatrix); 16451 16452 window.matchMedia("screen and (min-resolution: 2dppx)").addEventListener("change", () => 16453 { 16454 this.emitEvent("resize"); 16455 }); 16456 16457 } 16458 16459 get canvasWidth() 16460 { 16461 return this.width; 16462 } 16463 16464 get canvasHeight() 16465 { 16466 return this.height; 16467 } 16468 16469 get width() 16470 { 16471 return this.cgCanvas.canvasWidth; 16472 } 16473 16474 get height() 16475 { 16476 return this.cgCanvas.canvasHeight; 16477 } 16478 16479 get widthCss() 16480 { 16481 return this.cgCanvas.canvasWidth / this.pixelDensity; 16482 } 16483 16484 get heightCss() 16485 { 16486 return this.cgCanvas.canvasHeight / this.pixelDensity; 16487 } 16488 16489 set pixelDensity(p) 16490 { 16491 if (this.cgCanvas.pixelDensity != p) 16492 { 16493 this.cgCanvas.pixelDensity = p; 16494 this.cgCanvas.updateSize(); 16495 this.emitEvent("resize"); 16496 } 16497 } 16498 16499 get pixelDensity() 16500 { 16501 return this.cgCanvas.pixelDensity; 16502 } 16503 16504 getGApiName() 16505 { 16506 return ["unknown", "WebGL", "WebGPU"][this.gApi]; 16507 } 16508 16509 get canvas() 16510 { 16511 return this.cgCanvas.canvasEle; 16512 } 16513 16514 get viewPort() 16515 { 16516 // TODO: add stack... 16517 return [0, 0, this.canvasWidth, this.canvasHeight]; 16518 } 16519 16520 /** 16521 * @param {HTMLElement} canvEle 16522 */ 16523 setCanvas(canvEle) 16524 { 16525 if (this.cgCanvas && canvEle == this.cgCanvas.canvasEle) return; 16526 if (typeof canvEle === "string") canvEle = document.getElementById(canvEle); 16527 16528 this.cgCanvas = new _cg_canvas_js__WEBPACK_IMPORTED_MODULE_7__.CgCanvas({ "canvasEle": canvEle, "cg": this }); 16529 if (!canvEle) return; 16530 16531 canvEle.parentElement.classList.add("cablesContainer"); 16532 if (this._setCanvas) this._setCanvas(canvEle); 16533 16534 this.updateSize(); 16535 } 16536 16537 /** 16538 * @param {HTMLElement} _canvEle 16539 */ 16540 _setCanvas(_canvEle) 16541 { 16542 } 16543 16544 updateSize() 16545 { 16546 this.cgCanvas.updateSize(); 16547 } 16548 16549 /** 16550 * @param {number} w 16551 * @param {number} h 16552 * @param {boolean} ignorestyle 16553 */ 16554 setSize(w, h, ignorestyle = false) 16555 { 16556 this.cgCanvas.setSize(w, h, ignorestyle); 16557 } 16558 16559 _resizeToWindowSize() 16560 { 16561 if (this.autoReSize) 16562 { 16563 this.setSize(window.innerWidth, window.innerHeight); 16564 this.updateSize(); 16565 } 16566 } 16567 16568 _resizeToParentSize() 16569 { 16570 if (this.autoReSize) 16571 { 16572 const p = this.canvas.parentElement; 16573 if (!p) 16574 { 16575 this._log.error("cables: can not resize to container element"); 16576 return; 16577 } 16578 16579 this.setSize(p.clientWidth, p.clientHeight); 16580 this.updateSize(); 16581 } 16582 } 16583 16584 setAutoResize(parent) 16585 { 16586 window.removeEventListener("resize", this._resizeToWindowSize.bind(this)); 16587 window.removeEventListener("resize", this._resizeToParentSize.bind(this)); 16588 16589 if (parent == "window") 16590 { 16591 window.addEventListener("resize", this._resizeToWindowSize.bind(this)); 16592 window.addEventListener("orientationchange", this._resizeToWindowSize.bind(this)); 16593 this._resizeToWindowSize(); 16594 } 16595 if (parent == "parent") 16596 { 16597 window.addEventListener("resize", this._resizeToParentSize.bind(this)); 16598 this._resizeToParentSize(); 16599 } 16600 } 16601 16602 /** 16603 * push a matrix to the projection matrix stack 16604 * @function pushPMatrix 16605 * @memberof Context 16606 * @instance 16607 */ 16608 pushPMatrix() 16609 { 16610 this.pMatrix = this._pMatrixStack.push(this.pMatrix); 16611 } 16612 16613 /** 16614 * pop projection matrix stack 16615 * @function popPMatrix 16616 * @memberof Context 16617 * @instance 16618 * @returns {mat4} current projectionmatrix 16619 */ 16620 popPMatrix() 16621 { 16622 this.pMatrix = this._pMatrixStack.pop(); 16623 return this.pMatrix; 16624 } 16625 16626 getProjectionMatrixStateCount() 16627 { 16628 return this._pMatrixStack.stateCounter; 16629 } 16630 16631 /** 16632 * push a matrix to the model matrix stack 16633 * @function pushModelMatrix 16634 * @memberof Context 16635 * @instance 16636 * @example 16637 * // see source code of translate op: 16638 * cgl.pushModelMatrix(); 16639 * mat4.translate(cgl.mMatrix,cgl.mMatrix, vec); 16640 * trigger.trigger(); 16641 * cgl.popModelMatrix(); 16642 */ 16643 pushModelMatrix() 16644 { 16645 this.mMatrix = this._mMatrixStack.push(this.mMatrix); 16646 } 16647 16648 /** 16649 * pop model matrix stack 16650 * @function popModelMatrix 16651 * @memberof Context 16652 * @instance 16653 * @returns {mat4} current modelmatrix 16654 */
16655 popModelMatrix() 16656 { 16657 // todo: DEPRECATE 16658 // if (this._mMatrixStack.length === 0) throw "Invalid modelview popMatrix!"; 16659 this.mMatrix = this._mMatrixStack.pop(); 16660 return this.mMatrix; 16661 } 16662 16663 /** 16664 * get model matrix 16665 * @function modelMatrix 16666 * @memberof Context 16667 * @instance 16668 * @returns {mat4} current modelmatrix 16669 */ 16670 modelMatrix() 16671 { 16672 return this.mMatrix; 16673 } 16674 16675 /** 16676 * push a matrix to the view matrix stack 16677 * @function pushviewMatrix 16678 * @memberof Context 16679 * @instance 16680 */ 16681 pushViewMatrix() 16682 { 16683 this.vMatrix = this._vMatrixStack.push(this.vMatrix); 16684 } 16685 16686 /** 16687 * pop view matrix stack 16688 * @function popViewMatrix 16689 * @memberof Context 16690 * @instance 16691 * @returns {mat4} current viewmatrix 16692 * @function 16693 */ 16694 popViewMatrix() 16695 { 16696 this.vMatrix = this._vMatrixStack.pop(); 16697 } 16698 16699 getViewMatrixStateCount() 16700 { 16701 return this._vMatrixStack.stateCounter; 16702 } 16703 16704 /** 16705 * @param {vec3} identTranslate 16706 * @param {vec3} identTranslateView 16707 */ 16708 _startMatrixStacks(identTranslate, identTranslateView) 16709 { 16710 identTranslate = identTranslate || this._ident; 16711 identTranslateView = identTranslateView || this._identView; 16712 16713 gl_matrix__WEBPACK_IMPORTED_MODULE_6__.perspective(this.pMatrix, 45, this.canvasWidth / this.canvasHeight, 0.1, 1000.0); 16714 16715 gl_matrix__WEBPACK_IMPORTED_MODULE_6__.identity(this.mMatrix); 16716 gl_matrix__WEBPACK_IMPORTED_MODULE_6__.identity(this.vMatrix); 16717 gl_matrix__WEBPACK_IMPORTED_MODULE_6__.translate(this.mMatrix, this.mMatrix, identTranslate); 16718 gl_matrix__WEBPACK_IMPORTED_MODULE_6__.translate(this.vMatrix, this.vMatrix, identTranslateView); 16719 16720 this.pushPMatrix(); 16721 this.pushModelMatrix(); 16722 this.pushViewMatrix(); 16723 } 16724 16725 _endMatrixStacks() 16726 { 16727 this.popViewMatrix(); 16728 this.popModelMatrix(); 16729 this.popPMatrix(); 16730 } 16731 16732 dispose() 16733 { 16734 this.aborted = true; 16735 if (this.cgCanvas) this.cgCanvas.dispose(); 16736 if (this._dispose) this._dispose(); 16737 } 16738 16739 _dispose() 16740 { 16741 } 16742 16743 /** 16744 * @param {any} _op 16745 */ 16746 shouldDrawHelpers(_op) 16747 { 16748 return false; 16749 } 16750 16751 /** 16752 * execute the callback next frame, once 16753 * @param {function} cb 16754 */ 16755 addNextFrameOnceCallback(cb) 16756 { 16757 if (cb && this._onetimeCallbacks.indexOf(cb) == -1) this._onetimeCallbacks.push(cb); 16758 } 16759 16760 _execOneTimeCallbacks() 16761 { 16762 if (this._onetimeCallbacks.length > 0) 16763 { 16764 for (let i = 0; i < this._onetimeCallbacks.length; i++) this._onetimeCallbacks[i](); 16765 this._onetimeCallbacks.length = 0; 16766 } 16767 } 16768 16769 /** 16770 * @param {number} x 16771 */ 16772 checkTextureSize(x) 16773 { 16774 x = x || 1; 16775 x = Math.floor(x); 16776 x = Math.min(x, this.maxTexSize); 16777 x = Math.max(x, 1); 16778 return x; 16779 } 16780 16781 // should be overwritten... 16782 screenShot(cb, doScreenshotClearAlpha, mimeType, quality) 16783 { 16784 console.log("no screenshot function implemented"); 16785 } 16786 16787 /** 16788 * @param {string} [filename] 16789 * @param {function} [cb] 16790 * @param {number} [pw] 16791 * @param {number} [ph] 16792 * @param {boolean} [_noclearalpha] 16793 */ 16794 saveScreenshot(filename, cb, pw, ph, _noclearalpha) 16795 { 16796 this.patch.renderOneFrame(); 16797 16798 let w = this.canvas.clientWidth * this.pixelDensity; 16799 let h = this.canvas.clientHeight * this.pixelDensity; 16800 16801 if (pw) 16802 { 16803 this.canvas.width = pw; 16804 w = pw; 16805 } 16806 if (ph) 16807 { 16808 this.canvas.height = ph; 16809 h = ph; 16810 } 16811 16812 function padLeft(nr, n, str) 16813 { 16814 return Array(n - String(nr).length + 1).join(str || "0") + nr; 16815 } 16816 16817 const d = new Date(); 16818 const dateStr = "".concat(String(d.getFullYear()) + String(d.getMonth() + 1) + String(d.getDate()), "_").concat(padLeft(d.getHours(), 2)).concat(padLeft(d.getMinutes(), 2)).concat(padLeft(d.getSeconds(), 2)); 16819 16820 if (!filename) filename = "cables_" + dateStr + ".png"; 16821 else filename += ".png"; 16822 16823 this.screenShot((blob) => 16824 { 16825 this.canvas.width = w; 16826 this.canvas.height = h; 16827 16828 if (blob) 16829 { 16830 const anchor = document.createElement("a"); 16831 16832 anchor.download = filename; 16833 anchor.href = URL.createObjectURL(blob); 16834 16835 console.log("scrrenshot"); 16836 setTimeout(function () 16837 { 16838 anchor.click(); 16839 if (cb) cb(blob); 16840 }, 100); 16841 } 16842 else 16843 { 16844 this._log.log("screenshot: no blob"); 16845 } 16846 }); 16847 } 16848 16849 hasFocus() 16850 { 16851 return this.cgCanvas.hasFocus; 16852 16853 } 16854 16855} 16856 16857 16858/***/ }), 16859
16860/***/ "./src/corelibs/cg/cg_fpscounter.js": 16861/*!******************************************!*\ 16862 !*** ./src/corelibs/cg/cg_fpscounter.js ***! 16863 \******************************************/ 16864/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 16865 16866"use strict"; 16867/* harmony export */ __webpack_require__.d(__webpack_exports__, { 16868/* harmony export */ FpsCounter: () => (/* binding */ FpsCounter) 16869/* harmony export */ }); 16870/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/eventtarget.js"); 16871/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cables */ "./src/core/timer.js"); 16872 16873 16874 16875class FpsCounter extends cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"] 16876{ 16877 constructor() 16878 { 16879 super(); 16880 this._timeStartFrame = 0; 16881 this._timeStartSecond = 0; 16882 this._fpsCounter = 0; 16883 this._msCounter = 0; 16884 this._frameCount = 0; 16885 this.logFps = false; 16886 16887 this.stats = { "ms": 0, "fps": 0 }; 16888 } 16889 16890 get frameCount() 16891 { 16892 return this._frameCount; 16893 } 16894 16895 startFrame() 16896 { 16897 this._timeStartFrame = (0,cables__WEBPACK_IMPORTED_MODULE_1__.now)(); 16898 } 16899 16900 endFrame() 16901 { 16902 this._frameCount++; 16903 this._fpsCounter++; 16904 16905 const timeFrame = (0,cables__WEBPACK_IMPORTED_MODULE_1__.now)() - this._timeStartFrame; 16906 this._msCounter += timeFrame; 16907 16908 if ((0,cables__WEBPACK_IMPORTED_MODULE_1__.now)() - this._timeStartSecond > 1000) this.endSecond(); 16909 } 16910 16911 endSecond() 16912 { 16913 this.stats.fps = this._fpsCounter; 16914 this.stats.ms = Math.round(this._msCounter / this._fpsCounter * 100) / 100; 16915 16916 this.emitEvent("performance", this.stats); 16917 if (this.logFps)console.log(this.stats); 16918 16919 // reset 16920 this._fpsCounter = 0; 16921 this._msCounter = 0; 16922 this._timeStartSecond = (0,cables__WEBPACK_IMPORTED_MODULE_1__.now)(); 16923 } 16924} 16925 16926 16927/***/ }), 16928
16929/***/ "./src/corelibs/cg/cg_geom.js": 16930/*!************************************!*\ 16931 !*** ./src/corelibs/cg/cg_geom.js ***! 16932 \************************************/ 16933/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 16934 16935"use strict"; 16936/* harmony export */ __webpack_require__.d(__webpack_exports__, { 16937/* harmony export */ Geometry: () => (/* binding */ Geometry) 16938/* harmony export */ }); 16939/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 16940/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/vec3.js"); 16941/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/vec2.js"); 16942/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! cables */ "./src/core/utils.js"); 16943/* harmony import */ var _cg_boundingbox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./cg_boundingbox.js */ "./src/corelibs/cg/cg_boundingbox.js"); 16944 16945 16946 16947 16948 16949/** 16950 * a geometry contains all information about a mesh, vertices, texturecoordinates etc. etc. 16951 * @param {String} name 16952 * @example 16953 * // create a triangle with all attributes 16954 * const geom=new Geometry("triangle"), 16955 * 16956 * geom.vertices = [ 16957 * 0.0, sizeH.get(), 0.0, 16958 * -sizeW.get(), -sizeH.get(), 0.0, 16959 * sizeW.get(), -sizeH.get(), 0.0 ]; 16960 * 16961 * geom.vertexNormals = [ 16962 * 0.0, 0.0, 1.0, 16963 * 0.0, 0.0, 1.0, 16964 * 0.0, 0.0, 1.0 ]; 16965 * 16966 * geom.tangents = [ 16967 * 1,0,0, 16968 * 1,0,0, 16969 * 1,0,0 ]; 16970 * 16971 * geom.biTangents = [ 16972 * 0,1,0, 16973 * 0,1,0, 16974 * 0,1,0 ]; 16975 * 16976 * geom.texCoords = [ 16977 * 0.5, 0.0, 16978 * 1.0, 1.0, 16979 * 0.0, 1.0, ]; 16980 * 16981 * geom.verticesIndices = [ 16982 * 0, 1, 2 ]; 16983 * 16984 */ 16985 16986class Geometry 16987{ 16988 isGeometry = true; 16989 16990 /** 16991 * @param {String} name 16992 */ 16993 constructor(name) 16994 { 16995 this.name = name || "unknown"; 16996 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"]("cgl_geometry"); 16997 16998 this.faceVertCount = 3; 16999 this.glPrimitive = null; 17000 this._attributes = {}; 17001 17002 /** @type {Array|Float32Array} */ 17003 this._vertices = []; 17004 17005 /** @type {Array} */ 17006 this.verticesIndices = []; 17007 17008 this.morphTargets = []; 17009 } 17010 17011 get vertices() 17012 { 17013 return this._vertices; 17014 } 17015 17016 set vertices(v) 17017 { 17018 this.setVertices(v); 17019 } 17020 17021 get texCoords() 17022 { 17023 const att = this.getAttribute("texCoords"); 17024 if (!att) return []; 17025 return att.data; 17026 } 17027 17028 set texCoords(v) 17029 { 17030 this.setAttribute("texCoords", v, 2); 17031 } 17032 17033 get vertexNormals() 17034 { 17035 const att = this.getAttribute("vertexNormals"); 17036 if (!att) return []; 17037 return att.data; 17038 } 17039 17040 set vertexNormals(v) 17041 { 17042 this.setAttribute("vertexNormals", v, 3); 17043 } 17044 17045 get tangents() 17046 { 17047 const att = this.getAttribute("tangents"); 17048 if (!att) return []; 17049 return att.data; 17050 } 17051 17052 set tangents(v) 17053 { 17054 this.setAttribute("tangents", v, 3); 17055 } 17056 17057 get biTangents() 17058 { 17059 const att = this.getAttribute("biTangents"); 17060 if (!att) return []; 17061 return att.data; 17062 } 17063 17064 set biTangents(v) 17065 { 17066 this.setAttribute("biTangents", v, 3); 17067 } 17068 17069 get vertexColors() 17070 { 17071 const att = this.getAttribute("vertexColors"); 17072 if (!att) return []; 17073 return att.data; 17074 } 17075 17076 set vertexColors(v) 17077 { 17078 this.setAttribute("vertexColors", v, 4); 17079 } 17080 17081 /** 17082 * @description clear all buffers/set them to length 0 17083 */ 17084 clear() 17085 { 17086 this._vertices = new Float32Array([]); 17087 this.verticesIndices = []; 17088 this.texCoords = new Float32Array([]); 17089 this.vertexNormals = new Float32Array([]); 17090 this.tangents = []; 17091 this.biTangents = []; 17092 this._attributes = {}; 17093 } 17094 17095 /** 17096 * @return {Object} returns array of attribute objects 17097 */ 17098 getAttributes() 17099 { 17100 return this._attributes; 17101 } 17102 17103 /** 17104 * @function getAttribute 17105 * @memberof Geometry 17106 * @instance 17107 * @param {String} name 17108 * @return {Object} 17109 */ 17110 getAttribute(name) 17111 { 17112 for (const i in this._attributes) 17113 { 17114 if (this._attributes[i].name == name) return this._attributes[i]; 17115 } 17116 return null; 17117 } 17118 17119 /** 17120 * @function setAttribute
17121 * @description create an attribute 17122 * @memberof Geometry 17123 * @instance 17124 * @param {String} name 17125 * @param {Array} arr 17126 * @param {Number} itemSize 17127 */ 17128 setAttribute(name, arr, itemSize) 17129 { 17130 let attrType = ""; 17131 if (!itemSize || itemSize > 4) 17132 { 17133 this._log.warn("itemsize wrong?", itemSize, name); 17134 this._log.stack("itemsize"); 17135 17136 itemSize = 3; 17137 } 17138 17139 if (itemSize == 1) attrType = "float"; 17140 else if (itemSize == 2) attrType = "vec2"; 17141 else if (itemSize == 3) attrType = "vec3"; 17142 else if (itemSize == 4) attrType = "vec4"; 17143 17144 const attr = { 17145 "name": name, 17146 "data": arr, 17147 "itemSize": itemSize, 17148 "type": attrType, 17149 }; 17150 17151 this._attributes[name] = attr; 17152 } 17153 17154 /** 17155 * @param {string} name 17156 * @param {Geometry} newgeom 17157 */ 17158 copyAttribute(name, newgeom) 17159 { 17160 const attr = this.getAttribute(name); 17161 newgeom.setAttribute(name, new Float32Array(attr.data), attr.itemSize); 17162 } 17163 17164 /** 17165 * @function setVertices 17166 * @memberof Geometry 17167 * @instance 17168 * @description set vertices 17169 * @param {Array|Float32Array} arr [x,y,z,x,y,z,...] 17170 */ 17171 setVertices(arr) 17172 { 17173 if (arr instanceof Float32Array) this._vertices = arr; 17174 else this._vertices = new Float32Array(arr); 17175 } 17176 17177 /** 17178 * set texcoords 17179 * @param {Array|Float32Array} arr [u,v,u,v,...] 17180 */ 17181 setTexCoords(arr) 17182 { 17183 if (arr instanceof Float32Array) this.texCoords = arr; 17184 else this.texCoords = new Float32Array(arr); 17185 } 17186 17187 // deprecated 17188 calcNormals(smooth) 17189 { 17190 const options = { "smooth": smooth }; 17191 this.calculateNormals(options); 17192 } 17193 17194 /** 17195 * @param {number} x 17196 * @param {number} y 17197 * @param {number} z 17198 */ 17199 flipNormals(x, y, z) 17200 { 17201 let vec = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17202 17203 if (x == undefined)x = 1; 17204 if (y == undefined)y = 1; 17205 if (z == undefined)z = 1; 17206 17207 for (let i = 0; i < this.vertexNormals.length; i += 3) 17208 { 17209 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.set(vec, 17210 this.vertexNormals[i + 0], 17211 this.vertexNormals[i + 1], 17212 this.vertexNormals[i + 2]); 17213 17214 vec[0] *= -x; 17215 vec[1] *= -y; 17216 vec[2] *= -z; 17217 17218 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.normalize(vec, vec); 17219 17220 this.vertexNormals[i + 0] = vec[0]; 17221 this.vertexNormals[i + 1] = vec[1]; 17222 this.vertexNormals[i + 2] = vec[2]; 17223 } 17224 } 17225 17226 getNumTriangles() 17227 { 17228 if (this.verticesIndices && this.verticesIndices.length) return this.verticesIndices.length / 3; 17229 return this.vertices.length / 3; 17230 } 17231 17232 /** 17233 * flip order of vertices in geom faces 17234 */ 17235 flipVertDir() 17236 { 17237 const newInd = []; 17238 newInd.length = this.verticesIndices.length; 17239 for (let i = 0; i < this.verticesIndices.length; i += 3) 17240 { 17241 newInd[i] = this.verticesIndices[i + 2]; 17242 newInd[i + 1] = this.verticesIndices[i + 1]; 17243 newInd[i + 2] = this.verticesIndices[i]; 17244 } 17245 this.verticesIndices = newInd; 17246 } 17247 17248 /** 17249 * @param {Array} verts 17250 */ 17251 setPointVertices(verts) 17252 { 17253 if (verts.length % 3 !== 0) 17254 { 17255 this._log.error("SetPointVertices: Array must be multiple of three."); 17256 return; 17257 } 17258 17259 if (!(verts instanceof Float32Array)) this.vertices = new Float32Array(verts); 17260 else this.vertices = verts; 17261 17262 if (!(this.texCoords instanceof Float32Array)) this.texCoords = new Float32Array((verts.length / 3) * 2); 17263 17264 // this.texCoords.length=verts.length/3*2; 17265 this.verticesIndices.length = verts.length / 3; 17266 // this.verticesIndices=[]; 17267 17268 for (let i = 0; i < verts.length / 3; i++) 17269 { 17270 this.verticesIndices[i] = i; 17271 this.texCoords[i * 2] = 0; 17272 this.texCoords[i * 2 + 1] = 0; 17273 } 17274 } 17275 17276 /** 17277 * merge a different geometry into the this geometry 17278 * @param {Geometry} geom 17279 */ 17280 merge(geom) 17281 { 17282 if (!geom) return; 17283 17284 if (this.isIndexed() != geom.isIndexed()) 17285 { 17286 if (this.isIndexed()) 17287 { 17288 this.unIndex(false, true); 17289 } 17290 if (geom.isIndexed()) 17291 { 17292 const g = geom.copy(); 17293 g.unIndex(false, true); 17294 geom = g; 17295 } 17296 } 17297 17298 const oldIndizesLength = this.verticesIndices.length; 17299 const vertLength = this._vertices.length / 3; 17300 17301 this.verticesIndices.length += geom.verticesIndices.length; 17302 for (let i = 0; i < geom.verticesIndices.length; i++) 17303 this.verticesIndices[oldIndizesLength + i] = geom.verticesIndices[i] + vertLength; 17304 17305 this.vertices = cables__WEBPACK_IMPORTED_MODULE_2__.float32Concat(this._vertices, geom.vertices); 17306 this.texCoords = cables__WEBPACK_IMPORTED_MODULE_2__.float32Concat(this.texCoords, geom.texCoords); 17307 this.vertexNormals = cables__WEBPACK_IMPORTED_MODULE_2__.float32Concat(this.vertexNormals, geom.vertexNormals); 17308 this.tangents = cables__WEBPACK_IMPORTED_MODULE_2__.float32Concat(this.tangents, geom.tangents); 17309 this.biTangents = cables__WEBPACK_IMPORTED_MODULE_2__.float32Concat(this.biTangents, geom.biTangents); 17310 } 17311 17312 /** 17313 * a copy of the geometry 17314 * @function copy 17315 * @memberof Geometry 17316 * @instance 17317 */ 17318 copy() 17319 { 17320 const geom = new Geometry(this.name + " copy"); 17321 geom.faceVertCount = this.faceVertCount; 17322 geom.glPrimitive = this.glPrimitive; 17323 17324 geom.setVertices(this._vertices.slice(0)); 17325 17326 if (this.verticesIndices) 17327 { 17328 geom.verticesIndices.length = this.verticesIndices.length; 17329 for (let i = 0; i < this.verticesIndices.length; i++) geom.verticesIndices[i] = this.verticesIndices[i]; 17330 } 17331 17332 for (let i in this._attributes) this.copyAttribute(i, geom); 17333 17334 geom.morphTargets.length = this.morphTargets.length; 17335 for (let i = 0; i < this.morphTargets.length; i++) geom.morphTargets[i] = this.morphTargets[i]; 17336 17337 return geom; 17338 } 17339 17340 /** 17341 * Calculaten normals 17342 * @function calculateNormals 17343 * @param {{ smooth?: any; forceZUp?: any; }} options 17344 */ 17345 calculateNormals(options = null) 17346 { 17347 // todo: should check angle of normals to get edges https://community.khronos.org/t/calculating-accurate-vertex-normals/28152 17348 options = options || {}; 17349 if (options.smooth === false) this.unIndex(); 17350 17351 const u = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17352 const v = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17353 const n = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17354 17355 function calcNormal(triangle) 17356 { 17357 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.subtract(u, triangle[0], triangle[1]); 17358 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.subtract(v, triangle[0], triangle[2]); 17359 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.cross(n, u, v); 17360 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.normalize(n, n); 17361 17362 if (options && options.forceZUp) 17363 { 17364 if (n[2] < 0) 17365 { 17366 n[0] *= -1; 17367 n[1] *= -1; 17368 n[2] *= -1; 17369 } 17370 } 17371 return n; 17372 } 17373 17374 this.getVertexVec = function (which) 17375 { 17376 const vec = [0, 0, 0]; 17377 vec[0] = this.vertices[which * 3 + 0]; 17378 vec[1] = this.vertices[which * 3 + 1]; 17379 vec[2] = this.vertices[which * 3 + 2]; 17380 return vec; 17381 }; 17382 17383 if (!(this.vertexNormals instanceof Float32Array) || this.vertexNormals.length != this.vertices.length) this.vertexNormals = new Float32Array(this.vertices.length); 17384 17385 for (let i = 0; i < this.vertices.length; i++) 17386 { 17387 this.vertexNormals[i] = 0; 17388 } 17389 17390 if (!this.isIndexed()) 17391 { 17392 const norms = []; 17393 for (let i = 0; i < this.vertices.length; i += 9) 17394 { 17395 const triangle = [[this.vertices[i + 0], this.vertices[i + 1], this.vertices[i + 2]], [this.vertices[i + 3], this.vertices[i + 4], this.vertices[i + 5]], [this.vertices[i + 6], this.vertices[i + 7], this.vertices[i + 8]]]; 17396 const nn = calcNormal(triangle); 17397 norms.push(nn[0], nn[1], nn[2], nn[0], nn[1], nn[2], nn[0], nn[1], nn[2]); 17398 } 17399 this.vertexNormals = norms; 17400 } 17401 else 17402 { 17403 const faceNormals = []; 17404 17405 faceNormals.length = Math.floor(this.verticesIndices.length / 3); 17406 17407 for (let i = 0; i < this.verticesIndices.length; i += 3) 17408 { 17409 const triangle = [this.getVertexVec(this.verticesIndices[i + 0]), this.getVertexVec(this.verticesIndices[i + 1]), this.getVertexVec(this.verticesIndices[i + 2])]; 17410 17411 faceNormals[i / 3] = calcNormal(triangle); 17412 17413 this.vertexNormals[this.verticesIndices[i + 0] * 3 + 0] += faceNormals[i / 3][0]; 17414 this.vertexNormals[this.verticesIndices[i + 0] * 3 + 1] += faceNormals[i / 3][1]; 17415 this.vertexNormals[this.verticesIndices[i + 0] * 3 + 2] += faceNormals[i / 3][2]; 17416 17417 this.vertexNormals[this.verticesIndices[i + 1] * 3 + 0] += faceNormals[i / 3][0]; 17418 this.vertexNormals[this.verticesIndices[i + 1] * 3 + 1] += faceNormals[i / 3][1]; 17419 this.vertexNormals[this.verticesIndices[i + 1] * 3 + 2] += faceNormals[i / 3][2]; 17420 17421 this.vertexNormals[this.verticesIndices[i + 2] * 3 + 0] += faceNormals[i / 3][0]; 17422 this.vertexNormals[this.verticesIndices[i + 2] * 3 + 1] += faceNormals[i / 3][1]; 17423 this.vertexNormals[this.verticesIndices[i + 2] * 3 + 2] += faceNormals[i / 3][2]; 17424 } 17425 17426 for (let i = 0; i < this.verticesIndices.length; i += 3) // faces 17427 { 17428 for (let k = 0; k < 3; k++) // triangles 17429 { 17430 const vv = [this.vertexNormals[this.verticesIndices[i + k] * 3 + 0], this.vertexNormals[this.verticesIndices[i + k] * 3 + 1], this.vertexNormals[this.verticesIndices[i + k] * 3 + 2]]; 17431 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.normalize(vv, vv); 17432 this.vertexNormals[this.verticesIndices[i + k] * 3 + 0] = vv[0]; 17433 this.vertexNormals[this.verticesIndices[i + k] * 3 + 1] = vv[1]; 17434 this.vertexNormals[this.verticesIndices[i + k] * 3 + 2] = vv[2]; 17435 } 17436 } 17437 } 17438 } 17439 17440 /** 17441 * Calculates tangents & bitangents with the help of uv-coordinates. Adapted from 17442 * Lengyel, Eric. âComputing Tangent Space Basis Vectors for an Arbitrary Meshâ. 17443 * Terathon Software 3D Graphics Library. 17444 * https://fenix.tecnico.ulisboa.pt/downloadFile/845043405449073/Tangent%20Space%20Calculation.pdf 17445 * 17446 * @function calcTangentsBitangents 17447 */ 17448 calcTangentsBitangents() 17449 { 17450 if (!this.vertices.length) 17451 { 17452 // this._log.error("Cannot calculate tangents/bitangents without vertices."); 17453 return; 17454 } 17455 if (!this.vertexNormals.length) 17456 { 17457 // this._log.error("Cannot calculate tangents/bitangents without normals."); 17458 return; 17459 } 17460 if (!this.texCoords.length) 17461 { 17462 const texCoordLength = (this.vertices.length / 3) * 2; 17463 this.texCoords = new Float32Array(texCoordLength); 17464 for (let i = 0; i < texCoordLength; i += 1) this.texCoords[i] = 0; 17465 } 17466 if (!this.verticesIndices || !this.verticesIndices.length) 17467 { 17468 // this._log.error("Cannot calculate tangents/bitangents without vertex indices."); 17469 return; 17470 } 17471 // this code assumes that we have three indices per triangle 17472 if (this.verticesIndices.length % 3 !== 0) 17473 { 17474 this._log.error("Vertex indices mismatch!"); 17475 return; 17476 } 17477 17478 const triangleCount = this.verticesIndices.length / 3; 17479 const vertexCount = this.vertices.length / 3; 17480 17481 this.tangents = new Float32Array(this.vertexNormals.length); 17482 this.biTangents = new Float32Array(this.vertexNormals.length); 17483 17484 // temporary buffers 17485 const tempVertices = []; 17486 tempVertices.length = vertexCount * 2; 17487 const v1 = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17488 const v2 = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17489 const v3 = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17490 17491 const w1 = gl_matrix__WEBPACK_IMPORTED_MODULE_3__.create(); 17492 const w2 = gl_matrix__WEBPACK_IMPORTED_MODULE_3__.create(); 17493 const w3 = gl_matrix__WEBPACK_IMPORTED_MODULE_3__.create(); 17494 17495 const sdir = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17496 const tdir = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17497 17498 // for details on calculation, see article referenced above 17499 for (let tri = 0; tri < triangleCount; tri += 1) 17500 { 17501 // indices of the three vertices for a triangle 17502 const i1 = this.verticesIndices[tri * 3]; 17503 const i2 = this.verticesIndices[tri * 3 + 1]; 17504 const i3 = this.verticesIndices[tri * 3 + 2]; 17505 17506 // vertex position as vec3 17507 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.set(v1, this.vertices[i1 * 3], this.vertices[i1 * 3 + 1], this.vertices[i1 * 3 + 2]); 17508 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.set(v2, this.vertices[i2 * 3], this.vertices[i2 * 3 + 1], this.vertices[i2 * 3 + 2]); 17509 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.set(v3, this.vertices[i3 * 3], this.vertices[i3 * 3 + 1], this.vertices[i3 * 3 + 2]); 17510 17511 // texture coordinate as vec2 17512 gl_matrix__WEBPACK_IMPORTED_MODULE_3__.set(w1, this.texCoords[i1 * 2], this.texCoords[i1 * 2 + 1]); 17513 gl_matrix__WEBPACK_IMPORTED_MODULE_3__.set(w2, this.texCoords[i2 * 2], this.texCoords[i2 * 2 + 1]); 17514 gl_matrix__WEBPACK_IMPORTED_MODULE_3__.set(w3, this.texCoords[i3 * 2], this.texCoords[i3 * 2 + 1]); 17515 17516 const x1 = v2[0] - v1[0]; 17517 const x2 = v3[0] - v1[0]; 17518 const y1 = v2[1] - v1[1]; 17519 const y2 = v3[1] - v1[1]; 17520 const z1 = v2[2] - v1[2];
17521 const z2 = v3[2] - v1[2]; 17522 17523 const s1 = w2[0] - w1[0]; 17524 const s2 = w3[0] - w1[0]; 17525 const t1 = w2[1] - w1[1]; 17526 const t2 = w3[1] - w1[1]; 17527 17528 const r = 1.0 / (s1 * t2 - s2 * t1); 17529 17530 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.set(sdir, (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); 17531 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.set(tdir, (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); 17532 17533 tempVertices[i1] = sdir; 17534 tempVertices[i2] = sdir; 17535 tempVertices[i3] = sdir; 17536 17537 tempVertices[i1 + vertexCount] = tdir; 17538 tempVertices[i2 + vertexCount] = tdir; 17539 tempVertices[i3 + vertexCount] = tdir; 17540 } 17541 17542 const normal = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17543 const tempVert = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17544 const tan = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17545 const bitan = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17546 const temp1 = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17547 const temp2 = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17548 const crossPd = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17549 const normalized = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.create(); 17550 17551 for (let vert = 0; vert < vertexCount; vert += 1) 17552 { 17553 // NOTE: some meshes don't have index 0 - n in their indexbuffer, if this is the case, skip calculation of this vertex 17554 if (!tempVertices[vert]) continue; 17555 17556 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.set(normal, this.vertexNormals[vert * 3], this.vertexNormals[vert * 3 + 1], this.vertexNormals[vert * 3 + 2]); 17557 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.set(tempVert, tempVertices[vert][0], tempVertices[vert][1], tempVertices[vert][2]); 17558 17559 // Gram-Schmidt orthagonalize 17560 const _dp = gl_matrix__WEBPACK_IMPORTED_MODULE_1__.dot(normal, tempVert); 17561 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.scale(temp1, normal, _dp); 17562 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.subtract(temp2, tempVert, temp1); 17563 17564 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.normalize(normalized, temp2); 17565 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.cross(crossPd, normal, tempVert); 17566 17567 // const intermDot = vec3.dot(crossPd, tempVertices[vert + vertexCount]); 17568 const w = 1.0;// intermDot < 0.0 ? -1.0 : 1.0; 17569 17570 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.scale(tan, normalized, 1 / w); 17571 gl_matrix__WEBPACK_IMPORTED_MODULE_1__.cross(bitan, normal, tan); 17572 17573 this.tangents[vert * 3 + 0] = tan[0]; 17574 this.tangents[vert * 3 + 1] = tan[1]; 17575 this.tangents[vert * 3 + 2] = tan[2]; 17576 this.biTangents[vert * 3 + 0] = bitan[0]; 17577 this.biTangents[vert * 3 + 1] = bitan[1]; 17578 this.biTangents[vert * 3 + 2] = bitan[2]; 17579 } 17580 } 17581 17582 isIndexed() 17583 { 17584 if (this._vertices.length == 0) return true; 17585 return this.verticesIndices.length != 0; 17586 } 17587 17588 /** 17589 * @function unIndex 17590 * @memberof Geometry 17591 * @instance 17592 * @description remove all vertex indizes, vertices array will contain 3*XYZ for every triangle 17593 * @param {boolean} reIndex 17594 * @param {boolean} dontCalcNormals 17595 */ 17596 unIndex(reIndex = false, dontCalcNormals = false) 17597 { 17598 const newVerts = []; 17599 const newIndizes = []; 17600 let count = 0; 17601 17602 for (let j in this._attributes) 17603 { 17604 const attr = this._attributes[j]; 17605 let na = []; 17606 17607 for (let i = 0; i < this.verticesIndices.length; i += 3) 17608 { 17609 for (let s = 0; s < 3; s++) 17610 { 17611 if (attr.itemSize == 3) 17612 na.push( 17613 attr.data[this.verticesIndices[i + s] * 3 + 0], 17614 attr.data[this.verticesIndices[i + s] * 3 + 1], 17615 attr.data[this.verticesIndices[i + s] * 3 + 2]); 17616 else if (attr.itemSize == 4) 17617 na.push( 17618 attr.data[this.verticesIndices[i + s] * 4 + 0], 17619 attr.data[this.verticesIndices[i + s] * 4 + 1], 17620 attr.data[this.verticesIndices[i + s] * 4 + 2], 17621 attr.data[this.verticesIndices[i + s] * 4 + 3]); 17622 else if (attr.itemSize == 2) 17623 na.push( 17624 attr.data[this.verticesIndices[i + s] * 2 + 0], 17625 attr.data[this.verticesIndices[i + s] * 2 + 1]); 17626 else if (attr.itemSize == 1) 17627 na.push( 17628 attr.data[this.verticesIndices[i + s]]); 17629 else this._log.warn("unknown attr", attr); 17630 } 17631 } 17632 this.setAttribute(attr.name, na, attr.itemSize); 17633 } 17634 17635 for (let i = 0; i < this.verticesIndices.length; i += 3) 17636 { 17637 newVerts.push( 17638 this.vertices[this.verticesIndices[i + 0] * 3 + 0], 17639 this.vertices[this.verticesIndices[i + 0] * 3 + 1], 17640 this.vertices[this.verticesIndices[i + 0] * 3 + 2]); 17641 17642 newIndizes.push(count); 17643 count++; 17644 17645 newVerts.push( 17646 this.vertices[this.verticesIndices[i + 1] * 3 + 0], 17647 this.vertices[this.verticesIndices[i + 1] * 3 + 1], 17648 this.vertices[this.verticesIndices[i + 1] * 3 + 2]); 17649 17650 newIndizes.push(count); 17651 count++; 17652 17653 newVerts.push( 17654 this.vertices[this.verticesIndices[i + 2] * 3 + 0], 17655 this.vertices[this.verticesIndices[i + 2] * 3 + 1], 17656 this.vertices[this.verticesIndices[i + 2] * 3 + 2]); 17657 17658 newIndizes.push(count); 17659 count++; 17660 } 17661 17662 this.vertices = newVerts; 17663 17664 this.verticesIndices = []; 17665 if (reIndex) this.verticesIndices = newIndizes; 17666 17667 if (!dontCalcNormals) this.calculateNormals(); 17668 } 17669 17670 calcBarycentric() 17671 { 17672 let barycentrics = []; 17673 barycentrics.length = this.vertices.length; 17674 for (let i = 0; i < this.vertices.length; i++) barycentrics[i] = 0; 17675 17676 let count = 0; 17677 for (let i = 0; i < this.vertices.length; i += 3) 17678 { 17679 barycentrics[i + count] = 1; 17680 count++; 17681 if (count == 3) count = 0; 17682 } 17683 17684 this.setAttribute("attrBarycentric", barycentrics, 3); 17685 } 17686 17687 getBounds() 17688 { 17689 return new _cg_boundingbox_js__WEBPACK_IMPORTED_MODULE_4__.BoundingBox(this); 17690 } 17691 17692 /** 17693 * @param {boolean} x 17694 * @param {boolean} y 17695 * @param {boolean} z 17696 * @returns {Array} offset 17697 */ 17698 center(x, y, z) 17699 { 17700 if (x === undefined) 17701 { 17702 x = true; 17703 y = true; 17704 z = true; 17705 } 17706 17707 let i = 0; 17708 const bounds = this.getBounds();
17709 const offset = [bounds.minX + (bounds.maxX - bounds.minX) / 2, bounds.minY + (bounds.maxY - bounds.minY) / 2, bounds.minZ + (bounds.maxZ - bounds.minZ) / 2]; 17710 17711 for (i = 0; i < this.vertices.length; i += 3) 17712 { 17713 if (this.vertices[i + 0] == this.vertices[i + 0]) 17714 { 17715 if (x) this.vertices[i + 0] -= offset[0]; 17716 if (y) this.vertices[i + 1] -= offset[1]; 17717 if (z) this.vertices[i + 2] -= offset[2]; 17718 } 17719 } 17720 17721 return offset; 17722 } 17723 17724 mapTexCoords2d() 17725 { 17726 const bounds = this.getBounds(); 17727 const num = this.vertices.length / 3; 17728 17729 this.texCoords = new Float32Array(num * 2); 17730 17731 for (let i = 0; i < num; i++) 17732 { 17733 const vertX = this.vertices[i * 3 + 0]; 17734 const vertY = this.vertices[i * 3 + 1]; 17735 this.texCoords[i * 2 + 0] = vertX / (bounds.maxX - bounds.minX) + 0.5; 17736 this.texCoords[i * 2 + 1] = 1.0 - vertY / (bounds.maxY - bounds.minY) + 0.5; 17737 } 17738 } 17739 17740 getInfoOneLine() 17741 { 17742 let txt = ""; 17743 if (this.faceVertCount == 3 && this.verticesIndices)txt += this.verticesIndices.length / 3; 17744 else txt += 0; 17745 17746 txt += " tris "; 17747 17748 if (this.vertices)txt += this.vertices.length / 3; 17749 else txt += 0; 17750 17751 txt += " verts"; 17752 17753 return txt; 17754 } 17755 17756 getInfo() 17757 { 17758 const info = {}; 17759 17760 info.name = this.name; 17761 info.class = this.constructor.name; 17762 17763 if (this.faceVertCount == 3 && this.verticesIndices)info.numFaces = this.verticesIndices.length / 3; 17764 else info.numFaces = 0; 17765 17766 if (this.verticesIndices && this.verticesIndices.length)info.indices = this.verticesIndices.length; 17767 17768 if (this.vertices)info.numVerts = this.vertices.length / 3; 17769 else info.numVerts = 0; 17770 17771 if (this.vertexNormals) info.numNormals = this.vertexNormals.length / 3; 17772 else info.numNormals = 0; 17773 17774 if (this.texCoords) info.numTexCoords = this.texCoords.length / 2; 17775 else info.numTexCoords = 0; 17776 17777 if (this.tangents) info.numTangents = this.tangents.length / 3; 17778 else info.numTangents = 0; 17779 17780 if (this.biTangents) info.numBiTangents = this.biTangents.length / 3; 17781 else info.numBiTangents = 0; 17782 17783 if (this.biTangents) info.numBiTangents = this.biTangents.length / 3; 17784 else info.numBiTangents = 0; 17785 17786 if (this.vertexColors) info.numVertexColors = this.vertexColors.length / 4; 17787 else info.numVertexColors = 0; 17788 17789 if (this.getAttributes()) info.numAttribs = Object.keys(this.getAttributes()).length; 17790 else info.numAttribs = 0; 17791 17792 info.isIndexed = this.isIndexed(); 17793 17794 return info; 17795 } 17796 17797 // ----------------- 17798} 17799 17800// TODO : rewritwe circle op 1 17801/** @deprecated */ 17802Geometry.buildFromFaces = function (arr, name, optimize) 17803{ 17804 const vertices = []; 17805 const verticesIndices = []; 17806 17807 for (let i = 0; i < arr.length; i += 3) 17808 { 17809 const a = arr[i + 0]; 17810 const b = arr[i + 1]; 17811 const c = arr[i + 2]; 17812 const face = [-1, -1, -1]; 17813 17814 if (optimize) 17815 for (let iv = 0; iv < vertices.length; iv += 3) 17816 { 17817 if (vertices[iv + 0] == a[0] && vertices[iv + 1] == a[1] && vertices[iv + 2] == a[2]) face[0] = iv / 3; 17818 if (vertices[iv + 0] == b[0] && vertices[iv + 1] == b[1] && vertices[iv + 2] == b[2]) face[1] = iv / 3; 17819 if (vertices[iv + 0] == c[0] && vertices[iv + 1] == c[1] && vertices[iv + 2] == c[2]) face[2] = iv / 3; 17820 } 17821 17822 if (face[0] == -1) 17823 { 17824 vertices.push(a[0], a[1], a[2]); 17825 face[0] = (vertices.length - 1) / 3; 17826 } 17827 17828 if (face[1] == -1) 17829 { 17830 vertices.push(b[0], b[1], b[2]); 17831 face[1] = (vertices.length - 1) / 3; 17832 } 17833 17834 if (face[2] == -1) 17835 { 17836 vertices.push(c[0], c[1], c[2]); 17837 face[2] = (vertices.length - 1) / 3; 17838 } 17839 17840 verticesIndices.push(face[0]); 17841 verticesIndices.push(face[1]); 17842 verticesIndices.push(face[2]); 17843 } 17844 17845 const geom = new Geometry(name); 17846 geom.name = name; 17847 geom.vertices = vertices; 17848 geom.verticesIndices = verticesIndices; 17849 17850 return geom; 17851}; 17852 17853 17854/***/ }), 17855
17856/***/ "./src/corelibs/cg/cg_matrixstack.js": 17857/*!*******************************************!*\ 17858 !*** ./src/corelibs/cg/cg_matrixstack.js ***! 17859 \*******************************************/ 17860/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 17861 17862"use strict"; 17863/* harmony export */ __webpack_require__.d(__webpack_exports__, { 17864/* harmony export */ MatrixStack: () => (/* binding */ MatrixStack) 17865/* harmony export */ }); 17866/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/mat4.js"); 17867 17868 17869class MatrixStack 17870{ 17871 constructor() 17872 { 17873 this._arr = [gl_matrix__WEBPACK_IMPORTED_MODULE_0__.create()]; 17874 this._index = 0; 17875 this.stateCounter = 0; 17876 } 17877 17878 /** 17879 * @param {mat4} m 17880 */ 17881 push(m) 17882 { 17883 this._index++; 17884 this.stateCounter++; 17885 17886 if (this._index == this._arr.length) 17887 { 17888 const copy = gl_matrix__WEBPACK_IMPORTED_MODULE_0__.create(); 17889 this._arr.push(copy); 17890 } 17891 17892 gl_matrix__WEBPACK_IMPORTED_MODULE_0__.copy(this._arr[this._index], m || this._arr[this._index - 1]); 17893 17894 return this._arr[this._index]; 17895 } 17896 17897 pop() 17898 { 17899 this.stateCounter++; 17900 17901 this._index--; 17902 if (this._index < 0) this._index = 0; 17903 17904 return this._arr[this._index]; 17905 } 17906 17907 length() 17908 { 17909 return this._index; 17910 } 17911} 17912 17913 17914/***/ }), 17915
17916/***/ "./src/corelibs/cg/cg_mesh.js": 17917/*!************************************!*\ 17918 !*** ./src/corelibs/cg/cg_mesh.js ***! 17919 \************************************/ 17920/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 17921 17922"use strict"; 17923/* harmony export */ __webpack_require__.d(__webpack_exports__, { 17924/* harmony export */ CgMesh: () => (/* binding */ CgMesh) 17925/* harmony export */ }); 17926class CgMesh 17927{ 17928 _name = "unknown"; 17929 17930 constructor() 17931 { 17932 } 17933 17934} 17935 17936 17937/***/ }), 17938
17939/***/ "./src/corelibs/cg/cg_shader.js": 17940/*!**************************************!*\ 17941 !*** ./src/corelibs/cg/cg_shader.js ***! 17942 \**************************************/ 17943/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 17944 17945"use strict"; 17946/* harmony export */ __webpack_require__.d(__webpack_exports__, { 17947/* harmony export */ CgShader: () => (/* binding */ CgShader) 17948/* harmony export */ }); 17949/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/eventtarget.js"); 17950/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cables */ "./src/core/utils.js"); 17951 17952 17953 17954/** 17955 * @typedef ShaderModule 17956 * @property {String} title 17957 * @property {String} name 17958 * @property {Number} id 17959 * @property {Number} numId 17960 * @property {String} group 17961 * @property {String} prefix 17962 * @property {Number} priority 17963 * @property {Number} num 17964 * @property {String} attributes 17965 * @property {String} srcBodyFrag 17966 * @property {String} srcBodyVert 17967 * @property {String} srcHeadFrag 17968 * @property {String} srcHeadVert 17969 */ 17970 17971class CgShader extends cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"] 17972{ 17973 id = cables__WEBPACK_IMPORTED_MODULE_1__.simpleId(); 17974 _isValid = true; 17975 17976 /** @type {Array<Array<String>>} */ 17977 _defines = []; 17978 17979 /** @type {Array<String>} */ 17980 _moduleNames = []; 17981 17982 _moduleNumId = 0; 17983 _needsRecompile = true; 17984 _compileReason = "initial"; 17985 17986 /** @type {Array<ShaderModule>} */ 17987 _modules = []; 17988 17989 _compileCount = 0; 17990 17991 logError = true; 17992 num = -1; 17993 lastCompile = 0; 17994 17995 constructor() 17996 { 17997 super(); 17998 } 17999 18000 /** 18001 * @param {string} reason 18002 */ 18003 setWhyCompile(reason) 18004 { 18005 this._compileReason = reason; 18006 this._needsRecompile = true; 18007 } 18008 18009 getWhyCompile() 18010 { 18011 return this._compileReason; 18012 } 18013 18014 needsRecompile() 18015 { 18016 return this._needsRecompile; 18017 } 18018 18019 /** 18020 * @param {string} name 18021 */ 18022 removeUniform(name) 18023 { 18024 for (let i = 0; i < this._uniforms.length; i++) 18025 { 18026 if (this._uniforms[i].getName() == name) 18027 { 18028 this._uniforms.splice(i, 1); 18029 } 18030 } 18031 this.setWhyCompile("remove uniform " + name); 18032 } 18033 18034 /** 18035 * @param {String} name 18036 * @param {number} stage 18037 */ 18038 hasUniformInStage(name, stage) 18039 { 18040 18041 let binding = this.defaultUniBindingFrag; 18042 if (stage == GPUShaderStage.VERTEX) binding = this.defaultUniBindingVert; 18043 if (stage == GPUShaderStage.COMPUTE) binding = this.defaultUniBindingCompute; 18044 18045 for (let i = 0; i < this._uniforms.length; i++) 18046 { 18047 18048 console.log("hasuniiiiiiiiiiiiiii", this._uniforms[i].getName(), name); 18049 if (this._uniforms[i].getName() == name) return true; 18050 } 18051 return false; 18052 } 18053 18054 /** 18055 * @param {String} name 18056 */ 18057 hasUniform(name) 18058 { 18059 } 18060 18061 /** 18062 * easily enable/disable a define without a value 18063 * @param {String} name 18064 * @param {Port|boolean} enabled value or port 18065 */ 18066 toggleDefine(name, enabled) 18067 { 18068 if (enabled && typeof (enabled) == "object" && enabled.addEventListener) // port 18069 { 18070 if (enabled.changeListener)enabled.off(enabled.changeListener); 18071 18072 enabled.onToggleDefine = (v) => 18073 { 18074 this.toggleDefine(name, v); 18075 }; 18076 18077 enabled.changeListener = enabled.on("change", enabled.onToggleDefine); 18078 enabled = enabled.get(); 18079 } 18080 18081 if (enabled) this.define(name); 18082 else this.removeDefine(name); 18083 } 18084 18085 /** 18086 * add a define to a shader, e.g. #define DO_THIS_THAT 1 18087 * @param {String} name 18088 * @param {any} value (can be empty) 18089 */ 18090 define(name, value = "") 18091 { 18092 if (value === null || value === undefined) value = ""; 18093 18094 if (typeof (value) == "object") // port 18095 { 18096 value.removeEventListener("change", value.onDefineChange); 18097 value.onDefineChange = (v) => 18098 { 18099 this.define(name, v); 18100 }; 18101 value.on("change", value.onDefineChange); 18102 18103 value = value.get(); 18104 } 18105 18106 for (let i = 0; i < this._defines.length; i++) 18107 { 18108 if (this._defines[i][0] == name && this._defines[i][1] == value) return; 18109 if (this._defines[i][0] == name) 18110 { 18111 this._defines[i][1] = value; 18112 this.setWhyCompile("define " + name + " " + value); 18113 return; 18114 } 18115 } 18116 this.setWhyCompile("define " + name + " " + value); 18117 18118 this._defines.push([name, value]); 18119 } 18120 18121 getDefines() 18122 { 18123 return this._defines; 18124 } 18125 18126 /** 18127 * @param {string} name 18128 */ 18129 getDefine(name) 18130 { 18131 for (let i = 0; i < this._defines.length; i++) 18132 if (this._defines[i][0] == name) return this._defines[i][1]; 18133 return null; 18134 } 18135 18136 /** 18137 * return true if shader has define 18138 * @function hasDefine 18139 * @memberof Shader 18140 * @instance 18141 * @param {String} name 18142 * @return {Boolean} 18143 */ 18144 hasDefine(name) 18145 { 18146 for (let i = 0; i < this._defines.length; i++) 18147 if (this._defines[i][0] == name) return true; 18148 } 18149 18150 /** 18151 * remove a define from a shader 18152 * @param {string} name 18153 */ 18154 removeDefine(name) 18155 { 18156 for (let i = 0; i < this._defines.length; i++) 18157 { 18158 if (this._defines[i][0] == name) 18159 { 18160 this._defines.splice(i, 1); 18161 this.setWhyCompile("define removed:" + name); 18162 return; 18163 } 18164 } 18165 } 18166 18167 /** 18168 * @param {any} modId 18169 */ 18170 hasModule(modId) 18171 { 18172 for (let i = 0; i < this._modules.length; i++) 18173 if (this._modules[i].id == modId) return true; 18174 18175 return false;
18176 } 18177 18178 /** 18179 * 18180 * @param {Array<String>} names 18181 */ 18182 setModules(names) 18183 { 18184 this._moduleNames = names; 18185 } 18186 18187 /** 18188 * remove a module from shader 18189 * @param {ShaderModule} mod the module to be removed 18190 */ 18191 removeModule(mod) 18192 { 18193 for (let i = 0; i < this._modules.length; i++) 18194 { 18195 if (mod && mod.id) 18196 { 18197 if (this._modules[i].id == mod.id || !this._modules[i]) 18198 { 18199 let found = true; 18200 while (found) 18201 { 18202 found = false; 18203 for (let j = 0; j < this._uniforms.length; j++) 18204 { 18205 if (this._uniforms[j].getName().startsWith(mod.prefix)) 18206 { 18207 this._uniforms.splice(j, 1); 18208 found = true; 18209 continue; 18210 } 18211 } 18212 } 18213 18214 this.setWhyCompile("remove module " + mod.title); 18215 this._modules.splice(i, 1); 18216 break; 18217 } 18218 } 18219 } 18220 } 18221 18222 getNumModules() 18223 { 18224 return this._modules.length; 18225 } 18226 18227 getCurrentModules() { return this._modules; } 18228 18229 /** 18230 * add a module 18231 * @param {ShaderModule} mod the module to be added 18232 * @param {ShaderModule} [sibling] sibling module, new module will share the same group 18233 */ 18234 addModule(mod, sibling) 18235 { 18236 if (this.hasModule(mod.id)) return; 18237 if (!mod.id) mod.id = cables__WEBPACK_IMPORTED_MODULE_1__.simpleId(); 18238 if (!mod.numId) mod.numId = this._moduleNumId; 18239 if (!mod.num)mod.num = this._modules.length; 18240 if (sibling && !sibling.group) sibling.group = cables__WEBPACK_IMPORTED_MODULE_1__.simpleId(); 18241 18242 if (!mod.group) 18243 if (sibling) mod.group = sibling.group; 18244 else mod.group = cables__WEBPACK_IMPORTED_MODULE_1__.simpleId(); 18245 18246 mod.prefix = "mod" + mod.group + "_"; 18247 this._modules.push(mod); 18248 18249 this.setWhyCompile("add module " + mod.title); 18250 this._moduleNumId++; 18251 18252 return mod; 18253 } 18254 18255 isValid() 18256 { 18257 return this._isValid; 18258 } 18259 18260} 18261 18262 18263/***/ }), 18264
18265/***/ "./src/corelibs/cg/cg_texture.js": 18266/*!***************************************!*\ 18267 !*** ./src/corelibs/cg/cg_texture.js ***! 18268 \***************************************/ 18269/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 18270 18271"use strict"; 18272/* harmony export */ __webpack_require__.d(__webpack_exports__, { 18273/* harmony export */ CgTexture: () => (/* binding */ CgTexture) 18274/* harmony export */ }); 18275/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables */ "./src/core/utils.js"); 18276 18277 18278const DEFAULT_TEXTURE_SIZE = 8; 18279 18280/** 18281 * @typedef {Object} CglTextureOptions 18282 * @property {number} [width] 18283 * @property {number} [height] 18284 * @property {string} [pixelformat] 18285 */ 18286class CgTexture 18287{ 18288 18289 /** 18290 * @param {CglTextureOptions} options={} 18291 */ 18292 constructor(options = {}) 18293 { 18294 this.id = cables__WEBPACK_IMPORTED_MODULE_0__.uuid(); 18295 this.width = 0; 18296 this.height = 0; 18297 this.name = "unknown"; 18298 18299 options = options || {}; 18300 this.pixelFormat = options.pixelFormat || CgTexture.PFORMATSTR_RGBA8UB; 18301 18302 this.name = options.name || "unknown"; 18303 18304 if (!options.width) options.width = DEFAULT_TEXTURE_SIZE; 18305 if (!options.height) options.height = DEFAULT_TEXTURE_SIZE; 18306 } 18307} 18308 18309CgTexture.getDefaultTextureData = (name, size, options = {}) => 18310{ 18311 if (name == "empty") 18312 { 18313 return new Uint8Array(size * size * 4).fill(0); 18314 } 18315 else 18316 if (name == "color") 18317 { 18318 const data = new Uint8Array(size * size * 4); 18319 let r = options.r || 1; 18320 let g = options.g || 1; 18321 let b = options.b || 1; 18322 18323 for (let x = 0; x < size * size; x++) 18324 { 18325 data[x * 4 + 0] = r; 18326 data[x * 4 + 1] = g; 18327 data[x * 4 + 2] = b; 18328 data[x * 4 + 3] = 255; 18329 } 18330 return data; 18331 } 18332 else 18333 if (name == "randomUInt") 18334 { 18335 const data = new Uint8Array(size * size * 4); 18336 18337 for (let x = 0; x < size * size; x++) 18338 { 18339 data[x * 4 + 0] = Math.random() * 255; 18340 data[x * 4 + 1] = Math.random() * 255; 18341 data[x * 4 + 2] = Math.random() * 255; 18342 data[x * 4 + 3] = 255; 18343 } 18344 return data; 18345 } 18346 else 18347 if (name == "random" || name == "randomFloat") 18348 { 18349 const data = new Float32Array(size * size * 4); 18350 18351 for (let x = 0; x < size * size; x++) 18352 { 18353 data[x * 4 + 0] = (Math.random() - 0.5) * 2.0; 18354 data[x * 4 + 1] = (Math.random() - 0.5) * 2.0; 18355 data[x * 4 + 2] = (Math.random() - 0.5) * 2.0; 18356 data[x * 4 + 3] = 1; 18357 } 18358 return data; 18359 } 18360 else 18361 if (name == "stripes") 18362 { 18363 const arr = []; 18364 18365 let r = options.r; 18366 let g = options.g; 18367 let b = options.b; 18368 18369 if (r === undefined)r = 1; 18370 if (g === undefined)g = 1; 18371 if (b === undefined)b = 1; 18372 18373 for (let y = 0; y < size; y++) 18374 { 18375 for (let x = 0; x < size; x++) 18376 { 18377 if ((x + y) % 64 < 32) 18378 { 18379 arr.push((200 + (y / size) * 25 + (x / size) * 25) * r); 18380 arr.push((200 + (y / size) * 25 + (x / size) * 25) * g); 18381 arr.push((200 + (y / size) * 25 + (x / size) * 25) * b); 18382 } 18383 else 18384 { 18385 arr.push((40 + (y / size) * 25 + (x / size) * 25) * r); 18386 arr.push((40 + (y / size) * 25 + (x / size) * 25) * g); 18387 arr.push((40 + (y / size) * 25 + (x / size) * 25) * b); 18388 } 18389 arr.push(255); 18390 } 18391 } 18392 18393 return new Uint8Array(arr); 18394 } 18395 else 18396 { 18397 console.warn("unknown default texture", name); 18398 return CgTexture.getDefaultTextureData("stripes", size, { "r": 1, "g": 0, "b": 0 }); 18399 } 18400}; 18401 18402CgTexture.FILTER_NEAREST = 0; 18403CgTexture.FILTER_LINEAR = 1; 18404CgTexture.FILTER_MIPMAP = 2; 18405 18406CgTexture.WRAP_REPEAT = 0; 18407CgTexture.WRAP_MIRRORED_REPEAT = 1; 18408CgTexture.WRAP_CLAMP_TO_EDGE = 2; 18409 18410CgTexture.TYPE_DEFAULT = 0; 18411CgTexture.TYPE_DEPTH = 1; 18412CgTexture.TYPE_FLOAT = 2; 18413 18414CgTexture.PFORMATSTR_RGB565 = "RGB 5/6/5bit ubyte"; 18415 18416CgTexture.PFORMATSTR_R8UB = "R 8bit ubyte"; 18417CgTexture.PFORMATSTR_RG8UB = "RG 8bit ubyte"; 18418CgTexture.PFORMATSTR_RGB8UB = "RGB 8bit ubyte"; 18419CgTexture.PFORMATSTR_RGBA8UB = "RGBA 8bit ubyte"; 18420 18421CgTexture.PFORMATSTR_SRGBA8 = "SRGBA 8bit ubyte"; 18422 18423CgTexture.PFORMATSTR_R11FG11FB10F = "RGB 11/11/10bit float"; 18424 18425CgTexture.PFORMATSTR_R16F = "R 16bit float"; 18426CgTexture.PFORMATSTR_RG16F = "RG 16bit float"; 18427CgTexture.PFORMATSTR_RGB16F = "RGB 16bit float"; 18428CgTexture.PFORMATSTR_RGBA16F = "RGBA 16bit float"; 18429 18430CgTexture.PFORMATSTR_R32F = "R 32bit float"; 18431CgTexture.PFORMATSTR_RG32F = "RG 32bit float"; 18432CgTexture.PFORMATSTR_RGB32F = "RGB 32bit float"; 18433CgTexture.PFORMATSTR_RGBA32F = "RGBA 32bit float"; 18434 18435CgTexture.PFORMATSTR_DEPTH = "DEPTH"; 18436 18437CgTexture.PIXELFORMATS = [ 18438 18439 CgTexture.PFORMATSTR_RGB565, 18440 18441 CgTexture.PFORMATSTR_R8UB, 18442 CgTexture.PFORMATSTR_RG8UB, 18443 CgTexture.PFORMATSTR_RGB8UB, 18444 CgTexture.PFORMATSTR_RGBA8UB, 18445 18446 CgTexture.PFORMATSTR_SRGBA8, 18447 18448 CgTexture.PFORMATSTR_R11FG11FB10F, 18449 CgTexture.PFORMATSTR_R16F, 18450 CgTexture.PFORMATSTR_RG16F, 18451 CgTexture.PFORMATSTR_RGBA16F, 18452 18453 CgTexture.PFORMATSTR_R32F, 18454 CgTexture.PFORMATSTR_RGBA32F 18455 18456]; 18457 18458 18459/***/ }), 18460
18461/***/ "./src/corelibs/cg/cg_uniform.js": 18462/*!***************************************!*\ 18463 !*** ./src/corelibs/cg/cg_uniform.js ***! 18464 \***************************************/ 18465/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 18466 18467"use strict"; 18468/* harmony export */ __webpack_require__.d(__webpack_exports__, { 18469/* harmony export */ CgUniform: () => (/* binding */ CgUniform) 18470/* harmony export */ }); 18471/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 18472/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cables */ "./src/core/core_port.js"); 18473 18474 18475 18476 18477 18478 18479class CgUniform 18480{ 18481 18482 /** 18483 * Description 18484 * @param {CgShader|CgpShader|Shader} __shader 18485 * @param {string} __type 18486 * @param {string} __name 18487 * @param {Number|Port} _value 18488 * @param {Port} _port2 18489 * @param {Port} _port3 18490 * @param {Port} _port4 18491 */ 18492 constructor(__shader, __type, __name, _value, _port2, _port3, _port4, _structUniformName, _structName, _propertyName) 18493 { 18494 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"]("cg_uniform"); 18495 this._type = __type; 18496 this._name = __name; 18497 18498 /** @type {CgShader} */ 18499 this._shader = __shader; 18500 this._value = 0.00001; 18501 this._oldValue = null; 18502 this._port = null; 18503 18504 this._structName = _structName; 18505 this._structUniformName = _structUniformName; 18506 this._propertyName = _propertyName; 18507 18508 if (this._shader._addUniform) this._shader._addUniform(this); 18509 this.needsUpdate = true; 18510 this.shaderType = null; 18511 this.comment = null; 18512 18513 if (__type == "f") 18514 { 18515 this.set = this.setValue = this.setValueF.bind(this); 18516 this.updateValue = this.updateValueF.bind(this); 18517 } 18518 else if (__type == "f[]") 18519 { 18520 this.set = this.setValue = this.setValueArrayF.bind(this); 18521 this.updateValue = this.updateValueArrayF.bind(this); 18522 } 18523 else if (__type == "2f[]") 18524 { 18525 this.set = this.setValue = this.setValueArray2F.bind(this); 18526 this.updateValue = this.updateValueArray2F.bind(this); 18527 } 18528 else if (__type == "3f[]") 18529 { 18530 this.set = this.setValue = this.setValueArray3F.bind(this); 18531 this.updateValue = this.updateValueArray3F.bind(this); 18532 } 18533 else if (__type == "4f[]") 18534 { 18535 this.set = this.setValue = this.setValueArray4F.bind(this); 18536 this.updateValue = this.updateValueArray4F.bind(this); 18537 } 18538 else if (__type == "i") 18539 { 18540 this.set = this.setValue = this.setValueI.bind(this); 18541 this.updateValue = this.updateValueI.bind(this); 18542 } 18543 else if (__type == "2i") 18544 { 18545 this.set = this.setValue = this.setValue2I.bind(this); 18546 this.updateValue = this.updateValue2I.bind(this); 18547 } 18548 else if (__type == "3i") 18549 { 18550 this.set = this.setValue = this.setValue3I.bind(this); 18551 this.updateValue = this.updateValue3I.bind(this); 18552 } 18553 else if (__type == "4i") 18554 { 18555 this.set = this.setValue = this.setValue4I.bind(this); 18556 this.updateValue = this.updateValue4I.bind(this); 18557 } 18558 else if (__type == "b") 18559 { 18560 this.set = this.setValue = this.setValueBool.bind(this); 18561 this.updateValue = this.updateValueBool.bind(this); 18562 } 18563 else if (__type == "4f") 18564 { 18565 this.set = this.setValue = this.setValue4F.bind(this); 18566 this.updateValue = this.updateValue4F.bind(this); 18567 } 18568 else if (__type == "3f") 18569 { 18570 this.set = this.setValue = this.setValue3F.bind(this); 18571 this.updateValue = this.updateValue3F.bind(this); 18572 } 18573 else if (__type == "2f") 18574 { 18575 this.set = this.setValue = this.setValue2F.bind(this);
18576 this.updateValue = this.updateValue2F.bind(this); 18577 } 18578 else if (__type == "t") 18579 { 18580 this.set = this.setValue = this.setValueT.bind(this); 18581 this.updateValue = this.updateValueT.bind(this); 18582 } 18583 else if (__type == "sampler") 18584 { 18585 if (this.setValueAny) 18586 { 18587 this.set = this.setValue = this.setValueAny.bind(this); 18588 this.updateValue = this.updateValueAny.bind(this); 18589 } 18590 } 18591 else if (__type == "tc") 18592 { 18593 this.set = this.setValue = this.setValueT.bind(this); 18594 this.updateValue = this.updateValueT.bind(this); 18595 } 18596 else if (__type == "t[]") 18597 { 18598 this.set = this.setValue = this.setValueArrayT.bind(this); 18599 this.updateValue = this.updateValueArrayT.bind(this); 18600 } 18601 else if (__type == "m4" || __type == "m4[]") 18602 { 18603 this.set = this.setValue = this.setValueM4.bind(this); 18604 this.updateValue = this.updateValueM4.bind(this); 18605 } 18606 else 18607 { 18608 // console.error("unknown"); 18609 this._log.error("Unknown uniform type " + __type, __name, typeof this._shader); 18610 } 18611 18612 if (typeof _value == "object" && _value instanceof cables__WEBPACK_IMPORTED_MODULE_1__.Port) 18613 { 18614 this._port = _value; 18615 this._value = this._port.get(); 18616 18617 if (_port2 && _port3 && _port4) 18618 { 18619 if (!(_port2 instanceof cables__WEBPACK_IMPORTED_MODULE_1__.Port) || !(_port3 instanceof cables__WEBPACK_IMPORTED_MODULE_1__.Port) || !(_port4 instanceof cables__WEBPACK_IMPORTED_MODULE_1__.Port)) 18620 { 18621 this._log.error("[cgl_uniform] mixed port/value parameter for vec4 ", this._name); 18622 } 18623 18624 this._value = [0, 0, 0, 0]; 18625 this._port2 = _port2; 18626 this._port3 = _port3; 18627 this._port4 = _port4; 18628 18629 this._port.on("change", this.updateFromPort4f.bind(this)); 18630 this._port2.on("change", this.updateFromPort4f.bind(this)); 18631 this._port3.on("change", this.updateFromPort4f.bind(this)); 18632 this._port4.on("change", this.updateFromPort4f.bind(this)); 18633 18634 // this._port.onChange = this._port2.onChange = this._port3.onChange = this._port4.onChange = this.updateFromPort4f.bind(this); 18635 this.updateFromPort4f(); 18636 } 18637 else if (_port2 && _port3) 18638 { 18639 if (!(_port2 instanceof cables__WEBPACK_IMPORTED_MODULE_1__.Port) || !(_port3 instanceof cables__WEBPACK_IMPORTED_MODULE_1__.Port)) 18640 { 18641 this._log.error("[cgl_uniform] mixed port/value parameter for vec4 ", this._name); 18642 } 18643 18644 this._value = [0, 0, 0]; 18645 this._port2 = _port2; 18646 this._port3 = _port3; 18647 // this._port.onChange = this._port2.onChange = this._port3.onChange = this.updateFromPort3f.bind(this); 18648 this._port.on("change", this.updateFromPort3f.bind(this)); 18649 this._port2.on("change", this.updateFromPort3f.bind(this)); 18650 this._port3.on("change", this.updateFromPort3f.bind(this)); 18651 18652 this.updateFromPort3f(); 18653 } 18654 else if (_port2) 18655 { 18656 if (!(_port2 instanceof cables__WEBPACK_IMPORTED_MODULE_1__.Port)) 18657 { 18658 this._log.error("[cgl_uniform] mixed port/value parameter for vec4 ", this._name); 18659 } 18660 18661 this._value = [0, 0]; 18662 this._port2 = _port2; 18663 // this._port.onChange = this._port2.onChange = this.updateFromPort2f.bind(this); 18664 this._port.on("change", this.updateFromPort2f.bind(this)); 18665 this._port2.on("change", this.updateFromPort2f.bind(this)); 18666 18667 this.updateFromPort2f(); 18668 } 18669 else 18670 { 18671 // this._port.on = this.updateFromPort.bind(this); 18672 this._port.on("change", this.updateFromPort.bind(this)); 18673 } 18674 } 18675 else this._value = _value; 18676 18677 if (this._value == undefined) 18678 { 18679 this._value = 0; 18680 } 18681 18682 this.setValue(this._value); 18683 18684 this.needsUpdate = true; 18685 } 18686 18687 getType() 18688 { 18689 return this._type; 18690 } 18691
18692 get type() 18693 { 18694 return this._type; 18695 } 18696 18697 get name() 18698 { 18699 return this._name; 18700 } 18701 18702 getName() 18703 { 18704 return this._name; 18705 } 18706 18707 getValue() 18708 { 18709 return this._value; 18710 } 18711 18712 getShaderType() 18713 { 18714 return this.shaderType; 18715 } 18716 18717 isStructMember() 18718 { 18719 return !!this._structName; 18720 } 18721 18722 updateFromPort4f() 18723 { 18724 this._value[0] = this._port.get(); 18725 this._value[1] = this._port2.get(); 18726 this._value[2] = this._port3.get(); 18727 this._value[3] = this._port4.get(); 18728 this.setValue(this._value); 18729 } 18730 18731 updateFromPort3f() 18732 { 18733 this._value[0] = this._port.get(); 18734 this._value[1] = this._port2.get(); 18735 this._value[2] = this._port3.get(); 18736 this.setValue(this._value); 18737 } 18738 18739 updateFromPort2f() 18740 { 18741 this._value[0] = this._port.get(); 18742 this._value[1] = this._port2.get(); 18743 this.setValue(this._value); 18744 } 18745 18746 updateFromPort() 18747 { 18748 this.setValue(this._port.get()); 18749 } 18750 18751 get port() 18752 { 18753 return this._port; 18754 } 18755} 18756 18757 18758/***/ }), 18759
18760/***/ "./src/corelibs/cg/index.js": 18761/*!**********************************!*\ 18762 !*** ./src/corelibs/cg/index.js ***! 18763 \**********************************/ 18764/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 18765 18766"use strict"; 18767/* unused harmony export CG */ 18768/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/common.js"); 18769/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/mat2.js"); 18770/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/mat2d.js"); 18771/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/mat3.js"); 18772/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/mat4.js"); 18773/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/quat.js"); 18774/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/quat2.js"); 18775/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/vec2.js"); 18776/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/vec3.js"); 18777/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/vec4.js"); 18778/* harmony import */ var _cg_boundingbox_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cg_boundingbox.js */ "./src/corelibs/cg/cg_boundingbox.js"); 18779/* harmony import */ var _cg_canvas_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./cg_canvas.js */ "./src/corelibs/cg/cg_canvas.js"); 18780/* harmony import */ var _cg_geom_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./cg_geom.js */ "./src/corelibs/cg/cg_geom.js"); 18781/* harmony import */ var _cg_fpscounter_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./cg_fpscounter.js */ "./src/corelibs/cg/cg_fpscounter.js"); 18782 18783 18784 18785 18786 18787 18788 18789 18790 18791 18792 18793 18794const CG = { 18795 18796 "DEPTH_COMPARE_NEVER": 0, 18797 "DEPTH_COMPARE_LESS": 1, 18798 "DEPTH_COMPARE_EQUAL": 2, 18799 "DEPTH_COMPARE_LESSEQUAL": 3, 18800 "DEPTH_COMPARE_GREATER": 4, 18801 "DEPTH_COMPARE_NOTEQUAL": 5, 18802 "DEPTH_COMPARE_GREATEREQUAL": 6, 18803 "DEPTH_COMPARE_ALWAYS": 7, 18804 18805 "CULL_NONE": 0, 18806 "CULL_BACK": 1, 18807 "CULL_FRONT": 2, 18808 "CULL_BOTH": 3, 18809 18810 "Geometry": _cg_geom_js__WEBPACK_IMPORTED_MODULE_0__.Geometry, 18811 "BoundingBox": _cg_boundingbox_js__WEBPACK_IMPORTED_MODULE_1__.BoundingBox, 18812 "FpsCounter": _cg_fpscounter_js__WEBPACK_IMPORTED_MODULE_2__.FpsCounter, 18813 18814 "CgCanvas": _cg_canvas_js__WEBPACK_IMPORTED_MODULE_3__.CgCanvas 18815}; 18816 18817window.CABLES = window.CABLES || {}; 18818window.CABLES.CG = window.CABLES.CG || CG; 18819window.CG = window.CG || CG; 18820 18821window.glMatrix = gl_matrix__WEBPACK_IMPORTED_MODULE_4__; 18822window.mat2 = gl_matrix__WEBPACK_IMPORTED_MODULE_5__; 18823window.mat2d = gl_matrix__WEBPACK_IMPORTED_MODULE_6__; 18824window.mat3 = gl_matrix__WEBPACK_IMPORTED_MODULE_7__; 18825window.mat4 = gl_matrix__WEBPACK_IMPORTED_MODULE_8__; 18826window.quat = gl_matrix__WEBPACK_IMPORTED_MODULE_9__; 18827window.quat2 = gl_matrix__WEBPACK_IMPORTED_MODULE_10__; 18828window.vec2 = gl_matrix__WEBPACK_IMPORTED_MODULE_11__; 18829 18830window.vec3 = gl_matrix__WEBPACK_IMPORTED_MODULE_12__; 18831window.vec4 = gl_matrix__WEBPACK_IMPORTED_MODULE_13__; 18832 18833 18834 18835 18836/***/ }), 18837
18838/***/ "./src/corelibs/cgl/cgl_mesh.js": 18839/*!**************************************!*\ 18840 !*** ./src/corelibs/cgl/cgl_mesh.js ***! 18841 \**************************************/ 18842/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 18843 18844"use strict"; 18845/* harmony export */ __webpack_require__.d(__webpack_exports__, { 18846/* harmony export */ MESH: () => (/* binding */ MESH), 18847/* harmony export */ Mesh: () => (/* binding */ Mesh) 18848/* harmony export */ }); 18849/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 18850/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cables */ "./src/core/utils.js"); 18851/* harmony import */ var _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./cgl_shader_uniform.js */ "./src/corelibs/cgl/cgl_shader_uniform.js"); 18852/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants.js */ "./src/corelibs/cgl/constants.js"); 18853/* harmony import */ var _cg_cg_mesh_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../cg/cg_mesh.js */ "./src/corelibs/cg/cg_mesh.js"); 18854 18855 18856 18857 18858 18859 18860 18861 18862 18863 18864 18865const MESH = {}; 18866MESH.lastMesh = null; 18867 18868/** 18869 * @typedef {Object} CglMeshAttributeOptions 18870 * @property {boolean} [instanced] 18871 * @property {Function} [cb] 18872 * @property {Function} [type] 18873 */ 18874 18875/** 18876 * @type Object 18877 * @typedef CglMeshOptions 18878 * @property {Number} [glPrimitive] 18879 * @property {String} [opId] 18880 */ 18881 18882/** 18883 * webgl renderable 3d object 18884 * @class 18885 * @namespace external:CGL 18886 * @hideconstructor 18887 * @example 18888 * const cgl=this._cgl 18889 * const mesh=new CGL.Mesh(cgl, geometry); 18890 * 18891 * function render() 18892 * { 18893 * mesh.render(cgl.getShader()); 18894 * } 18895 * 18896 */ 18897class Mesh extends _cg_cg_mesh_js__WEBPACK_IMPORTED_MODULE_0__.CgMesh 18898{ 18899 18900 /** @type {CglContext} */ 18901 #cgl = null; 18902 18903 /** @type {Geometry} */ 18904 #geom = null; 18905 18906 /** @type {WebGLBuffer} */ 18907 #bufVerticesIndizes = null; 18908 18909 /** 18910 * @param {CglContext} _cgl cgl 18911 * @param {Geometry} __geom geometry 18912 * @param {CglMeshOptions} _options 18913 */ 18914 constructor(_cgl, __geom, _options = {}) 18915 { 18916 super(); 18917 this.#cgl = _cgl; 18918 18919 let options = _options || {}; 18920 if (cables__WEBPACK_IMPORTED_MODULE_1__.isNumeric(options))options = { "glPrimitive": _options }; // old constructor fallback... 18921 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_2__["default"]("cgl_mesh"); 18922 this._bufVertexAttrib = null; 18923 this.#bufVerticesIndizes = this.#cgl.gl.createBuffer(); 18924 this._indexType = this.#cgl.gl.UNSIGNED_SHORT; 18925 this._attributes = []; 18926 this._attribLocs = {}; 18927 18928 this._lastShader = null; 18929 this._numInstances = 0; 18930 this._glPrimitive = options.glPrimitive; 18931 18932 this.opId = options.opId || ""; 18933 this._preWireframeGeom = null; 18934 this.addVertexNumbers = false; 18935 18936 this.feedBackAttributes = []; 18937 this.setGeom(__geom); 18938 18939 this._feedBacks = []; 18940 this._feedBacksChanged = false; 18941 this._transformFeedBackLoc = -1; 18942 this._lastAttrUpdate = 0; 18943 18944 this.memFreed = false; 18945 18946 this.#cgl.profileData.addHeavyEvent("mesh constructed", this._name); 18947 18948 this._queryExt = null; 18949 } 18950 18951 get geom() 18952 { 18953 return this.#geom; 18954 } 18955 18956 get numInstances() 18957 { 18958 return this._numInstances; 18959 } 18960 18961 set numInstances(v) 18962 { 18963 this.setNumInstances(v); 18964 } 18965 18966 freeMem() 18967 { 18968 this.memFreed = true; 18969 18970 for (let i = 0; i < this._attributes.length; i++) 18971 this._attributes[i].floatArray = null; 18972 } 18973 18974 /** 18975 * @function updateVertices 18976 * @memberof Mesh 18977 * @instance 18978 * @description update vertices only from a geometry 18979 * @param {Geometry} geom 18980 */ 18981 updateVertices(geom) 18982 { 18983 this.setAttribute(_constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_VERTEX_POSITION, geom.vertices, 3); 18984 this._numVerts = geom.vertices.length / 3; 18985 } 18986 18987 /** 18988 * @param {String} attrName 18989 * @param {String} name 18990 * @param {Number} stride 18991 * @param {Number} offset 18992 */ 18993 setAttributePointer(attrName, name, stride, offset) 18994 { 18995 for (let i = 0; i < this._attributes.length; i++) 18996 { 18997 if (this._attributes[i].name == attrName) 18998 { 18999 if (!this._attributes[i].pointer) this._attributes[i].pointer = []; 19000 19001 this._attributes[i].pointer.push( 19002 { 19003 "loc": -1, 19004 "name": name, 19005 "stride": stride, 19006 "offset": offset, 19007 "instanced": attrName == _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_INSTANCE_MMATRIX, 19008 } 19009 ); 19010 } 19011 } 19012 } 19013 19014 /** 19015 * @param {String} name 19016 * @returns {AttributeObject} 19017 */ 19018 getAttribute(name) 19019 { 19020 for (let i = 0; i < this._attributes.length; i++) if (this._attributes[i].name == name) return this._attributes[i]; 19021 } 19022 19023 setAttributeRange(attr, array, start, end) 19024 { 19025 if (!attr) return; 19026 if (!start && !end) return; 19027 19028 if (!attr.name) 19029 this._log.stack("no attrname?!"); 19030 19031 const gl = this.#cgl.gl; 19032 19033 gl.bindBuffer(gl.ARRAY_BUFFER, attr.buffer); 19034 this.#cgl.profileData.profileMeshAttributes += (end - start) || 0; 19035 19036 this.#cgl.profileData.profileSingleMeshAttribute[this._name] = this.#cgl.profileData.profileSingleMeshAttribute[this._name] || 0; 19037 this.#cgl.profileData.profileSingleMeshAttribute[this._name] += (end - start) || 0; 19038 19039 if (attr.numItems < array.length / attr.itemSize) 19040 { 19041 this._resizeAttr(array, attr); 19042 } 19043 19044 if (end > array.length && !this.warned) 19045 { 19046 this.warned = true; 19047 this._log.warn(this.#cgl.canvas.id + " " + attr.name + " buffersubdata out of bounds ?", array.length, end, start, attr); 19048 return; 19049 } 19050 19051 // if (glVersion == 1) gl.bufferSubData(gl.ARRAY_BUFFER, 0, array); // probably slow/ maybe create and array with only changed size ?? 19052 // else 19053 gl.bufferSubData(gl.ARRAY_BUFFER, start * 4, array, start, (end - start)); 19054 } 19055 19056 _resizeAttr(array, attr) 19057 { 19058 const gl = this.#cgl.gl; 19059 19060 if (attr.buffer) 19061 gl.deleteBuffer(attr.buffer); 19062 19063 attr.buffer = gl.createBuffer(); 19064 gl.bindBuffer(gl.ARRAY_BUFFER, attr.buffer); 19065 this._bufferArray(array, attr); 19066 attr.numItems = array.length / attr.itemSize;// numItems; 19067 } 19068 19069 _bufferArray(array, attr) 19070 { 19071 let floatArray = attr.floatArray || null; 19072 if (!array) return; 19073 19074 if (this.#cgl.debugOneFrame) 19075 { 19076 console.log("_bufferArray", array.length, attr.name); // eslint-disable-line 19077 } 19078 19079 if (!(array instanceof Float32Array)) 19080 { 19081 if (attr && floatArray && floatArray.length == array.length) 19082 { 19083 floatArray.set(array); 19084 } 19085 else 19086 { 19087 floatArray = new Float32Array(array); 19088 19089 if (this.#cgl.debugOneFrame) 19090 { 19091 console.log("_bufferArray create new float32array", array.length, attr.name); // eslint-disable-line 19092 } 19093 19094 if (array.length > 10000) 19095 { 19096 this.#cgl.profileData.profileNonTypedAttrib++; 19097 this.#cgl.profileData.profileNonTypedAttribNames = "(" + this._name + ":" + attr.name + ")"; 19098 } 19099 } 19100 } 19101 else floatArray = array; 19102 19103 attr.arrayLength = floatArray.length; 19104 attr.floatArray = null;// floatArray; 19105 19106 this.#cgl.gl.bufferData(this.#cgl.gl.ARRAY_BUFFER, floatArray, this.#cgl.gl.DYNAMIC_DRAW); 19107 } 19108 19109 /** 19110 * @function setAttribute
19111 * @description update attribute 19112 * @memberof Mesh 19113 * @instance 19114 * @param {String} name 19115 * @param {Array} array 19116 * @param {Number} itemSize 19117 * @param {Object} options 19118 */ 19119 addAttribute(name, array, itemSize, options) 19120 { 19121 this.setAttribute(name, array, itemSize, options); 19122 } 19123 19124 /** 19125 * @param {String} name 19126 * @param {Array|Float32Array} array 19127 * @param {Number} itemSize Integer 19128 * @param {CglMeshAttributeOptions} options 19129 */ 19130 setAttribute(name, array, itemSize, options = {}) 19131 { 19132 if (!array) 19133 { 19134 this._log.error("mesh addAttribute - no array given! " + name); 19135 throw new Error(); 19136 } 19137 let cb = null; 19138 let instanced = false; 19139 let i = 0; 19140 const numItems = array.length / itemSize; 19141 19142 this.#cgl.profileData.profileMeshAttributes += numItems || 0; 19143 19144 if (typeof options == "function") 19145 { 19146 cb = options; 19147 } 19148 19149 if (typeof options == "object") 19150 { 19151 if (options.cb) cb = options.cb; 19152 if (options.instanced) instanced = options.instanced; 19153 } 19154 19155 if (name == _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_INSTANCE_MMATRIX) instanced = true; 19156 19157 for (i = 0; i < this._attributes.length; i++) 19158 { 19159 const attr = this._attributes[i]; 19160 if (attr.name == name) 19161 { 19162 if (attr.numItems === numItems) 19163 { 19164 } 19165 else 19166 { 19167 this._resizeAttr(array, attr); 19168 } 19169 19170 this.#cgl.gl.bindBuffer(this.#cgl.gl.ARRAY_BUFFER, attr.buffer); 19171 this._bufferArray(array, attr); 19172 19173 return attr; 19174 } 19175 } 19176 19177 // create new buffer... 19178 19179 const buffer = this.#cgl.gl.createBuffer(); 19180 19181 this.#cgl.gl.bindBuffer(this.#cgl.gl.ARRAY_BUFFER, buffer); 19182 // this._cgl.gl.bufferData(this._cgl.gl.ARRAY_BUFFER, floatArray, this._cgl.gl.DYNAMIC_DRAW); 19183 19184 let type = this.#cgl.gl.FLOAT; 19185 if (options && options.type) type = options.type; 19186 const attr = { 19187 "buffer": buffer, 19188 "name": name, 19189 "cb": cb, 19190 "itemSize": itemSize, 19191 "numItems": numItems, 19192 "startItem": 0, 19193 "instanced": instanced, 19194 "type": type 19195 }; 19196 19197 this._bufferArray(array, attr); 19198 19199 if (name == _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_VERTEX_POSITION) this._bufVertexAttrib = attr; 19200 this._attributes.push(attr); 19201 this._attribLocs = {}; 19202 19203 return attr; 19204 } 19205 19206 getAttributes() 19207 { 19208 return this._attributes; 19209 } 19210 19211 /** 19212 * @function updateTexCoords 19213 * @description update texture coordinates only from a geometry 19214 * @memberof Mesh 19215 * @instance 19216 * @param {Geometry} geom 19217 */ 19218 updateTexCoords(geom) 19219 { 19220 if (geom.texCoords && geom.texCoords.length > 0) 19221 { 19222 this.setAttribute(_constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_VERTEX_TEXCOORD, geom.texCoords, 2); 19223 } 19224 else 19225 { 19226 const tcBuff = new Float32Array(Math.round((geom.vertices.length / 3) * 2)); 19227 this.setAttribute(_constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_VERTEX_TEXCOORD, tcBuff, 2); 19228 } 19229 } 19230 19231 /** 19232 * @function updateNormals 19233 * @description update normals only from a geometry 19234 * @memberof Mesh 19235 * @instance 19236 * @param {Geometry} geom 19237 */ 19238 updateNormals(geom) 19239 { 19240 if (geom.vertexNormals && geom.vertexNormals.length > 0) 19241 { 19242 this.setAttribute(_constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_VERTEX_NORMAL, geom.vertexNormals, 3); 19243 } 19244 else 19245 { 19246 const tcBuff = new Float32Array(Math.round((geom.vertices.length))); 19247 this.setAttribute(_constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_VERTEX_NORMAL, tcBuff, 3); 19248 } 19249 } 19250 19251 /** 19252 * @param {Array} [arr] 19253 */ 19254 _setVertexNumbers(arr = null) 19255 { 19256 if (!this._verticesNumbers || this._verticesNumbers.length != this._numVerts || arr) 19257 { 19258 if (arr) this._verticesNumbers = arr; 19259 else 19260 { 19261 this._verticesNumbers = new Float32Array(this._numVerts); 19262 for (let i = 0; i < this._numVerts; i++) this._verticesNumbers[i] = i; 19263 } 19264 19265 this.setAttribute(_constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_VERTEX_NUMBER, this._verticesNumbers, 1, (_attr, _geom, shader) => 19266 { 19267 if (!shader.uniformNumVertices) shader.uniformNumVertices = new _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_4__.Uniform(shader, "f", "numVertices", this._numVerts); 19268 shader.uniformNumVertices.setValue(this._numVerts); 19269 }); 19270 } 19271 } 19272 19273 /** 19274 * @function setVertexIndices
19275 * @description update vertex indices / faces 19276 * @memberof Mesh 19277 * @instance 19278 * @param {array} vertIndices 19279 */ 19280 setVertexIndices(vertIndices) 19281 { 19282 if (!this.#bufVerticesIndizes) 19283 { 19284 this._log.warn("no bufVerticesIndizes: " + this._name); 19285 return; 19286 } 19287 if (vertIndices.length > 0) 19288 { 19289 if (vertIndices instanceof Float32Array) this._log.warn("vertIndices float32Array: " + this._name); 19290 19291 for (let i = 0; i < vertIndices.length; i++) 19292 { 19293 if (vertIndices[i] >= this._numVerts) 19294 { 19295 this._log.warn("invalid index in " + this._name, i, vertIndices[i]); 19296 return; 19297 } 19298 } 19299 19300 this.#cgl.gl.bindBuffer(this.#cgl.gl.ELEMENT_ARRAY_BUFFER, this.#bufVerticesIndizes); 19301 19302 /* 19303 * todo cache this ? 19304 * if(!this.vertIndicesTyped || this.vertIndicesTyped.length!=this._geom.verticesIndices.length) 19305 */ 19306 19307 if (vertIndices.length > 65535) 19308 { 19309 this.vertIndicesTyped = new Uint32Array(vertIndices); 19310 this._indexType = this.#cgl.gl.UNSIGNED_INT; 19311 } 19312 else 19313 if (vertIndices instanceof Uint32Array) 19314 { 19315 this.vertIndicesTyped = vertIndices; 19316 this._indexType = this.#cgl.gl.UNSIGNED_INT; 19317 } 19318 else 19319 if (!(vertIndices instanceof Uint16Array)) 19320 { 19321 this.vertIndicesTyped = new Uint16Array(vertIndices); 19322 this._indexType = this.#cgl.gl.UNSIGNED_SHORT; 19323 } 19324 else this.vertIndicesTyped = vertIndices; 19325 19326 this.#cgl.gl.bufferData(this.#cgl.gl.ELEMENT_ARRAY_BUFFER, this.vertIndicesTyped, this.#cgl.gl.DYNAMIC_DRAW); 19327 this.#bufVerticesIndizes.itemSize = 1; 19328 this.#bufVerticesIndizes.numItems = vertIndices.length; 19329 } 19330 else this.#bufVerticesIndizes.numItems = 0; 19331 } 19332 19333 /** 19334 * @function setGeom 19335 * @memberof Mesh 19336 * @instance 19337 * @description set geometry for mesh 19338 * @param {Geometry} geom 19339 * @param {boolean} removeRef 19340 */ 19341 setGeom(geom, removeRef = false) 19342 { 19343 this.#geom = geom; 19344 if (geom.glPrimitive != null) this._glPrimitive = geom.glPrimitive; 19345 if (this.#geom && this.#geom.name) this._name = "mesh " + this.#geom.name; 19346 19347 MESH.lastMesh = null; 19348 this.#cgl.profileData.profileMeshSetGeom++; 19349 19350 this._disposeAttributes(); 19351 19352 this.updateVertices(this.#geom); 19353 this.setVertexIndices(this.#geom.verticesIndices); 19354 19355 if (this.addVertexNumbers) this._setVertexNumbers(); 19356 19357 const geomAttribs = this.#geom.getAttributes(); 19358 19359 const attribAssoc = { 19360 "texCoords": _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_VERTEX_TEXCOORD, 19361 "vertexNormals": _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_VERTEX_NORMAL, 19362 "vertexColors": _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_VERTEX_COLOR, 19363 "tangents": "attrTangent", 19364 "biTangents": "attrBiTangent", 19365 }; 19366 19367 for (const index in geomAttribs) 19368 if (geomAttribs[index].data && geomAttribs[index].data.length) 19369 this.setAttribute(attribAssoc[index] || index, geomAttribs[index].data, geomAttribs[index].itemSize); 19370 19371 if (removeRef) 19372 { 19373 this.#geom = null; 19374 } 19375 } 19376 19377 _preBind(shader) 19378 { 19379 for (let i = 0; i < this._attributes.length; i++) 19380 if (this._attributes[i].cb) 19381 this._attributes[i].cb(this._attributes[i], this.#geom, shader); 19382 } 19383 19384 _checkAttrLengths() 19385 { 19386 if (this.memFreed) return; 19387 // check length 19388 for (let i = 0; i < this._attributes.length; i++) 19389 { 19390 if (this._attributes[i].arrayLength / this._attributes[i].itemSize < this._attributes[0].arrayLength / this._attributes[0].itemSize) 19391 { 19392 let name = "unknown"; 19393 if (this.#geom)name = this.#geom.name; 19394 19395 /* 19396 * this._log.warn( 19397 * name + ": " + this._attributes[i].name + 19398 * " wrong attr length. is:", this._attributes[i].arrayLength / this._attributes[i].itemSize, 19399 * " should be:", this._attributes[0].arrayLength / this._attributes[0].itemSize, 19400 * ); 19401 */ 19402 } 19403 } 19404 } 19405 19406 _bind(shader) 19407 { 19408 if (!shader) return; 19409 if (!shader.isValid()) return; 19410 19411 let attrLocs = []; 19412 if (this._attribLocs[shader.id]) attrLocs = this._attribLocs[shader.id]; 19413 else this._attribLocs[shader.id] = attrLocs; 19414 19415 this._lastShader = shader; 19416 if (shader.lastCompile > this._lastAttrUpdate || attrLocs.length != this._attributes.length) 19417 { 19418 this._lastAttrUpdate = shader.lastCompile; 19419 for (let i = 0; i < this._attributes.length;
19419 i++) attrLocs[i] = -1; 19420 } 19421 19422 for (let i = 0; i < this._attributes.length; i++) 19423 { 19424 const attribute = this._attributes[i]; 19425 if (attrLocs[i] == -1) 19426 { 19427 if (attribute._attrLocationLastShaderTime != shader.lastCompile) 19428 { 19429 attribute._attrLocationLastShaderTime = shader.lastCompile; 19430 attrLocs[i] = this.#cgl.glGetAttribLocation(shader.getProgram(), attribute.name); 19431 // this._log.log('attribloc',attribute.name,attrLocs[i]); 19432 this.#cgl.profileData.profileAttrLoc++; 19433 } 19434 } 19435 19436 if (attrLocs[i] != -1) 19437 { 19438 this.#cgl.gl.enableVertexAttribArray(attrLocs[i]); 19439 this.#cgl.gl.bindBuffer(this.#cgl.gl.ARRAY_BUFFER, attribute.buffer); 19440 19441 if (attribute.instanced) 19442 { 19443 // todo: easier way to fill mat4 attribs... 19444 if (attribute.itemSize <= 4) 19445 { 19446 if (!attribute.itemSize || attribute.itemSize == 0) this._log.warn("instanced attrib itemsize error", this.#geom.name, attribute); 19447 19448 this.#cgl.gl.vertexAttribPointer(attrLocs[i], attribute.itemSize, attribute.type, false, attribute.itemSize * 4, 0); 19449 this.#cgl.gl.vertexAttribDivisor(attrLocs[i], 1); 19450 } 19451 else if (attribute.itemSize == 16) 19452 { 19453 const stride = 16 * 4; 19454 19455 this.#cgl.gl.vertexAttribPointer(attrLocs[i], 4, attribute.type, false, stride, 0); 19456 this.#cgl.gl.enableVertexAttribArray(attrLocs[i] + 1); 19457 this.#cgl.gl.vertexAttribPointer(attrLocs[i] + 1, 4, attribute.type, false, stride, 4 * 4 * 1); 19458 this.#cgl.gl.enableVertexAttribArray(attrLocs[i] + 2); 19459 this.#cgl.gl.vertexAttribPointer(attrLocs[i] + 2, 4, attribute.type, false, stride, 4 * 4 * 2); 19460 this.#cgl.gl.enableVertexAttribArray(attrLocs[i] + 3); 19461 this.#cgl.gl.vertexAttribPointer(attrLocs[i] + 3, 4, attribute.type, false, stride, 4 * 4 * 3); 19462 19463 this.#cgl.gl.vertexAttribDivisor(attrLocs[i], 1); 19464 this.#cgl.gl.vertexAttribDivisor(attrLocs[i] + 1, 1); 19465 this.#cgl.gl.vertexAttribDivisor(attrLocs[i] + 2, 1); 19466 this.#cgl.gl.vertexAttribDivisor(attrLocs[i] + 3, 1); 19467 } 19468 else 19469 { 19470 this._log.warn("unknown instance attrib size", attribute.name); 19471 } 19472 } 19473 else 19474 { 19475 if (!attribute.itemSize || attribute.itemSize == 0) this._log.warn("attrib itemsize error", this._name, attribute); 19476 this.#cgl.gl.vertexAttribPointer(attrLocs[i], attribute.itemSize, attribute.type, false, attribute.itemSize * 4, 0); 19477 19478 if (attribute.pointer) 19479 { 19480 for (let ip = 0; ip < attribute.pointer.length; ip++) 19481 { 19482 const pointer = attribute.pointer[ip]; 19483 19484 if (pointer.loc == -1) 19485 pointer.loc = this.#cgl.glGetAttribLocation(shader.getProgram(), pointer.name); 19486 19487 this.#cgl.profileData.profileAttrLoc++; 19488 19489 this.#cgl.gl.enableVertexAttribArray(pointer.loc); 19490 this.#cgl.gl.vertexAttribPointer(pointer.loc, attribute.itemSize, attribute.type, false, pointer.stride, pointer.offset); 19491 } 19492 } 19493 if (this.bindFeedback) this.bindFeedback(attribute); 19494 } 19495 } 19496 } 19497 19498 if (this.#bufVerticesIndizes && this.#bufVerticesIndizes.numItems !== 0) this.#cgl.gl.bindBuffer(this.#cgl.gl.ELEMENT_ARRAY_BUFFER, this.#bufVerticesIndizes); 19499 } 19500 19501 unBind() 19502 { 19503 const shader = this._lastShader; 19504 this._lastShader = null; 19505 if (!shader) return; 19506 19507 let attrLocs = []; 19508 if (this._attribLocs[shader.id]) attrLocs = this._attribLocs[shader.id]; 19509 else this._attribLocs[shader.id] = attrLocs; 19510 19511 MESH.lastMesh = null; 19512 19513 for (let i = 0; i < this._attributes.length; i++) 19514 { 19515 if (this._attributes[i].instanced) 19516 { 19517 // todo: easier way to fill mat4 attribs... 19518 if (this._attributes[i].itemSize <= 4) 19519 { 19520 if (attrLocs[i] != -1) this.#cgl.gl.vertexAttribDivisor(attrLocs[i], 0); 19521 if (attrLocs[i] >= 0) this.#cgl.gl.disableVertexAttribArray(attrLocs[i]); 19522 } 19523 else 19524 { 19525 this.#cgl.gl.vertexAttribDivisor(attrLocs[i], 0); 19526 this.#cgl.gl.vertexAttribDivisor(attrLocs[i] + 1, 0); 19527 this.#cgl.gl.vertexAttribDivisor(attrLocs[i] + 2, 0); 19528 this.#cgl.gl.vertexAttribDivisor(attrLocs[i] + 3, 0); 19529 this.#cgl.gl.disableVertexAttribArray(attrLocs[i] + 1); 19530 this.#cgl.gl.disableVertexAttribArray(attrLocs[i] + 2); 19531 this.#cgl.gl.disableVertexAttribArray(attrLocs[i] + 3); 19532 } 19533 } 19534 19535 if (attrLocs[i] != -1) this.#cgl.gl.disableVertexAttribArray(attrLocs[i]); 19536 19537 } 19538 } 19539 19540 meshChanged() 19541 { 19542 return this.#cgl.lastMesh && this.#cgl.lastMesh != this; 19543 } 19544 19545 printDebug() 19546 { 19547 console.log("--attributes"); 19548 for (let i = 0; i < this._attributes.length; i++) 19549 { 19550 console.log("attribute " + i + " " + this._attributes[i].name); 19551 } 19552 } 19553 19554 /** 19555 * @param {Number} num 19556 */ 19557 setNumVertices(num) 19558 { 19559 // this._bufVerticesIndizes.numItems = num; 19560 this._bufVertexAttrib.numItems = num; 19561 } 19562 19563 /** 19564 * @returns {Number} 19565 */ 19566 getNumVertices() 19567 { 19568 // return this._bufVerticesIndizes.numItems; 19569 return this._bufVertexAttrib.numItems; 19570 } 19571 19572 /** 19573 * @param {Number} num 19574 */ 19575 setNumIndices(num) 19576 { 19577 this.#bufVerticesIndizes.numItems = num; 19578 } 19579 19580 /** 19581 * @returns {Number} 19582 */ 19583 getNumIndices() 19584 { 19585 return this.#bufVerticesIndizes.numItems; 19586 } 19587 19588 /** 19589 * @function render 19590 * @memberof Mesh 19591 * @instance
19592 * @description draw mesh to screen 19593 * @param {Shader} shader 19594 */ 19595 render(shader) 19596 { 19597 // TODO: enable/disablevertex only if the mesh has changed... think drawing 10000x the same mesh 19598 19599 if (this.#cgl.aborted) return; 19600 shader = shader || this.#cgl.getShader(); 19601 19602 if (!shader) 19603 { 19604 return console.log("shader not valid"); 19605 } 19606 19607 if (!shader.isValid()) 19608 { 19609 shader = this.#cgl.getErrorShader(); 19610 } 19611 19612 this._checkAttrLengths(); 19613 19614 if (this.#geom) 19615 { 19616 if (this._preWireframeGeom && !shader.wireframe && !this.#geom.isIndexed()) 19617 { 19618 this.setGeom(this._preWireframeGeom); 19619 this._preWireframeGeom = null; 19620 } 19621 19622 if (shader.wireframe) 19623 { 19624 let changed = false; 19625 19626 if (this.#geom.isIndexed()) 19627 { 19628 if (!this._preWireframeGeom) 19629 { 19630 this._preWireframeGeom = this.#geom; 19631 this.#geom = this.#geom.copy(); 19632 } 19633 19634 this.#geom.unIndex(); 19635 changed = true; 19636 } 19637 19638 if (!this.#geom.getAttribute("attrBarycentric")) 19639 { 19640 if (!this._preWireframeGeom) 19641 { 19642 this._preWireframeGeom = this.#geom; 19643 this.#geom = this.#geom.copy(); 19644 } 19645 changed = true; 19646 19647 this.#geom.calcBarycentric(); 19648 } 19649 if (changed) this.setGeom(this.#geom); 19650 } 19651 } 19652 19653 let needsBind = false; 19654 if (MESH.lastMesh != this) 19655 { 19656 if (MESH.lastMesh) MESH.lastMesh.unBind(); 19657 needsBind = true; 19658 } 19659 19660 if (needsBind) this._preBind(shader); 19661 19662 if (!shader.bind()) return; 19663 19664 this._bind(shader); 19665 if (this.addVertexNumbers) this._setVertexNumbers(); 19666 19667 MESH.lastMesh = this; 19668 19669 let prim = this.#cgl.gl.TRIANGLES; 19670 if (this._glPrimitive !== undefined) prim = this._glPrimitive; 19671 if (shader.glPrimitive !== null) prim = shader.glPrimitive; 19672 19673 let elementDiv = 1; 19674 let doQuery = this.#cgl.profileData.doProfileGlQuery; 19675 let queryStarted = false; 19676 if (doQuery) 19677 { 19678 let id = this._name + " - " + shader.getName() + " #" + shader.id; 19679 if (this._numInstances) id += " instanced " + this._numInstances + "x"; 19680 19681 let queryProfilerData = this.#cgl.profileData.glQueryData[id]; 19682 19683 if (!queryProfilerData) queryProfilerData = { "id": id, "num": 0 }; 19684 19685 if (shader.opId)queryProfilerData.shaderOp = shader.opId; 19686 if (this.opId)queryProfilerData.meshOp = this.opId; 19687 19688 this.#cgl.profileData.glQueryData[id] = queryProfilerData; 19689 19690 if (!this._queryExt && this._queryExt !== false) this._queryExt = this.#cgl.enableExtension("EXT_disjoint_timer_query_webgl2") || false; 19691 if (this._queryExt) 19692 { 19693 if (queryProfilerData._drawQuery) 19694 { 19695 const available = this.#cgl.gl.getQueryParameter(queryProfilerData._drawQuery, this.#cgl.gl.QUERY_RESULT_AVAILABLE); 19696 if (available) 19697 { 19698 const elapsedNanos = this.#cgl.gl.getQueryParameter(queryProfilerData._drawQuery, this.#cgl.gl.QUERY_RESULT); 19699 const currentTimeGPU = elapsedNanos / 1000000; 19700 19701 queryProfilerData._times = queryProfilerData._times || 0; 19702 queryProfilerData._times += currentTimeGPU; 19703 queryProfilerData._numcount++; 19704 queryProfilerData.when = performance.now(); 19705 queryProfilerData._drawQuery = null; 19706 queryProfilerData.queryStarted = false; 19707 } 19708 } 19709 19710 if (!queryProfilerData.queryStarted) 19711 { 19712 queryProfilerData._drawQuery = this.#cgl.gl.createQuery(); 19713 this.#cgl.gl.beginQuery(this._queryExt.TIME_ELAPSED_EXT, queryProfilerData._drawQuery); 19714 queryStarted = queryProfilerData.queryStarted = true; 19715 } 19716 } 19717 } 19718 19719 if (this.hasFeedbacks && this.hasFeedbacks()) this.drawFeedbacks(shader, prim); 19720 else if (!this.#bufVerticesIndizes || this.#bufVerticesIndizes.numItems === 0) 19721 { 19722 19723 /* 19724 * for (let i = 0; i < this._attributes.length; i++) 19725 * { 19726 * if (this._attributes[i].arrayLength / this._attributes[i].itemSize != this._bufVertexAttrib.floatArray.length / 3) 19727 * { 19728 * this._log.warn("attrib buffer length wrong! ", this._attributes[i].name, this._attributes[i].arrayLength / this._attributes[i].itemSize, this._bufVertexAttrib.floatArray.length / 3, this._attributes[i].itemSize); 19729 * // this._log.log(this); 19730 * // debugger; 19731 * return; 19732 * } 19733 * } 19734 */ 19735 19736 if (prim == this.#cgl.gl.TRIANGLES)elementDiv = 3; 19737 19738 if (this._numInstances === 0) this.#cgl.gl.drawArrays(prim, this._bufVertexAttrib.startItem, this._bufVertexAttrib.numItems - this._bufVertexAttrib.startItem); 19739 else this.#cgl.gl.drawArraysInstanced(prim, this._bufVertexAttrib.startItem, this._bufVertexAttrib.numItems, this._numInstances); 19740 } 19741 else 19742 { 19743 if (prim == this.#cgl.gl.TRIANGLES)elementDiv = 3; 19744 if (this._numInstances === 0) 19745 { 19746 this.#cgl.gl.drawElements(prim, this.#bufVerticesIndizes.numItems, this._indexType, 0); 19747 } 19748 else 19749 { 19750 this.#cgl.gl.drawElementsInstanced(prim, this.#bufVerticesIndizes.numItems, this._indexType, 0, this._numInstances); 19751 } 19752 } 19753 19754 if (this.#cgl.debugOneFrame && this.#cgl.gl.getError() != this.#cgl.gl.NO_ERROR) 19755 { 19756 this._log.error("mesh draw gl error"); 19757 this._log.error("mesh", this); 19758 this._log.error("shader", shader); 19759 19760 const attribNames = []; 19761 for (let i = 0; i < this.#cgl.gl.getProgramParameter(shader.getProgram(), this.#cgl.gl.ACTIVE_ATTRIBUTES); i++) 19762 { 19763 const name = this.#cgl.gl.getActiveAttrib(shader.getProgram(), i).name; 19764 this._log.error("attrib ", name); 19765 } 19766 } 19767 19768 this.#cgl.profileData.profileMeshNumElements += (this._bufVertexAttrib.numItems / elementDiv) * (this._numInstances || 1
19768); 19769 this.#cgl.profileData.profileMeshDraw++; 19770 19771 if (doQuery && queryStarted) 19772 { 19773 this.#cgl.gl.endQuery(this._queryExt.TIME_ELAPSED_EXT); 19774 } 19775 19776 this.#cgl.printError("mesh render " + this._name); 19777 19778 this.unBind(); 19779 } 19780 19781 setNumInstances(n) 19782 { 19783 n = Math.max(0, n); 19784 if (this._numInstances != n) 19785 { 19786 this._numInstances = n; 19787 const indexArr = new Float32Array(n); 19788 for (let i = 0; i < n; i++) indexArr[i] = i; 19789 this.setAttribute(_constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.SHADER.SHADERVAR_INSTANCE_INDEX, indexArr, 1, { "instanced": true }); 19790 } 19791 } 19792 19793 _disposeAttributes() 19794 { 19795 if (!this._attributes) return; 19796 19797 for (let i = 0; i < this._attributes.length; i++) 19798 { 19799 if (this._attributes[i].buffer) 19800 { 19801 this.#cgl.gl.deleteBuffer(this._attributes[i].buffer); 19802 this._attributes[i].buffer = null; 19803 } 19804 } 19805 this._attributes.length = 0; 19806 } 19807 19808 dispose() 19809 { 19810 if (this.#cgl.aborted) return; 19811 if (this._bufVertexAttrib && this._bufVertexAttrib.buffer) this.#cgl.gl.deleteBuffer(this._bufVertexAttrib.buffer); 19812 if (this.#bufVerticesIndizes) this.#cgl.gl.deleteBuffer(this.#bufVerticesIndizes); 19813 this.#bufVerticesIndizes = null; 19814 19815 this._disposeAttributes(); 19816 } 19817} 19818 19819 19820 19821 19822/***/ }), 19823
19824/***/ "./src/corelibs/cgl/cgl_profiledata.js": 19825/*!*********************************************!*\ 19826 !*** ./src/corelibs/cgl/cgl_profiledata.js ***! 19827 \*********************************************/ 19828/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 19829 19830"use strict"; 19831/* harmony export */ __webpack_require__.d(__webpack_exports__, { 19832/* harmony export */ ProfileData: () => (/* binding */ ProfileData) 19833/* harmony export */ }); 19834class ProfileData 19835{ 19836 constructor(cgl) 19837 { 19838 this._cgl = cgl; 19839 this._lastTime = 0; 19840 this.pause = false; 19841 this.profileUniformCount = 0; 19842 this.profileShaderBinds = 0; 19843 this.profileUniformCount = 0; 19844 this.profileShaderCompiles = 0; 19845 this.profileVideosPlaying = 0; 19846 this.profileMVPMatrixCount = 0; 19847 this.profileEffectBuffercreate = 0; 19848 this.profileShaderGetUniform = 0; 19849 this.profileFrameBuffercreate = 0; 19850 this.profileMeshSetGeom = 0; 19851 this.profileTextureNew = 0; 19852 this.profileGenMipMap = 0; 19853 this.profileOnAnimFrameOps = 0; 19854 19855 this.profileFencedPixelRead = 0; 19856 this.profileMainloopMs = 0; 19857 this.profileMeshDraw = 0; 19858 this.profileTextureEffect = 0; 19859 this.profileTexPreviews = 0; 19860 this.shaderCompileTime = 0; 19861 this.profileMeshNumElements = 0; 19862 this.profileMeshAttributes = 0; 19863 this.profileSingleMeshAttribute = []; 19864 this.heavyEvents = []; 19865 19866 this.doProfileGlQuery = false; 19867 this.glQueryData = {}; 19868 this.counts = {}; 19869 } 19870 19871 clear() 19872 { 19873 this.counts = {}; 19874 this.profileSingleMeshAttribute = {}; 19875 this.profileMeshAttributes = 0; 19876 this.profileUniformCount = 0; 19877 this.profileShaderGetUniform = 0; 19878 this.profileShaderCompiles = 0; 19879 this.profileShaderBinds = 0; 19880 this.profileTextureResize = 0; 19881 this.profileFrameBuffercreate = 0; 19882 this.profileEffectBuffercreate = 0; 19883 this.profileTextureDelete = 0; 19884 this.profileMeshSetGeom = 0; 19885 this.profileVideosPlaying = 0; 19886 this.profileMVPMatrixCount = 0; 19887 this.profileNonTypedAttrib = 0; 19888 this.profileNonTypedAttribNames = ""; 19889 this.profileTextureNew = 0; 19890 this.profileGenMipMap = 0; 19891 this.profileFramebuffer = 0; 19892 this.profileMeshDraw = 0; 19893 this.profileTextureEffect = 0; 19894 this.profileTexPreviews = 0; 19895 this.profileMeshNumElements = 0; 19896 this.profileFencedPixelRead = 0; 19897 } 19898 19899 clearGlQuery() 19900 { 19901 for (let i in this.glQueryData) 19902 { 19903 if (!this.glQueryData[i].lastClear || performance.now() - this.glQueryData[i].lastClear > 1000) 19904 { 19905 this.glQueryData[i].time = this.glQueryData[i]._times / this.glQueryData[i]._numcount; 19906 this.glQueryData[i].num = this.glQueryData[i]._numcount; 19907 19908 this.glQueryData[i]._times = 0; 19909 this.glQueryData[i]._numcount = 0; 19910 this.glQueryData[i].lastClear = performance.now(); 19911 } 19912 } 19913 } 19914 19915 /** 19916 * @param {string} event 19917 * @param {string} name 19918 */ 19919 count(event, name) 19920 { 19921 this.counts[event] = this.counts[event] || []; 19922 this.counts[event].push(name); 19923 } 19924 19925 /** 19926 * @param {string} event 19927 * @param {string} name 19928 * @param {string} [info] 19929 */ 19930 addHeavyEvent(event, name, info) 19931 { 19932 const e = { "event": event, "name": name, "info": info, "date": performance.now() }; 19933 this.heavyEvents.push(e); 19934 this._cgl.emitEvent("heavyEvent", e); 19935 } 19936} 19937 19938 19939/***/ }), 19940
19941/***/ "./src/corelibs/cgl/cgl_shader.js": 19942/*!****************************************!*\ 19943 !*** ./src/corelibs/cgl/cgl_shader.js ***! 19944 \****************************************/ 19945/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 19946 19947"use strict"; 19948/* harmony export */ __webpack_require__.d(__webpack_exports__, { 19949/* harmony export */ Shader: () => (/* binding */ CglShader) 19950/* harmony export */ }); 19951/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 19952/* harmony import */ var gl_matrix__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! gl-matrix */ "./node_modules/gl-matrix/esm/mat4.js"); 19953/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! cables */ "./src/core/timer.js"); 19954/* harmony import */ var _cgl_shader_lib_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./cgl_shader_lib.js */ "./src/corelibs/cgl/cgl_shader_lib.js"); 19955/* harmony import */ var _cgl_mesh_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./cgl_mesh.js */ "./src/corelibs/cgl/cgl_mesh.js"); 19956/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants.js */ "./src/corelibs/cgl/constants.js"); 19957/* harmony import */ var _cg_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../cg/index.js */ "./src/corelibs/cg/cg_shader.js"); 19958/* harmony import */ var _cgl_texture_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./cgl_texture.js */ "./src/corelibs/cgl/cgl_texture.js"); 19959/* harmony import */ var _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./cgl_shader_uniform.js */ "./src/corelibs/cgl/cgl_shader_uniform.js"); 19960 19961 19962 19963 19964 19965 19966 19967 19968 19969 19970 19971// --------------------------------------------------------------------------- 19972 19973/* 19974 19975proposal default shader variable names: 19976 19977attrVertex - currently: vPosition 19978attrVertexIndex - currently: attrVertIndex 19979attrTexCoord 19980attrInstMat - currently: instMat 19981attrVertColor 19982attrTangent 19983attrBiTangent 19984 19985uProjMatrix - currently: projMatrix 19986uModelMatrix - currently: modelMatrix 19987uNormalMatrix - currently: normalMatrix 19988uCamPosition - currently: camPos 19989 19990*/ 19991 19992// --------------------------------------------------------------------------- 19993 19994// eslint-disable-next-line no-restricted-syntax 19995const defaultShaderSrcVert = ` 19996{{MODULES_HEAD}} 19997IN vec3 vPosition; //!@ 19998IN vec2 attrTexCoord; 19999IN vec3 attrVertNormal; 20000IN vec3 attrTangent,attrBiTangent; 20001 20002IN float attrVertIndex; 20003 20004OUT vec2 texCoord; 20005OUT vec3 norm; 20006UNI mat4 projMatrix; 20007UNI mat4 viewMatrix; 20008UNI mat4 modelMatrix; 20009 20010void main() 20011{ 20012 texCoord=attrTexCoord; 20013 norm=attrVertNormal; 20014 vec4 pos=vec4(vPosition, 1.0); 20015 vec3 tangent=attrTangent; 20016 vec3 bitangent=attrBiTangent; 20017 mat4 mMatrix=modelMatrix; 20018 gl_PointSize=10.0; 20019 20020 {{MODULE_VERTEX_POSITION}} 20021 20022 mat4 modelViewMatrix=viewMatrix*mMatrix; 20023 {{MODULE_VERTEX_MODELVIEW}} 20024 20025 gl_Position = projMatrix * modelViewMatrix * pos; 20026} 20027`; 20028let materialIdCounter = 0; 20029 20030function getDefaultVertexShader() 20031{ 20032 return defaultShaderSrcVert; 20033} 20034 20035/** 20036 * @param {number} [r] 20037 * @param {number} [g] 20038 * @param {number} [b] 20039 */ 20040function getDefaultFragmentShader(r, g, b) 20041{ 20042 if (r == undefined) 20043 { 20044 r = 0.5; 20045 g = 0.5; 20046 b = 0.5; 20047 } 20048 return "" 20049 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "IN vec2 texCoord;" 20050 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "{{MODULES_HEAD}}" 20051 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "void main()" 20052 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "{" 20053 20054 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + " vec4 col=vec4(" + r + "," + g + "," + b + ",1.0);" 20055 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + " {{MODULE_COLOR}}" 20056 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + " outColor = col;" 20057 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "}"; 20058} 20059 20060/** 20061 * @class 20062 * @namespace external:CGL 20063 * @hideconstructor 20064 * @param _cgl 20065 * @param _name 20066 * @param _op 20067 * @example 20068 * var shader=new CGL.Shader(cgl,'MinimalMaterial'); 20069 * shader.setSource(attachments.shader_vert,attachments.shader_frag); 20070 */ 20071class CglShader extends _cg_index_js__WEBPACK_IMPORTED_MODULE_1__.CgShader 20072{ 20073 20074 /** @type {Uniform[]} */ 20075 _uniforms = []; 20076 20077 /** 20078 * @param {CglContext} _cgl 20079 * @param {string} _name 20080 * @param {Op} [_op] 20081 */ 20082 constructor(_cgl, _name, _op) 20083 { 20084 super(); 20085 if (!_cgl) throw new Error("shader constructed without cgl " + _name); 20086 20087 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_2__["default"]("cgl_shader"); 20088 this._cgl = _cgl; 20089 20090 if (!_name) this._log.stack("no shader name given"); 20091 this._name = _name || "unknown"; 20092 20093 if (_op) this.opId = _op.id; 20094 this.glslVersion = 0; 20095 if (_cgl.glVersion > 1) this.glslVersion = 300; 20096 20097 this._materialId = ++materialIdCounter; 20098 20099 this._program = null; 20100 this._drawBuffers = [true]; 20101 this.error = null; 20102 20103 this.ignoreMissingUniforms = false;
20104 this._projMatrixUniform = null; 20105 this._mvMatrixUniform = null; 20106 this._mMatrixUniform = null; 20107 this._vMatrixUniform = null; 20108 this._camPosUniform = null; 20109 this._normalMatrixUniform = null; 20110 this._inverseViewMatrixUniform = null; 20111 this._fromUserInteraction = false; 20112 20113 this._attrVertexPos = -1; 20114 this.precision = _cgl.patch.config.glslPrecision || "highp"; 20115 20116 this._pMatrixState = -1; 20117 this._vMatrixState = -1; 20118 20119 this._countMissingUniforms = 0; 20120 this._modGroupCount = 0; // not needed anymore... 20121 this._feedBackNames = []; 20122 this._attributes = []; 20123 20124 this.glPrimitive = null; 20125 this.offScreenPass = false; 20126 this._extensions = []; 20127 this.srcVert = getDefaultVertexShader(); 20128 this.srcFrag = getDefaultFragmentShader(); 20129 this.lastCompile = 0; 20130 20131 this._libs = []; 20132 this._structNames = []; 20133 this._structUniformNames = []; 20134 this._textureStackUni = []; 20135 this._textureStackTex = []; 20136 this._textureStackType = []; 20137 this._textureStackTexCgl = []; 20138 20139 this._tempNormalMatrix = gl_matrix__WEBPACK_IMPORTED_MODULE_3__.create(); 20140 this._tempCamPosMatrix = gl_matrix__WEBPACK_IMPORTED_MODULE_3__.create(); 20141 this._tempInverseViewMatrix = gl_matrix__WEBPACK_IMPORTED_MODULE_3__.create(); 20142 this._tempInverseProjMatrix = gl_matrix__WEBPACK_IMPORTED_MODULE_3__.create(); 20143 20144 this.setModules(["MODULE_VERTEX_POSITION", "MODULE_COLOR", "MODULE_NORMAL", "MODULE_BEGIN_FRAG", "MODULE_VERTEX_MODELVIEW"]); 20145 } 20146 20147 isValid() 20148 { 20149 return this._isValid; 20150 } 20151 20152 getCgl() 20153 { 20154 return this._cgl; 20155 } 20156 20157 getName() 20158 { 20159 return this._name; 20160 } 20161 20162 /** 20163 * @param {string} name 20164 */ 20165 enableExtension(name) 20166 { 20167 this.setWhyCompile("enable extension " + name); 20168 20169 this._extensions.push(name); 20170 } 20171 20172 getAttrVertexPos() 20173 { 20174 return this._attrVertexPos; 20175 } 20176 20177 hasTextureUniforms() 20178 { 20179 for (let i = 0; i < this._uniforms.length; i++) 20180 if (this._uniforms[i].getType() == "t") return true; 20181 return false; 20182 } 20183 20184 /** 20185 * copy all uniform values from another shader 20186 * @param {CglShader} origShader uniform values will be copied from this shader 20187 */ 20188 copyUniformValues(origShader) 20189 { 20190 for (let i = 0; i < origShader._uniforms.length; i++) 20191 { 20192 if (!this._uniforms[i]) 20193 { 20194 this._log.log("unknown uniform?!"); 20195 continue; 20196 } 20197 20198 this.getUniform(origShader._uniforms[i].getName()).set(origShader._uniforms[i].getValue()); 20199 } 20200 20201 this.popTextures(); 20202 for (let i = 0; i < origShader._textureStackUni.length; i++) 20203 { 20204 this._textureStackUni[i] = origShader._textureStackUni[i]; 20205 this._textureStackTex[i] = origShader._textureStackTex[i]; 20206 this._textureStackType[i] = origShader._textureStackType[i]; 20207 this._textureStackTexCgl[i] = origShader._textureStackTexCgl[i]; 20208 } 20209 20210 } 20211 20212 /** 20213 * copy current shader 20214 * @returns {CglShader} newShader 20215 */ 20216 copy() 20217 { 20218 const shader = new CglShader(this._cgl, this._name + " copy"); 20219 shader.setSource(this.srcVert, this.srcFrag); 20220 20221 shader._modules = JSON.parse(JSON.stringify(this._modules)); 20222 shader._defines = JSON.parse(JSON.stringify(this._defines)); 20223 20224 shader._modGroupCount = this._modGroupCount; 20225 shader._moduleNames = this._moduleNames; 20226 shader.glPrimitive = this.glPrimitive; 20227 shader.offScreenPass = this.offScreenPass; 20228 shader._extensions = this._extensions; 20229 shader.wireframe = this.wireframe; 20230 shader._attributes = this._attributes; 20231 20232 for (let i = 0; i < this._uniforms.length; i++) 20233 { 20234 const u = this._uniforms[i].copy(shader); 20235 u.resetLoc(); 20236 } 20237 20238 shader.setWhyCompile("copy"); 20239 return shader; 20240 } 20241 20242 /** 20243 * set shader source code 20244 * @param {String} srcVert 20245 * @param {String} srcFrag 20246 * @param {Boolean} fromUserInteraction 20247 */ 20248 setSource(srcVert, srcFrag, fromUserInteraction = false) 20249 { 20250 this._fromUserInteraction = fromUserInteraction; 20251 this.srcVert = srcVert; 20252 this.srcFrag = srcFrag; 20253 this.setWhyCompile("Source changed"); 20254 this._isValid = true; 20255 } 20256 20257 _addLibs(src) 20258 { 20259 for (const id in _cgl_shader_lib_js__WEBPACK_IMPORTED_MODULE_4__.ShaderLibMods) 20260 { 20261 if (src.includes(id)) 20262 { 20263 const lib = new _cgl_shader_lib_js__WEBPACK_IMPORTED_MODULE_4__.ShaderLibMods[id](); 20264 src = src.replace("{{" + id + "}}", lib.srcHeadFrag); 20265 this._libs.push(lib); 20266 if (lib.initUniforms)lib.initUniforms(this); 20267 } 20268 } 20269 20270 return src; 20271 } 20272 20273 createStructUniforms() 20274 { 20275 // * create structs 20276 let structStrFrag = ""; 20277 let structStrVert = ""; // TODO: not used yet 20278 20279 this._structNames = []; 20280 // * reset the arrays holding the value each recompile so we don't skip structs 20281 // * key value mapping so the same struct can be added twice (two times the same modifier) 20282 this._injectedStringsFrag = {}; 20283 this._injectedStringsVert = {}; 20284 20285 this._structUniformNamesIndicesFrag = []; 20286 this._structUniformNamesIndicesVert = []; 20287 20288 for (let i = 0; i < this._uniforms.length; i++) 20289 { 20290 // * only add uniforms to struct that are a member of a struct 20291 if (this._uniforms[i].isStructMember()) 20292 { 20293 const injectionString = "{{INJECTION_POINT_STRUCT_" + this._uniforms[i]._structName + "}}"; 20294 20295 // * check if struct is not already part of shader 20296 if (!this._structNames.includes(this._uniforms[i]._structName)) 20297 { 20298 // * create struct definition with placeholder string to inject 20299 const structDefinition = "struct " 20300 + this._uniforms[i]._structName + " {" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl 20301 + injectionString 20302 + "};" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20303 20304 if (this._uniforms[i].getShaderType() === "both" || this._uniforms[i].getShaderType() === "frag") 20305 structStrFrag = structStrFrag.concat(structDefinition); 20306 20307 if (this._uniforms[i].getShaderType() === "both" || this._uniforms[i].getShaderType() === "vert") 20308 structStrVert = structStrVert.concat(structDefinition); 20309 20310 this._structNames.push(this._uniforms[i]._structName); 20311 this._injectedStringsFrag[this._uniforms[i]._structName] = []; 20312 this._injectedStringsVert[this._uniforms[i]._structName] = []; 20313 } 20314 20315 // * create member & comment 20316 let comment = ""; 20317 if (this._uniforms[i].comment) comment = " // " + this._uniforms[i].comment; 20318 20319 let stringToInsert = ""; 20320 if (this._uniforms[i].getGlslTypeString() == undefined)stringToInsert += "//";
20321 stringToInsert += " " + this._uniforms[i].getGlslTypeString() 20322 + " " + this._uniforms[i]._propertyName + ";" 20323 + comment; 20324 20325 if (this._uniforms[i].getShaderType() === "both") 20326 { 20327 // * inject member before {injectionString} 20328 if ( 20329 !this._injectedStringsFrag[this._uniforms[i]._structName].includes(stringToInsert) 20330 && !this._injectedStringsVert[this._uniforms[i]._structName].includes(stringToInsert)) 20331 { 20332 const insertionIndexFrag = structStrFrag.lastIndexOf(injectionString); 20333 const insertionIndexVert = structStrVert.lastIndexOf(injectionString); 20334 20335 structStrFrag = 20336 structStrFrag.slice(0, insertionIndexFrag) 20337 + stringToInsert + structStrFrag.slice(insertionIndexFrag - 1); 20338 20339 structStrVert = 20340 structStrVert.slice(0, insertionIndexVert) 20341 + stringToInsert + structStrVert.slice(insertionIndexVert - 1); 20342 20343 this._injectedStringsFrag[this._uniforms[i]._structName].push(stringToInsert); 20344 this._injectedStringsVert[this._uniforms[i]._structName].push(stringToInsert); 20345 } 20346 20347 if (!this._structUniformNamesIndicesFrag.includes(i)) this._structUniformNamesIndicesFrag.push(i); 20348 if (!this._structUniformNamesIndicesVert.includes(i)) this._structUniformNamesIndicesVert.push(i); 20349 } 20350 else if (this._uniforms[i].getShaderType() === "frag") 20351 { 20352 // * inject member before {injectionString} 20353 if (!this._injectedStringsFrag[this._uniforms[i]._structName].includes(stringToInsert)) // 20354 { 20355 const insertionIndexFrag = structStrFrag.lastIndexOf(injectionString); 20356 20357 structStrFrag = 20358 structStrFrag.slice(0, insertionIndexFrag) 20359 + stringToInsert + structStrFrag.slice(insertionIndexFrag - 1); 20360 20361 this._injectedStringsFrag[this._uniforms[i]._structName].push(stringToInsert); 20362 } 20363 20364 if (!this._structUniformNamesIndicesFrag.includes(i)) this._structUniformNamesIndicesFrag.push(i); 20365 } 20366 else if (this._uniforms[i].getShaderType() === "vert") 20367 { 20368 // * inject member before {injectionString} 20369 if (!this._injectedStringsVert[this._uniforms[i]._structName].includes(stringToInsert)) 20370 { 20371 const insertionIndexVert = structStrVert.lastIndexOf(injectionString); 20372 20373 structStrVert = 20374 structStrVert.slice(0, insertionIndexVert) 20375 + stringToInsert + structStrVert.slice(insertionIndexVert - 1); 20376 20377 this._injectedStringsVert[this._uniforms[i]._structName].push(stringToInsert); 20378 } 20379 20380 if (!this._structUniformNamesIndicesVert.includes(i)) this._structUniformNamesIndicesVert.push(i); 20381 } 20382 } 20383 } 20384 20385 // * dedupe injected uni declarations 20386 this._uniDeclarationsFrag = []; 20387 this._uniDeclarationsVert = []; 20388 20389 // * remove struct injection points and add uniform in fragment 20390 for (let i = 0; i < this._structUniformNamesIndicesFrag.length; i += 1) 20391 { 20392 const index = this._structUniformNamesIndicesFrag[i]; 20393 const uniDeclarationString = "UNI " + this._uniforms[index]._structName + " " + this._uniforms[index]._structUniformName + ";" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20394 20395 if (!this._uniDeclarationsFrag.includes(uniDeclarationString)) 20396 { 20397 const injectionString = "{{INJECTION_POINT_STRUCT_" + this._uniforms[index]._structName + "}}"; 20398 20399 structStrFrag = structStrFrag.replace(injectionString, ""); 20400 structStrFrag += uniDeclarationString; 20401 20402 this._uniDeclarationsFrag.push(uniDeclarationString); 20403 } 20404 } 20405 20406 // * remove struct injection points and add uniform in vertex 20407 for (let i = 0; i < this._structUniformNamesIndicesVert.length; i += 1) 20408 { 20409 const index = this._structUniformNamesIndicesVert[i]; 20410 const uniDeclarationString = "UNI " + this._uniforms[index]._structName + " " + this._uniforms[index]._structUniformName + ";" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20411 20412 if (!this._uniDeclarationsVert.includes(uniDeclarationString)) 20413 { 20414 const injectionString = "{{INJECTION_POINT_STRUCT_" + this._uniforms[index]._structName + "}}"; 20415 20416 structStrVert = structStrVert.replace(injectionString, ""); 20417 structStrVert += uniDeclarationString; 20418 this._uniDeclarationsVert.push(uniDeclarationString); 20419 } 20420 } 20421 20422 return [structStrVert, structStrFrag]; 20423 } 20424 20425 _getAttrSrc(attr, firstLevel) 20426 { 20427 const r = {}; 20428 if (attr.name && attr.type) 20429 { 20430 r.srcHeadVert = ""; 20431 if (!firstLevel) r.srcHeadVert += "#ifndef ATTRIB_" + attr.name + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20432 r.srcHeadVert += "#define ATTRIB_" + attr.name + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20433 r.srcHeadVert += "IN " + attr.type + " " + attr.name + ";" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20434 if (!firstLevel) r.srcHeadVert += "#endif" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20435 20436 if (attr.nameFrag) 20437 { 20438 r.srcHeadVert += ""; 20439 if (!firstLevel) r.srcHeadVert += "#ifndef ATTRIB_" + attr.nameFrag + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20440 r.srcHeadVert += "#define ATTRIB_" + attr.nameFrag + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20441 r.srcHeadVert += "OUT " + attr.type + " " + attr.nameFrag + ";" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20442 if (!firstLevel) r.srcHeadVert += "#endif" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20443 20444 r.srcVert = "" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + attr.nameFrag + "=" + attr.name + ";"; 20445 20446 r.srcHeadFrag = ""; 20447 if (!firstLevel) r.srcHeadFrag += "#ifndef ATTRIB_" + attr.nameFrag + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20448 r.srcHeadFrag += "#define ATTRIB_" + attr.nameFrag + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20449 r.srcHeadFrag += "IN " + attr.type + " " + attr.nameFrag + ";" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20450 if (!firstLevel) r.srcHeadFrag += "#endif" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20451 } 20452 } 20453 return r; 20454 } 20455 20456 compile() 20457 { 20458 if (this._cgl.aborted) return; 20459 const startTime = performance.now(); 20460 20461 this._cgl.profileData.profileShaderCompiles++; 20462 this._cgl.profileData.profileShaderCompileName = this._name + " [" + this._compileReason + "]"; 20463 20464 let extensionString = ""; 20465 if (this._extensions) 20466 for (let i = 0; i < this._extensions.length; i++) 20467 extensionString += "#extension " + this._extensions[i] + " : enable" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20468 20469 let definesStr = ""; 20470 if (this._defines.length) definesStr = "\n// cgl generated" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20471 for (let i = 0; i < this._defines.length; i++) 20472 definesStr += "#define " + this._defines[i][0] + " " + this._defines[i][1] + "" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20473 20474 const structStrings = this.createStructUniforms(); 20475 this._cgl.profileData.addHeavyEvent("shader compile", this._name + " [" + this._compileReason + "]"); 20476 this._compileReason = ""; 20477 20478 if (this._uniforms) 20479 { 20480 // * we create an array of the uniform names to check our indices & an array to save them
20481 const uniNames = this._uniforms.map((uni) => { return uni._name; }); 20482 const indicesToRemove = []; 20483 20484 // * we go through our uniforms and check if the same name is contained somewhere further in the array 20485 // * if so, we add the current index to be removed later 20486 for (let i = 0; i < this._uniforms.length; i++) 20487 { 20488 const uni = this._uniforms[i]; 20489 const nextIndex = uniNames.indexOf(uni._name, i + 1); 20490 if (nextIndex > -1) indicesToRemove.push(i); 20491 } 20492 20493 // * after that, we go through the uniforms backwards (so we keep the order) and remove the indices 20494 // * also, we reset the locations of all the other valid uniforms 20495 for (let j = this._uniforms.length - 1; j >= 0; j -= 1) 20496 { 20497 if (indicesToRemove.includes(j)) this._uniforms.splice(j, 1); 20498 else this._uniforms[j].resetLoc(); 20499 } 20500 } 20501 20502 this._cgl.printError("uniform resets"); 20503 20504 this._compileCount++; 20505 if (this.hasTextureUniforms()) definesStr += "#define HAS_TEXTURES" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20506 20507 let vs = ""; 20508 let fs = ""; 20509 20510 if (!this.srcFrag) 20511 { 20512 this._log.warn("[cgl shader] has no fragment source!", this._name, this); 20513 this.srcVert = getDefaultVertexShader(); 20514 this.srcFrag = getDefaultFragmentShader(); 20515 } 20516 20517 vs = "#version 300 es" 20518 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "// " 20519 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "// vertex shader " + this._name 20520 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "// " 20521 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "precision " + this.precision + " float;" 20522 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "precision " + this.precision + " sampler2D;" 20523 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "" 20524 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "#define WEBGL2" 20525 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "#define texture2D texture" 20526 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "#define UNI uniform" 20527 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "#define IN in" 20528 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "#define OUT out" 20529 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20530 20531 fs = "#version 300 es" 20532 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "// " 20533 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "// fragment shader " + this._name 20534 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "// " 20535 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "precision " + this.precision + " float;" 20536 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "precision " + this.precision + " sampler2D;" 20537 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "" 20538 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "#define WEBGL2" 20539 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "#define texture2D texture" 20540 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "#define IN in" 20541 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "#define OUT out" 20542 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "#define UNI uniform" 20543 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "{{DRAWBUFFER}}" 20544 20545 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20546 20547 let uniformsStrVert = "\n// cgl generated" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20548 let uniformsStrFrag = "\n// cgl generated" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20549 20550 fs += "\n// active mods: --------------- "; 20551 vs += "\n// active mods: --------------- "; 20552 20553 let foundModsFrag = false; 20554 let foundModsVert = false; 20555 for (let i = 0; i < this._moduleNames.length; i++) 20556 { 20557 for (let j = 0; j < this._modules.length; j++) 20558 { 20559 if (this._modules[j].name == this._moduleNames[i]) 20560 { 20561 if (this._modules[j].srcBodyFrag || this._modules[j].srcHeadFrag) 20562 { 20563 foundModsFrag = true; 20564 fs += "\n// " + i + "." + j + ". " + this._modules[j].title + " (" + this._modules[j].name + ")"; 20565 } 20566 if (this._modules[j].srcBodyVert || this._modules[j].srcHeadVert) 20567 { 20568 vs += "\n// " + i + "." + j + ". " + this._modules[j].title + " (" + this._modules[j].name + ")"; 20569 foundModsVert = true; 20570 } 20571 } 20572 } 20573 } 20574 if (!foundModsVert)fs += "\n// no mods used..."; 20575 if (!foundModsFrag)fs += "\n// no mods used..."; 20576 fs += "\n"; 20577 vs += "\n"; 20578 20579 for (let i = 0; i < this._uniforms.length; i++) 20580 { 20581 if (this._uniforms[i].shaderType && !this._uniforms[i].isStructMember()) 20582 { 20583 let uniStr = ""; 20584 if (!this._uniforms[i].getGlslTypeString())uniStr += "// "; 20585 uniStr += "UNI " + this._uniforms[i].getGlslTypeString() + " " + this._uniforms[i].getName(); 20586 let comment = ""; 20587 if (this._uniforms[i].comment) comment = " // " + this._uniforms[i].comment; 20588 20589 if (this._uniforms[i].shaderType == "vert" || this._uniforms[i].shaderType == "both") 20590 if (!this.srcVert.includes(uniStr) && !this.srcVert.includes("uniform " + this._uniforms[i].getGlslTypeString() + " " + this._uniforms[i].getName())) 20591 uniformsStrVert += uniStr + ";" + comment + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20592 20593 if (this._uniforms[i].shaderType == "frag" || this._uniforms[i].shaderType == "both") 20594 if (!this.srcFrag.includes(uniStr) && !this.srcFrag.includes("uniform " + this._uniforms[i].getGlslTypeString() + " " + this._uniforms[i].getName())) 20595 uniformsStrFrag += uniStr + ";" + comment + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20596 } 20597 } 20598 20599 let countUniFrag = 0; 20600 let countUniVert = 0; 20601 for (let i = 0; i < this._uniforms.length; i++) 20602 { 20603 if (this._uniforms[i].shaderType && !this._uniforms[i].isStructMember()) 20604 { 20605 if (this._uniforms[i].shaderType == "vert" || this._uniforms[i].shaderType == "both") countUniVert++; 20606 if (this._uniforms[i].shaderType == "frag" || this._uniforms[i].shaderType == "both") countUniFrag++; 20607 } 20608 } 20609 if (countUniFrag >= this._cgl.maxUniformsFrag) this._log.warn("[cgl_shader] num uniforms frag: " + countUniFrag + " / " + this._cgl.maxUniformsFrag); 20610 if (countUniVert >= this._cgl.maxUniformsVert) this._log.warn("[cgl_shader] num uniforms vert: " + countUniVert + " / " + this._cgl.maxUniformsVert); 20611 20612 if (!fs.includes("precision")) fs = "precision " + this.precision + " float;" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + fs;
20613 if (!vs.includes("precision")) vs = "precision " + this.precision + " float;" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + vs; 20614 if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) 20615 { 20616 fs += "#define MOBILE" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20617 vs += "#define MOBILE" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20618 } 20619 vs = extensionString + vs + definesStr + structStrings[0] + uniformsStrVert + "\n// -- \n" + this.srcVert; 20620 fs = extensionString + fs + definesStr + structStrings[1] + uniformsStrFrag + "\n// -- \n" + this.srcFrag; 20621 20622 let srcHeadVert = ""; 20623 let srcHeadFrag = ""; 20624 20625 this._modules.sort(function (a, b) 20626 { 20627 return a.priority || 0 - b.priority || 0; 20628 }); 20629 20630 let addedAttribs = false; 20631 20632 for (let i = 0; i < this._moduleNames.length; i++) 20633 { 20634 let srcVert = ""; 20635 let srcFrag = ""; 20636 20637 if (!addedAttribs) 20638 { 20639 addedAttribs = true; 20640 20641 for (let k = 0; k < this._attributes.length; k++) 20642 { 20643 const r = this._getAttrSrc(this._attributes[k], true); 20644 if (r.srcHeadVert)srcHeadVert += r.srcHeadVert; 20645 if (r.srcVert)srcVert += r.srcVert; 20646 if (r.srcHeadFrag)srcHeadFrag += r.srcHeadFrag; 20647 } 20648 } 20649 20650 for (let j = 0; j < this._modules.length; j++) 20651 { 20652 const mod = this._modules[j]; 20653 if (mod.name == this._moduleNames[i]) 20654 { 20655 srcHeadVert += "\n//---- MOD: group:" + mod.group + ": idx:" + j + " - prfx:" + mod.prefix + " - " + mod.title + " ------\n"; 20656 srcHeadFrag += "\n//---- MOD: group:" + mod.group + ": idx:" + j + " - prfx:" + mod.prefix + " - " + mod.title + " ------\n"; 20657 20658 srcVert += "\n\n//---- MOD: " + mod.title + " / " + mod.priority + " ------\n"; 20659 srcFrag += "\n\n//---- MOD: " + mod.title + " / " + mod.priority + " ------\n"; 20660 20661 if (mod.attributes) 20662 for (let k = 0; k < mod.attributes.length; k++) 20663 { 20664 const r = this._getAttrSrc(mod.attributes[k], false); 20665 if (r.srcHeadVert)srcHeadVert += r.srcHeadVert; 20666 if (r.srcVert)srcVert += r.srcVert; 20667 if (r.srcHeadFrag)srcHeadFrag += r.srcHeadFrag; 20668 } 20669 20670 srcHeadVert += mod.srcHeadVert || ""; 20671 srcHeadFrag += mod.srcHeadFrag || ""; 20672 srcVert += mod.srcBodyVert || ""; 20673 srcFrag += mod.srcBodyFrag || ""; 20674 20675 srcHeadVert += "\n//---- end mod ------\n"; 20676 srcHeadFrag += "\n//---- end mod ------\n"; 20677 20678 srcVert += "\n//---- end mod ------\n"; 20679 srcFrag += "\n//---- end mod ------\n"; 20680 20681 srcVert = srcVert.replace(/{{mod}}/g, mod.prefix); 20682 srcFrag = srcFrag.replace(/{{mod}}/g, mod.prefix); 20683 srcHeadVert = srcHeadVert.replace(/{{mod}}/g, mod.prefix); 20684 srcHeadFrag = srcHeadFrag.replace(/{{mod}}/g, mod.prefix); 20685 20686 srcVert = srcVert.replace(/MOD_/g, mod.prefix); 20687 srcFrag = srcFrag.replace(/MOD_/g, mod.prefix); 20688 srcHeadVert = srcHeadVert.replace(/MOD_/g, mod.prefix); 20689 srcHeadFrag = srcHeadFrag.replace(/MOD_/g, mod.prefix); 20690 } 20691 } 20692 20693 vs = vs.replace("{{" + this._moduleNames[i] + "}}", srcVert); 20694 fs = fs.replace("{{" + this._moduleNames[i] + "}}", srcFrag); 20695 } 20696 20697 vs = vs.replace("{{MODULES_HEAD}}", srcHeadVert); 20698 fs = fs.replace("{{MODULES_HEAD}}", srcHeadFrag); 20699 20700 vs = this._addLibs(vs); 20701 fs = this._addLibs(fs); 20702 20703 // SETUP draw buffers / multi texture render targets 20704 20705 let drawBufferStr = ""; 20706 for (let i = 0; i < 16; i++) 20707 if (fs.includes("outColor" + i)) this._drawBuffers[i] = true; 20708 20709 if (this._drawBuffers.length == 1) 20710 { 20711 drawBufferStr = "out vec4 outColor;" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20712 drawBufferStr += "#define gl_FragColor outColor" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20713 } 20714 else 20715 { 20716 drawBufferStr += "#define MULTI_COLORTARGETS" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20717 drawBufferStr += "vec4 outColor;" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20718 20719 let count = 0; 20720 for (let i = 0; i < this._drawBuffers.length; i++) 20721 { 20722 if (count == 0) drawBufferStr += "#define gl_FragColor outColor" + i + "" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20723 drawBufferStr += "layout(location = " + i + ") out vec4 outColor" + i + ";" + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl; 20724 count++; 20725 } 20726 } 20727 20728 fs = fs.replace("{{DRAWBUFFER}}", drawBufferStr); 20729 // ////// 20730 20731 if (!this._program) 20732 { 20733 this._program = this._createProgram(vs, fs); 20734 } 20735 else 20736 { 20737 // this.vshader=createShader(vs, gl.VERTEX_SHADER, this.vshader ); 20738 // this.fshader=createShader(fs, gl.FRAGMENT_SHADER, this.fshader ); 20739 // linkProgram(program); 20740 this._program = this._createProgram(vs, fs); 20741 20742 this._projMatrixUniform = null; 20743 20744 for (let i = 0; i < this._uniforms.length; i++) this._uniforms[i].resetLoc(); 20745 } 20746 20747 this.finalShaderFrag = fs; 20748 this.finalShaderVert = vs; 20749 20750 _cgl_mesh_js__WEBPACK_IMPORTED_MODULE_5__.MESH.lastMesh = null; 20751 _cgl_mesh_js__WEBPACK_IMPORTED_MODULE_5__.MESH.lastShader = null; 20752 20753 this._countMissingUniforms = 0; 20754 this._needsRecompile = false;
20755 this.lastCompile = (0,cables__WEBPACK_IMPORTED_MODULE_6__.now)(); 20756 20757 this._cgl.profileData.shaderCompileTime += performance.now() - startTime; 20758 } 20759 20760 bind() 20761 { 20762 if (!this._isValid || this._cgl.aborted) return; 20763 20764 _cgl_mesh_js__WEBPACK_IMPORTED_MODULE_5__.MESH.lastShader = this; 20765 20766 if (!this._program || this.needsRecompile()) this.compile(); 20767 if (!this._isValid) return; 20768 20769 if (!this._projMatrixUniform && !this.ignoreMissingUniforms) 20770 { 20771 this._countMissingUniforms++; 20772 // if (this._countMissingUniforms == 10)this._log.log("stopping getlocation of missing uniforms...", this._name); 20773 if (this._countMissingUniforms < 10) 20774 { 20775 this._projMatrixUniform = this._cgl.gl.getUniformLocation(this._program, _constants_js__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.SHADER.SHADERVAR_UNI_PROJMAT); 20776 this._attrVertexPos = this._cgl.glGetAttribLocation(this._program, _constants_js__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.SHADER.SHADERVAR_VERTEX_POSITION); 20777 this._mvMatrixUniform = this._cgl.gl.getUniformLocation(this._program, "mvMatrix"); 20778 this._vMatrixUniform = this._cgl.gl.getUniformLocation(this._program, _constants_js__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.SHADER.SHADERVAR_UNI_VIEWMAT); 20779 this._mMatrixUniform = this._cgl.gl.getUniformLocation(this._program, _constants_js__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.SHADER.SHADERVAR_UNI_MODELMAT); 20780 this._camPosUniform = this._cgl.gl.getUniformLocation(this._program, _constants_js__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.SHADER.SHADERVAR_UNI_VIEWPOS); 20781 this._normalMatrixUniform = this._cgl.gl.getUniformLocation(this._program, _constants_js__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.SHADER.SHADERVAR_UNI_NORMALMAT); 20782 this._inverseViewMatrixUniform = this._cgl.gl.getUniformLocation(this._program, _constants_js__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.SHADER.SHADERVAR_UNI_INVVIEWMAT); 20783 this._inverseProjMatrixUniform = this._cgl.gl.getUniformLocation(this._program, _constants_js__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.SHADER.SHADERVAR_UNI_INVPROJMAT); 20784 this._materialIdUniform = this._cgl.gl.getUniformLocation(this._program, _constants_js__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.SHADER.SHADERVAR_UNI_MATERIALID); 20785 this._objectIdUniform = this._cgl.gl.getUniformLocation(this._program, _constants_js__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.SHADER.SHADERVAR_UNI_OBJECTID); 20786 20787 for (let i = 0; i < this._uniforms.length; i++) this._uniforms[i].needsUpdate = true; 20788 } 20789 } 20790 20791 if (this._cgl.currentProgram != this._program) 20792 { 20793 this._cgl.profileData.profileShaderBinds++; 20794 this._cgl.gl.useProgram(this._program); 20795 this._cgl.currentProgram = this._program; 20796 } 20797 20798 for (let i = 0; i < this._uniforms.length; i++) 20799 if (this._uniforms[i].needsUpdate) this._uniforms[i].updateValue(); 20800 20801 if (this._pMatrixState != this._cgl.getProjectionMatrixStateCount()) 20802 { 20803 this._pMatrixState = this._cgl.getProjectionMatrixStateCount(); 20804 this._cgl.gl.uniformMatrix4fv(this._projMatrixUniform, false, this._cgl.pMatrix); 20805 this._cgl.profileData.profileMVPMatrixCount++; 20806 } 20807 20808 if (this._objectIdUniform) 20809 this._cgl.gl.uniform1f(this._objectIdUniform, ++this._cgl.tempData.objectIdCounter); 20810 20811 if (this._materialIdUniform) 20812 this._cgl.gl.uniform1f(this._materialIdUniform, this._materialId); 20813 20814 if (this._vMatrixUniform) 20815 { 20816 if (this._vMatrixState != this._cgl.getViewMatrixStateCount()) 20817 { 20818 this._cgl.gl.uniformMatrix4fv(this._vMatrixUniform, false, this._cgl.vMatrix); 20819 this._cgl.profileData.profileMVPMatrixCount++; 20820 this._vMatrixState = this._cgl.getViewMatrixStateCount(); 20821 20822 if (this._inverseViewMatrixUniform) 20823 { 20824 gl_matrix__WEBPACK_IMPORTED_MODULE_3__.invert(this._tempInverseViewMatrix, this._cgl.vMatrix); 20825 this._cgl.gl.uniformMatrix4fv(this._inverseViewMatrixUniform, false, this._tempInverseViewMatrix); 20826 this._cgl.profileData.profileMVPMatrixCount++; 20827 } 20828 if (this._inverseProjMatrixUniform) 20829 { 20830 gl_matrix__WEBPACK_IMPORTED_MODULE_3__.invert(this._tempInverseProjMatrix, this._cgl.pMatrix); 20831 this._cgl.gl.uniformMatrix4fv(this._inverseProjMatrixUniform, false, this._tempInverseProjMatrix); 20832 this._cgl.profileData.profileMVPMatrixCount++; 20833 } 20834 } 20835 this._cgl.gl.uniformMatrix4fv(this._mMatrixUniform, false, this._cgl.mMatrix); 20836 this._cgl.profileData.profileMVPMatrixCount++; 20837 20838 if (this._camPosUniform) 20839 { 20840 gl_matrix__WEBPACK_IMPORTED_MODULE_3__.invert(this._tempCamPosMatrix, this._cgl.vMatrix); 20841 this._cgl.gl.uniform3f(this._camPosUniform, this._tempCamPosMatrix[12], this._tempCamPosMatrix[13], this._tempCamPosMatrix[14]); 20842 this._cgl.profileData.profileMVPMatrixCount++; 20843 } 20844 } 20845 else 20846 { 20847 // mvmatrix deprecated.... 20848 const tempmv = gl_matrix__WEBPACK_IMPORTED_MODULE_3__.create(); 20849 20850 gl_matrix__WEBPACK_IMPORTED_MODULE_3__.mul(tempmv, this._cgl.vMatrix, this._cgl.mMatrix); 20851 this._cgl.gl.uniformMatrix4fv(this._mvMatrixUniform, false, tempmv); 20852 this._cgl.profileData.profileMVPMatrixCount++; 20853 } 20854 20855 if (this._normalMatrixUniform) 20856 { 20857 // mat4.mul(this._tempNormalMatrix, this._cgl.vMatrix, this._cgl.mMatrix); 20858 gl_matrix__WEBPACK_IMPORTED_MODULE_3__.invert(this._tempNormalMatrix, this._cgl.mMatrix); 20859 gl_matrix__WEBPACK_IMPORTED_MODULE_3__.transpose(this._tempNormalMatrix, this._tempNormalMatrix); 20860 20861 this._cgl.gl.uniformMatrix4fv(this._normalMatrixUniform, false, this._tempNormalMatrix); 20862 this._cgl.profileData.profileMVPMatrixCount++; 20863 } 20864 20865 for (let i = 0; i < this._libs.length; i++) 20866 { 20867 if (this._libs[i].onBind) this._libs[i].onBind.bind(this._libs[i])(this._cgl, this); 20868 } 20869 20870 this._bindTextures(); 20871 20872 return this._isValid; 20873 } 20874 20875 unBind() 20876 { 20877 } 20878 20879 dispose() 20880 { 20881 20882 if (this._program && this._cgl && this._cgl.gl) this._cgl.gl.deleteProgram(this._program); 20883 this._program = null; 20884 } 20885 20886 setDrawBuffers(arr) 20887 { 20888 this._log.warn("useless drawbuffers...?!"); 20889 } 20890 20891 getUniforms() 20892 { 20893 return this._uniforms; 20894 } 20895 20896 getUniform(name) 20897 { 20898 for (let i = 0; i < this._uniforms.length; i++) 20899 if (this._uniforms[i].getName() == name) 20900 return this._uniforms[i]; 20901 return null; 20902 } 20903 20904 removeAllUniforms() 20905 { 20906 this._uniforms = []; 20907 // for (let i = 0; i < this._uniforms.length; i++) 20908 // this.removeUniform(this._uniforms[i].name); 20909 } 20910 20911 _addUniform(uni) 20912 { 20913 this._uniforms.push(uni); 20914 this.setWhyCompile("add uniform " + name); 20915 } 20916 20917 /** 20918 * add a uniform to the fragment shader 20919 * @param {String} type ['f','t', etc] 20920 * @param {String} name 20921 * @param {any} valueOrPort value or port 20922 * @param p2 20923 * @param p3 20924 * @param p4 20925 * @returns {Uniform} 20926 */ 20927 addUniformFrag(type, name, valueOrPort, p2, p3, p4) 20928 { 20929 const uni = new _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_7__.Uniform(this, type, name, valueOrPort, p2, p3, p4); 20930 uni.shaderType = "frag"; 20931 return uni; 20932 } 20933 20934 /** 20935 * add a uniform to the vertex shader 20936 * @param {String} type ['f','t', etc] 20937 * @param {String} name 20938 * @param {any} valueOrPort value or port 20939 * @param p2 20940 * @param p3 20941 * @param p4 20942 * @returns {Uniform} 20943 */ 20944 addUniformVert(type, name, valueOrPort, p2, p3, p4) 20945 { 20946 const uni = new _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_7__.Uniform(this, type, name, valueOrPort, p2, p3, p4); 20947 uni.shaderType = "vert"; 20948 return uni; 20949 } 20950 20951 /** 20952 * add a uniform to both shaders 20953 * @param {String} type ['f','t', etc] 20954 * @param {String} name 20955 * @param {any} valueOrPort value or port 20956 * @param p2 20957 * @param p3 20958 * @param p4 20959 * @returns {Uniform} 20960 */ 20961 addUniformBoth(type, name, valueOrPort, p2, p3, p4) 20962 { 20963 const uni = new _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_7__.Uniform(this, type, name, valueOrPort, p2, p3, p4); 20964 uni.shaderType = "both"; 20965 return uni; 20966 } 20967 20968 /** 20969 * add a struct & its uniforms to the fragment shader 20970 * @param {String} structName name of the struct, i.e.: LightStruct 20971 * @param {String} uniformName name of the struct uniform in the shader, i.e.: lightUni 20972 * @param {Array} members array of objects containing the struct members. see example for structure 20973 20974 * @returns {Object} 20975 * @example 20976 * const shader = new CGL.Shader(cgl, 'MinimalMaterial'); 20977 * shader.setSource(attachments.shader_vert, attachments.shader_frag); 20978 * shader.addUniformStructFrag("Light", "uniformLight", [ 20979 * { "type": "3f", "name": "position", "v1": null }, 20980 * { "type": "4f", "name": "color", "v1": inR, v2: inG, v3: inB, v4: inAlpha } 20981 * ]); 20982 */ 20983 addUniformStructFrag(structName, uniformName, members) 20984 { 20985 const uniforms = {}; 20986 20987 if (!members) return uniforms; 20988 20989 for (let i = 0; i < members.length; i += 1) 20990 { 20991 const member = members[i]; 20992 if (!this.hasUniform(uniformName + "." + member.name)) 20993 { 20994 const uni = new _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_7__.Uniform(this, member.type, uniformName + "." + member.name, member.v1, member.v2, member.v3, member.v4, uniformName, structName, member.name); 20995 uni.shaderType = "frag"; 20996 uniforms[uniformName + "." + member.name] = uni; 20997 } 20998 } 20999 21000 return uniforms; 21001 } 21002 21003 /** 21004 * add a struct & its uniforms to the vertex shader 21005 * @param {String} structName name of the struct, i.e.: LightStruct 21006 * @param {String} uniformName name of the struct uniform in the shader, i.e.: lightUni 21007 * @param {Array} members array of objects containing the struct members. see example for structure 21008 * @returns {object} 21009 * @example 21010 * const shader = new CGL.Shader(cgl, 'MinimalMaterial'); 21011 * shader.setSource(attachments.shader_vert, attachments.shader_frag); 21012 * shader.addUniformStructVert("Light", "uniformLight", [ 21013 * { "type": "3f", "name": "position", "v1": null }, 21014 * { "type": "4f", "name": "color", "v1": inR, v2: inG, v3: inB, v4: inAlpha } 21015 * ]); 21016 */ 21017 addUniformStructVert(structName, uniformName, members) 21018 { 21019 const uniforms = {}; 21020 21021 if (!members) return uniforms; 21022 21023 for (let i = 0; i < members.length; i += 1) 21024 { 21025 const member = members[i]; 21026 if (!this.hasUniform(uniformName + "." + member.name)) 21027 { 21028 const uni = new _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_7__.Uniform(this, member.type, uniformName + "." + member.name, member.v1, member.v2, member.v3, member.v4, uniformName, structName, member.name); 21029 uni.shaderType = "vert"; 21030 uniforms[uniformName + "." + member.name] = uni; 21031 } 21032 } 21033 21034 return uniforms; 21035 } 21036 21037 /**
21038 * add a struct & its uniforms to the both shaders. PLEASE NOTE: it is not possible to add the same struct to both shaders when it contains ANY integer members. 21039 * @param {String} structName name of the struct, i.e.: LightStruct 21040 * @param {String} uniformName name of the struct uniform in the shader, i.e.: lightUni 21041 * @param {Array} members array of objects containing the struct members. see example for structure 21042 21043 * @returns {Object} 21044 * @example 21045 * const shader = new CGL.Shader(cgl, 'MinimalMaterial'); 21046 * shader.setSource(attachments.shader_vert, attachments.shader_frag); 21047 * shader.addUniformStructBoth("Light", "uniformLight", [ 21048 * { "type": "3f", "name": "position", "v1": null }, 21049 * { "type": "4f", "name": "color", "v1": inR, v2: inG, v3: inB, v4: inAlpha } 21050 * ]); 21051 */ 21052 addUniformStructBoth(structName, uniformName, members) 21053 { 21054 const uniforms = {}; 21055 21056 if (!members) return uniforms; 21057 21058 for (let i = 0; i < members.length; i += 1) 21059 { 21060 const member = members[i]; 21061 if ((member.type === "2i" || member.type === "i" || member.type === "3i")) 21062 this._log.error("Adding an integer struct member to both shaders can potentially error. Please use different structs for each shader. Error occured in struct:", structName, " with member:", member.name, " of type:", member.type, "."); 21063 if (!this.hasUniform(uniformName + "." + member.name)) 21064 { 21065 const uni = new _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_7__.Uniform(this, member.type, uniformName + "." + member.name, member.v1, member.v2, member.v3, member.v4, uniformName, structName, member.name); 21066 uni.shaderType = "both"; 21067 uniforms[uniformName + "." + member.name] = uni; 21068 } 21069 } 21070 21071 return uniforms; 21072 } 21073 21074 /** 21075 * @param {String} vstr 21076 * @param {String} fstr 21077 */ 21078 _createProgram(vstr, fstr) 21079 { 21080 this._cgl.printError("before _createprogram"); 21081 21082 const program = this._cgl.gl.createProgram(); 21083 21084 this.vshader = CglShader.createShader(this._cgl, vstr, this._cgl.gl.VERTEX_SHADER, this); 21085 this.fshader = CglShader.createShader(this._cgl, fstr, this._cgl.gl.FRAGMENT_SHADER, this); 21086 21087 if (this.vshader && this.fshader) 21088 { 21089 this._cgl.gl.attachShader(program, this.vshader); 21090 this._cgl.gl.attachShader(program, this.fshader); 21091 21092 this._linkProgram(program, vstr, fstr); 21093 } 21094 else 21095 { 21096 this._isValid = false; 21097 this._cgl.printError("shader _createProgram"); 21098 this._log.error("could not link shaderprogram"); 21099 return null; 21100 } 21101 21102 this._cgl.printError("shader _createProgram"); 21103 return program; 21104 } 21105 21106 hasErrors() 21107 { 21108 return this._hasErrors; 21109 } 21110 21111 /** 21112 * @param {any} program 21113 * @param {string} vstr 21114 * @param {string} fstr 21115 */ 21116 _linkProgram(program, vstr, fstr) 21117 { 21118 this._cgl.printError("before _linkprogram"); 21119 21120 if (this._feedBackNames.length > 0) 21121 { 21122 this._cgl.gl.transformFeedbackVaryings(program, this._feedBackNames, this._cgl.gl.SEPARATE_ATTRIBS); 21123 // INTERLEAVED_ATTRIBS 21124 // SEPARATE_ATTRIBS 21125 } 21126 21127 this._cgl.gl.linkProgram(program); 21128 this._cgl.printError("gl.linkprogram"); 21129 this._isValid = true; 21130 this._hasErrors = false; 21131 21132 if (this._cgl.patch.config.glValidateShader !== false) 21133 { 21134 this._cgl.gl.validateProgram(program); 21135 21136 if (!this._cgl.gl.getProgramParameter(program, this._cgl.gl.VALIDATE_STATUS)) 21137 { 21138 // validation failed 21139 this._log.log("shaderprogram validation failed..."); 21140 21141 this._cgl.gl.getProgramInfoLog(program); 21142 } 21143 21144 if (!this._cgl.gl.getProgramParameter(program, this._cgl.gl.LINK_STATUS)) 21145 { 21146 this._hasErrors = true; 21147 21148 const infoLogFrag = this._cgl.gl.getShaderInfoLog(this.fshader); 21149 const infoLogVert = this._cgl.gl.getShaderInfoLog(this.vshader); 21150 21151 if (this.logError) 21152 this._log.error(this._name + " shader linking fail..."); 21153 else 21154 this._log.warn(this._name + " shader linking fail..."); 21155 21156 if (infoLogFrag) this._log.warn(this._cgl.gl.getShaderInfoLog(this.fshader)); 21157 if (infoLogVert) this._log.warn(this._cgl.gl.getShaderInfoLog(this.vshader)); 21158 21159 this._cgl.gl.getProgramInfoLog(program); 21160 if (!CABLES.UI) this._log.log(this); 21161 this._isValid = false;
21162 21163 this._cgl.printError("shader link err"); 21164 } 21165 } 21166 } 21167 21168 getProgram() 21169 { 21170 return this._program; 21171 } 21172 21173 /** 21174 * @param {any[]} names 21175 */ 21176 setFeedbackNames(names) 21177 { 21178 this.setWhyCompile("setFeedbackNames"); 21179 this._feedBackNames = names; 21180 } 21181 21182 /** 21183 * adds attribute definition to shader header without colliding with other shader modules... 21184 * when attrFrag is defined, vertex shader will output this attribute to the fragment shader 21185 * @param {Object} attr {type:x,name:x,[nameFrag:x]} 21186 * @return {Object} 21187 */ 21188 addAttribute(attr) 21189 { 21190 for (let i = 0; i < this._attributes.length; i++) 21191 { 21192 if (this._attributes[i].name == attr.name && this._attributes[i].nameFrag == attr.nameFrag) return; 21193 } 21194 this._attributes.push(attr); 21195 21196 this.setWhyCompile("addAttribute"); 21197 } 21198 21199 bindTextures() 21200 { 21201 this._bindTextures(); 21202 } 21203 21204 _bindTextures() 21205 { 21206 if (this._textureStackTex.length > this._cgl.maxTextureUnits) 21207 { 21208 this._log.warn("[shader._bindTextures] too many textures bound", this._textureStackTex.length + "/" + this._cgl.maxTextureUnits); 21209 } 21210 21211 // for (let i = this._textureStackTex.length + 1; i < this._cgl.maxTextureUnits; i++) this._cgl.setTexture(i, null); 21212 21213 for (let i = 0; i < this._textureStackTex.length; i++) 21214 { 21215 // this._log.log(this._textureStackTex.length, i); 21216 if (!this._textureStackTex[i] && !this._textureStackTexCgl[i]) 21217 { 21218 this._log.warn("no texture for pushtexture", this._name); 21219 } 21220 else 21221 { 21222 let t = this._textureStackTex[i]; 21223 if (this._textureStackTexCgl[i]) 21224 { 21225 t = this._textureStackTexCgl[i].tex || CGL.Texture.getEmptyTexture(this._cgl).tex; 21226 } 21227 21228 let bindOk = true; 21229 21230 if (!this._textureStackUni[i]) 21231 { 21232 // throw(new Error('no uniform given to texturestack')); 21233 this._log.warn("no uniform for pushtexture", this._name); 21234 bindOk = this._cgl.setTexture(i, t, this._textureStackType[i]); 21235 } 21236 else 21237 { 21238 this._textureStackUni[i].setValue(i); 21239 bindOk = this._cgl.setTexture(i, t, this._textureStackType[i]); 21240 21241 // this._log.log(bindOk, i, t, this._textureStackType[i]); 21242 } 21243 if (!bindOk) this._log.warn("tex bind failed", this.getName(), this._textureStackUni[i]); 21244 } 21245 } 21246 } 21247 21248 /** 21249 * @param {Uniform} uni 21250 * @param {Texture} tex 21251 */ 21252 setUniformTexture(uni, tex) 21253 { 21254 tex = tex || _cgl_texture_js__WEBPACK_IMPORTED_MODULE_8__.Texture.getTempTexture(this._cgl); 21255 for (let i = 0; i < this._textureStackUni.length; i++) 21256 if (this._textureStackUni[i] == uni) 21257 { 21258 const old = this._textureStackTex[i] || this._textureStackTexCgl[i]; 21259 if (tex.hasOwnProperty("tex")) 21260 { 21261 this._textureStackTexCgl[i] = tex; 21262 this._textureStackTex[i] = null; 21263 } 21264 else 21265 { 21266 this._textureStackTexCgl[i] = null; 21267 this._textureStackTex[i] = tex; 21268 } 21269 21270 // this._textureStackTex[i] = tex; 21271 // this._cgl.setTexture(i, tex, this._textureStackType[i]); 21272 return old; 21273 } 21274 return null; 21275 } 21276 21277 /** 21278 * push a texture on the stack. those textures will be bound when binding the shader. texture slots are automatically set 21279 * @param {Uniform} uniform texture uniform 21280 * @param {Texture} t texture 21281 * @param {number} type texture type, can be ignored when TEXTURE_2D 21282 */ 21283 pushTexture(uniform, t, type) 21284 { 21285 if (!uniform) 21286 { 21287 // this._log.log("pushtexture: no uniform given to texturestack", "shader:"+this._name,uniform,t,type); 21288 return; 21289 } 21290 if (!t) 21291 { 21292 // if(uniform)this._log.warn("pushtexture: no tex","shader:"+this._name," uniform:"+uniform.name); 21293 return; 21294 } 21295 if (!t.hasOwnProperty("tex") && !(t instanceof WebGLTexture)) 21296 { 21297 this._log.warn(new Error("invalid texture").stack); 21298
21299 this._log.warn("[cgl_shader] invalid texture...", t); 21300 return; 21301 } 21302 21303 this._textureStackUni.push(uniform); 21304 21305 if (t.hasOwnProperty("tex")) 21306 { 21307 this._textureStackTexCgl.push(t); 21308 this._textureStackTex.push(null); 21309 } 21310 else 21311 { 21312 this._textureStackTexCgl.push(null); 21313 this._textureStackTex.push(t); 21314 } 21315 21316 this._textureStackType.push(type); 21317 } 21318 21319 /** 21320 * pop last texture 21321 */ 21322 popTexture() 21323 { 21324 this._textureStackUni.pop(); 21325 this._textureStackTex.pop(); 21326 this._textureStackTexCgl.pop(); 21327 this._textureStackType.pop(); 21328 } 21329 21330 /** 21331 * pop all textures 21332 */ 21333 popTextures() 21334 { 21335 this._textureStackTex.length = 21336 this._textureStackTexCgl.length = 21337 this._textureStackType.length = 21338 this._textureStackUni.length = 0; 21339 } 21340 21341 getMaterialId() 21342 { 21343 return this._materialId; 21344 } 21345 21346 getInfo() 21347 { 21348 const info = {}; 21349 info.name = this._name; 21350 // info.modules = JSON.parse(JSON.stringify(this._modules)); 21351 // info.defines = JSON.parse(JSON.stringify(this._defines)); 21352 info.defines = this.getDefines(); 21353 info.hasErrors = this.hasErrors(); 21354 21355 return info; 21356 } 21357 21358 getDefaultFragmentShader(r, g, b, a) 21359 { 21360 return getDefaultFragmentShader(r, g, b, a); 21361 } 21362 21363 getDefaultVertexShader() 21364 { 21365 return getDefaultVertexShader(); 21366 } 21367} 21368 21369// -------------------------- 21370 21371CglShader.getDefaultVertexShader = getDefaultVertexShader; 21372CglShader.getDefaultFragmentShader = getDefaultFragmentShader; 21373 21374CglShader.getErrorFragmentShader = function () 21375{ 21376 return "" 21377 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "void main()" 21378 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "{" 21379 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + " float g=mod((gl_FragCoord.y+gl_FragCoord.x),50.0)/50.0;" 21380 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + " g= step(0.1,g);" 21381 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + " outColor = vec4( g+0.5, 0.0, 0.0, 1.0);" 21382 + _constants_js__WEBPACK_IMPORTED_MODULE_0__.nl + "}"; 21383}; 21384 21385/** 21386 * @param {CglContext} cgl 21387 * @param {String} str 21388 * @param {number} type 21389 * @param {CglShader} cglShader 21390 * @returns {CglShader} 21391 */ 21392CglShader.createShader = function (cgl, str, type, cglShader) 21393{ 21394 if (cgl.aborted) return; 21395 21396 const shader = cgl.gl.createShader(type); 21397 cgl.gl.shaderSource(shader, str); 21398 cgl.gl.compileShader(shader); 21399 21400 if (!cgl.gl.getShaderParameter(shader, cgl.gl.COMPILE_STATUS)) 21401 { 21402 cglShader.error = { "str": str, "infoLog": cgl.gl.getShaderInfoLog(shader) }; 21403 21404 if (CABLES.UI) gui.emitEvent("ShaderError", cglShader); 21405 21406 if (!cglShader.error.infoLog) 21407 { 21408 cglShader._log.warn("empty shader info log", this._name); 21409 return; 21410 } 21411 cglShader.setSource(CglShader.getDefaultVertexShader(), CglShader.getErrorFragmentShader()); 21412 } 21413 return shader; 21414}; 21415 21416 21417 21418 21419/***/ }), 21420
21421/***/ "./src/corelibs/cgl/cgl_shader_lib.js": 21422/*!********************************************!*\ 21423 !*** ./src/corelibs/cgl/cgl_shader_lib.js ***! 21424 \********************************************/ 21425/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 21426 21427"use strict"; 21428/* harmony export */ __webpack_require__.d(__webpack_exports__, { 21429/* harmony export */ ShaderLibMods: () => (/* binding */ ShaderLibMods) 21430/* harmony export */ }); 21431/* harmony import */ var _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cgl_shader_uniform.js */ "./src/corelibs/cgl/cgl_shader_uniform.js"); 21432/* harmony import */ var _cgl_textureeffect_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./cgl_textureeffect.js */ "./src/corelibs/cgl/cgl_textureeffect.js"); 21433/* harmony import */ var _cgl_texture_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./cgl_texture.js */ "./src/corelibs/cgl/cgl_texture.js"); 21434 21435 21436 21437 21438/** @type {Object} */ 21439const ShaderLibMods = { 21440 "CGL.BLENDMODES": function () 21441 { 21442 this.name = "blendmodes"; 21443 this.srcHeadFrag = _cgl_textureeffect_js__WEBPACK_IMPORTED_MODULE_0__.TextureEffect.getBlendCode(); 21444 }, 21445 21446 "CGL.BLENDMODES3": function () 21447 { 21448 this.name = "blendmodes3"; 21449 this.srcHeadFrag = _cgl_textureeffect_js__WEBPACK_IMPORTED_MODULE_0__.TextureEffect.getBlendCode(3); 21450 }, 21451 21452 "CGL.LUMINANCE": function () 21453 { 21454 this.name = "luminance"; 21455 this.srcHeadFrag = "".endl() 21456 + "float cgl_luminance(vec3 c)".endl() 21457 + "{".endl() 21458 + " return dot(vec3(0.2126,0.7152,0.0722),c);".endl() 21459 + "}".endl(); 21460 }, 21461 21462 // quite good random numbers, but somehow don't work in ANGLE 21463 "CGL.RANDOM_OLD": function () 21464 { 21465 this.name = "randomNumber"; 21466 this.srcHeadFrag = "".endl() 21467 + "float cgl_random(vec2 co)".endl() 21468 + "{".endl() 21469 + " return fract(sin(dot(co.xy ,vec2(12.9898,4.1414))) * 432758.5453);".endl() 21470 + "}".endl() 21471 + "vec3 cgl_random3(vec2 co)".endl() 21472 + "{".endl() 21473 + " return vec3( cgl_random(co),cgl_random(co+0.5711),cgl_random(co+1.5711));".endl() 21474 + "}"; 21475 }, 21476 21477 // low quality generative ranodm numbers 21478 "CGL.RANDOM_LOW": function () 21479 { 21480 this.name = "randomNumber"; 21481 this.srcHeadFrag = "".endl() 21482 + "float cgl_random(vec2 co)".endl() 21483 + "{".endl() 21484 + " return fract(sin(dot(co.xy ,vec2(12.9898,4.1414))) * 358.5453);".endl() 21485 + "}".endl() 21486 + "vec3 cgl_random3(vec2 co)".endl() 21487 + "{".endl() 21488 + " return vec3( cgl_random(co),cgl_random(co+0.5711),cgl_random(co+1.5711));".endl() 21489 + "}"; 21490 }, 21491 21492 "CGL.RANDOM_TEX": function () 21493 { 21494 this.name = "randomNumbertex"; 21495 21496 this.srcHeadFrag = "".endl() 21497 + "UNI sampler2D CGLRNDTEX;".endl() 21498 + "float cgl_random(vec2 co)".endl() 21499 + "{".endl() 21500 + " return texture(CGLRNDTEX,co*5711.0).r;".endl() 21501 + "}".endl() 21502 + "vec3 cgl_random3(vec2 co)".endl() 21503 + "{".endl() 21504 + " return texture(CGLRNDTEX,co*5711.0).rgb;".endl() 21505 + "}"; 21506 21507 this.initUniforms = function (shader) 21508 { 21509 return [new _cgl_shader_uniform_js__WEBPACK_IMPORTED_MODULE_1__.Uniform(shader, "t", "CGLRNDTEX", 7)]; 21510 }; 21511 21512 this.onBind = function (cgl, shader) 21513 { 21514 _cgl_texture_js__WEBPACK_IMPORTED_MODULE_2__.Texture.getRandomTexture(cgl); 21515 cgl.setTexture(7, _cgl_texture_js__WEBPACK_IMPORTED_MODULE_2__.Texture.getRandomTexture(cgl).tex); 21516 }; 21517 } 21518 21519}; 21520 21521 21522/***/ }), 21523
21524/***/ "./src/corelibs/cgl/cgl_shader_uniform.js": 21525/*!************************************************!*\ 21526 !*** ./src/corelibs/cgl/cgl_shader_uniform.js ***! 21527 \************************************************/ 21528/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 21529 21530"use strict"; 21531/* harmony export */ __webpack_require__.d(__webpack_exports__, { 21532/* harmony export */ Uniform: () => (/* binding */ Uniform) 21533/* harmony export */ }); 21534/* harmony import */ var _cg_cg_uniform_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../cg/cg_uniform.js */ "./src/corelibs/cg/cg_uniform.js"); 21535 21536 21537 21538 21539/** 21540 * Shader uniforms 21541 * 21542 * types: 21543 * <pre> 21544 * f - float 21545 * 2f - vec2 21546 * 3f - vec3 21547 * 4f - vec4 21548 * i - integer 21549 * t - texture 21550 * m4 - mat4, 4x4 float matrix 21551 * f[] - array of floats 21552 * 2f[] - array of float vec2 21553 * 3f[] - array of float vec3 21554 * 4f[] - array of float vec4 21555 * </pre> 21556 * 21557 * @namespace external:CGL 21558 * @class 21559 * @param {CgShader} shader 21560 * @param {String} [type=f] 21561 * @param {String} name 21562 * @param {Number|Port} value can be a Number,Matrix or Port 21563 * @example 21564 * // bind float uniform called myfloat and initialize with value 1.0 21565 * const unir=new CGL.Uniform(shader,'f','myfloat',1.0); 21566 * unir.setValue(1.0); 21567 * 21568 * // bind float uniform called myfloat and automatically set it to input port value 21569 * const myPort=op.inFloat("input"); 21570 * const pv=new CGL.Uniform(shader,'f','myfloat',myPort); 21571 * 21572 */ 21573 21574// export const Uniform(__shader, __type, __name, _value, _port2, _port3, _port4, _structUniformName, _structName, _propertyName) 21575 21576class Uniform extends _cg_cg_uniform_js__WEBPACK_IMPORTED_MODULE_0__.CgUniform 21577{ 21578 constructor(__shader, __type, __name, _value, _port2, _port3, _port4, _structUniformName, _structName, _propertyName) 21579 { 21580 super(__shader, __type, __name, _value, _port2, _port3, _port4, _structUniformName, _structName, _propertyName); 21581 this._loc = -1; 21582 this._cgl = __shader._cgl; 21583 } 21584 21585 get name() 21586 { 21587 return this._name; 21588 } 21589 21590 copy(newShader) 21591 { 21592 const uni = new Uniform(newShader, this._type, this._name, this._value, this._port2, this._port3, this._port4, this._structUniformName, this._structName, this._propertyName); 21593 uni.shaderType = this.shaderType; 21594 return uni; 21595 } 21596 21597 /** 21598 * returns type as glsl type string. e.g. 'f' returns 'float' 21599 * @function getGlslTypeString 21600 * @memberof Uniform 21601 * @instance 21602 * @return {string} type as string 21603 */ 21604 getGlslTypeString() 21605 { 21606 return Uniform.glslTypeString(this._type); 21607 } 21608 21609 _isValidLoc() 21610 { 21611 return this._loc != -1;// && this._loc != null; 21612 } 21613 21614 resetLoc() 21615 { 21616 this._loc = -1; 21617 this.needsUpdate = true; 21618 } 21619 21620 bindTextures() {} 21621 21622 getLoc() 21623 { 21624 return this._loc; 21625 } 21626 21627 updateFromPort4f() 21628 { 21629 this._value[0] = this._port.get(); 21630 this._value[1] = this._port2.get(); 21631 this._value[2] = this._port3.get(); 21632 this._value[3] = this._port4.get(); 21633 this.setValue(this._value); 21634 } 21635 21636 updateFromPort3f() 21637 { 21638 this._value[0] = this._port.get(); 21639 this._value[1] = this._port2.get(); 21640 this._value[2] = this._port3.get(); 21641 this.setValue(this._value); 21642 } 21643 21644 updateFromPort2f() 21645 { 21646 this._value[0] = this._port.get(); 21647 this._value[1] = this._port2.get(); 21648 this.setValue(this._value); 21649 } 21650 21651 updateFromPort() 21652 { 21653 this.setValue(this._port.get()); 21654 } 21655 21656 updateValueF() 21657 { 21658 if (!this._isValidLoc()) this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21659 else this.needsUpdate = false; 21660 21661 this._shader.getCgl().gl.uniform1f(this._loc, this._value); 21662 this._cgl.profileData.profileUniformCount++; 21663 } 21664 21665 setValueF(v) 21666 { 21667 if (v != this._value) 21668 { 21669 this.needsUpdate = true; 21670 this._value = v; 21671 } 21672 } 21673 21674 updateValueI() 21675 { 21676 if (!this._isValidLoc()) this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21677 else this.needsUpdate = false;
21678 21679 this._shader.getCgl().gl.uniform1i(this._loc, this._value); 21680 this._cgl.profileData.profileUniformCount++; 21681 } 21682 21683 updateValue2I() 21684 { 21685 if (!this._value) return; 21686 21687 if (!this._isValidLoc()) 21688 { 21689 this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21690 this._cgl.profileData.profileShaderGetUniform++; 21691 this._cgl.profileData.profileShaderGetUniformName = this._name; 21692 } 21693 21694 this._shader.getCgl().gl.uniform2i(this._loc, this._value[0], this._value[1]); 21695 21696 this.needsUpdate = false; 21697 this._cgl.profileData.profileUniformCount++; 21698 } 21699 21700 updateValue3I() 21701 { 21702 if (!this._value) return; 21703 if (!this._isValidLoc()) 21704 { 21705 this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21706 this._cgl.profileData.profileShaderGetUniform++; 21707 this._cgl.profileData.profileShaderGetUniformName = this._name; 21708 } 21709 21710 this._shader.getCgl().gl.uniform3i(this._loc, this._value[0], this._value[1], this._value[2]); 21711 this.needsUpdate = false; 21712 this._cgl.profileData.profileUniformCount++; 21713 } 21714 21715 updateValue4I() 21716 { 21717 if (!this._isValidLoc()) 21718 { 21719 this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21720 this._cgl.profileData.profileShaderGetUniform++; 21721 this._cgl.profileData.profileShaderGetUniformName = this._name; 21722 } 21723 this._shader.getCgl().gl.uniform4i(this._loc, this._value[0], this._value[1], this._value[2], this._value[3]); 21724 this._cgl.profileData.profileUniformCount++; 21725 } 21726 21727 setValueI(v) 21728 { 21729 if (v != this._value) 21730 { 21731 this.needsUpdate = true; 21732 this._value = v; 21733 } 21734 } 21735 21736 setValue2I(v) 21737 { 21738 if (!v) return; 21739 if (!this._oldValue) 21740 { 21741 this._oldValue = [v[0] - 1, 1]; 21742 this.needsUpdate = true; 21743 } 21744 else if (v[0] != this._oldValue[0] || v[1] != this._oldValue[1]) 21745 { 21746 this._oldValue[0] = v[0]; 21747 this._oldValue[1] = v[1]; 21748 this.needsUpdate = true; 21749 } 21750 21751 this._value = v; 21752 } 21753 21754 setValue3I(v) 21755 { 21756 if (!v) return; 21757 if (!this._oldValue) 21758 { 21759 this._oldValue = [v[0] - 1, 1, 2]; 21760 this.needsUpdate = true; 21761 } 21762 else if (v[0] != this._oldValue[0] || v[1] != this._oldValue[1] || v[2] != this._oldValue[2]) 21763 { 21764 this._oldValue[0] = v[0]; 21765 this._oldValue[1] = v[1]; 21766 this._oldValue[2] = v[2]; 21767 this.needsUpdate = true; 21768 } 21769 21770 this._value = v; 21771 } 21772 21773 setValue4I(v) 21774 { 21775 this.needsUpdate = true; 21776 this._value = v || vec4.create(); 21777 } 21778 21779 updateValueBool() 21780 { 21781 if (!this._isValidLoc()) this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21782 else this.needsUpdate = false; 21783 this._shader.getCgl().gl.uniform1i(this._loc, this._value ? 1 : 0); 21784 21785 this._cgl.profileData.profileUniformCount++; 21786 } 21787 21788 setValueBool(v) 21789 { 21790 if (v != this._value) 21791 { 21792 this.needsUpdate = true; 21793 this._value = v; 21794 } 21795 } 21796 21797 setValueArray4F(v) 21798 { 21799 this.needsUpdate = true; 21800 this._value = v; 21801 } 21802 21803 updateValueArray4F() 21804 { 21805 if (!this._isValidLoc()) this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21806 else this.needsUpdate = false; 21807 21808 if (!this._value) return; 21809 this._shader.getCgl().gl.uniform4fv(this._loc, this._value); 21810 this._cgl.profileData.profileUniformCount++; 21811 } 21812 21813 setValueArray3F(v) 21814 { 21815 this.needsUpdate = true; 21816 this._value = v; 21817 } 21818 21819 updateValueArray3F() 21820 { 21821 if (!this._isValidLoc()) this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21822 else this.needsUpdate = false;
21823 21824 if (!this._value) return; 21825 this._shader.getCgl().gl.uniform3fv(this._loc, this._value); 21826 this._cgl.profileData.profileUniformCount++; 21827 } 21828 21829 setValueArray2F(v) 21830 { 21831 this.needsUpdate = true; 21832 this._value = v; 21833 } 21834 21835 updateValueArray2F() 21836 { 21837 if (!this._isValidLoc()) this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21838 else this.needsUpdate = false; 21839 21840 if (!this._value) return; 21841 this._shader.getCgl().gl.uniform2fv(this._loc, this._value); 21842 this._cgl.profileData.profileUniformCount++; 21843 } 21844 21845 setValueArrayF(v) 21846 { 21847 this.needsUpdate = true; 21848 this._value = v; 21849 } 21850 21851 updateValueArrayF() 21852 { 21853 if (!this._isValidLoc()) this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21854 else this.needsUpdate = false; 21855 21856 if (!this._value) return; 21857 this._shader.getCgl().gl.uniform1fv(this._loc, this._value); 21858 this._cgl.profileData.profileUniformCount++; 21859 } 21860 21861 setValueArrayT(v) 21862 { 21863 this.needsUpdate = true; 21864 this._value = v; 21865 } 21866 21867 updateValue3F() 21868 { 21869 if (!this._value) return; 21870 if (!this._isValidLoc()) 21871 { 21872 this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21873 this._cgl.profileData.profileShaderGetUniform++; 21874 this._cgl.profileData.profileShaderGetUniformName = this._name; 21875 } 21876 21877 this._shader.getCgl().gl.uniform3f(this._loc, this._value[0], this._value[1], this._value[2]); 21878 this.needsUpdate = false; 21879 this._cgl.profileData.profileUniformCount++; 21880 } 21881 21882 setValue3F(v) 21883 { 21884 if (!v) return; 21885 if (!this._oldValue) 21886 { 21887 this._oldValue = [v[0] - 1, 1, 2]; 21888 this.needsUpdate = true; 21889 } 21890 else if (v[0] != this._oldValue[0] || v[1] != this._oldValue[1] || v[2] != this._oldValue[2]) 21891 { 21892 this._oldValue[0] = v[0]; 21893 this._oldValue[1] = v[1]; 21894 this._oldValue[2] = v[2]; 21895 this.needsUpdate = true; 21896 } 21897 21898 this._value = v; 21899 } 21900 21901 updateValue2F() 21902 { 21903 if (!this._value) return; 21904 21905 if (!this._isValidLoc()) 21906 { 21907 this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21908 this._cgl.profileData.profileShaderGetUniform++; 21909 this._cgl.profileData.profileShaderGetUniformName = this._name; 21910 } 21911 21912 this._shader.getCgl().gl.uniform2f(this._loc, this._value[0], this._value[1]); 21913 this.needsUpdate = false; 21914 this._cgl.profileData.profileUniformCount++; 21915 } 21916 21917 setValue2F(v) 21918 { 21919 if (!v) return; 21920 if (!this._oldValue) 21921 { 21922 this._oldValue = [v[0] - 1, 1]; 21923 this.needsUpdate = true; 21924 } 21925 else if (v[0] != this._oldValue[0] || v[1] != this._oldValue[1]) 21926 { 21927 this._oldValue[0] = v[0]; 21928 this._oldValue[1] = v[1]; 21929 this.needsUpdate = true; 21930 } 21931 this._value = v; 21932 } 21933 21934 updateValue4F() 21935 { 21936 if (!this._isValidLoc()) 21937 { 21938 this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21939 this._cgl.profileData.profileShaderGetUniform++; 21940 this._cgl.profileData.profileShaderGetUniformName = this._name; 21941 } 21942 21943 if (!this._value) 21944 { 21945 this._log.warn("no value for uniform", this._name, this); 21946 this._value = [0, 0, 0, 0]; 21947 } 21948 21949 this.needsUpdate = false; 21950 this._shader.getCgl().gl.uniform4f(this._loc, this._value[0], this._value[1], this._value[2], this._value[3]); 21951 this._cgl.profileData.profileUniformCount++; 21952 } 21953 21954 setValue4F(v) 21955 { 21956 if (typeof this.value == "number") this.value = vec4.create(); // this should not be needed, but somehow it crashes with some shadermods 21957 21958 if (!v) return; 21959 if (!this._oldValue) 21960 { 21961 this._oldValue = [v[0] - 1, 1, 2, 3]; 21962 this.needsUpdate = true; 21963 } 21964 else if (v[0] != this._oldValue[0] || v[1] != this._oldValue[1] || v[2] != this._oldValue[2] || v[3] != this._oldValue[3]) 21965 { 21966 this._oldValue[0] = v[0]; 21967 this._oldValue[1] = v[1]; 21968 this._oldValue[2] = v[2]; 21969 this.needsUpdate = true; 21970 } 21971 21972 this._value = v; 21973 } 21974
21975 updateValueM4() 21976 { 21977 if (!this._isValidLoc()) 21978 { 21979 this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21980 this._cgl.profileData.profileShaderGetUniform++; 21981 this._cgl.profileData.profileShaderGetUniformName = this._name; 21982 } 21983 if (!this._value || this._value.length % 16 != 0) return console.log("this.name", this._name, this._value); 21984 21985 this._shader.getCgl().gl.uniformMatrix4fv(this._loc, false, this._value); 21986 this._cgl.profileData.profileUniformCount++; 21987 } 21988 21989 setValueM4(v) 21990 { 21991 this.needsUpdate = true; 21992 this._value = v || mat4.create(); 21993 } 21994 21995 updateValueArrayT() 21996 { 21997 if (!this._isValidLoc()) this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 21998 else this.needsUpdate = false; 21999 22000 if (!this._value) return; 22001 this._shader.getCgl().gl.uniform1iv(this._loc, this._value); 22002 this._cgl.profileData.profileUniformCount++; 22003 } 22004 22005 updateValueT() 22006 { 22007 if (!this._isValidLoc()) 22008 { 22009 this._loc = this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(), this._name); 22010 this._cgl.profileData.profileShaderGetUniform++; 22011 this._cgl.profileData.profileShaderGetUniformName = this._name; 22012 } 22013 22014 this._cgl.profileData.profileUniformCount++; 22015 this._shader.getCgl().gl.uniform1i(this._loc, this._value); 22016 this.needsUpdate = false; 22017 } 22018 22019 setValueT(v) 22020 { 22021 this.needsUpdate = true; 22022 this._value = v; 22023 } 22024} 22025 22026Uniform.glslTypeString = (t) => 22027{ 22028 if (t == "f") return "float"; 22029 if (t == "b") return "bool"; 22030 if (t == "i") return "int"; 22031 if (t == "2i") return "ivec2"; 22032 if (t == "2f") return "vec2"; 22033 if (t == "3f") return "vec3"; 22034 if (t == "4f") return "vec4"; 22035 if (t == "m4") return "mat4"; 22036 22037 if (t == "t") return "sampler2D"; 22038 if (t == "tc") return "samplerCube"; 22039 22040 if (t == "3f[]") return null; // ignore this for now... 22041 if (t == "m4[]") return null; // ignore this for now... 22042 if (t == "f[]") return null; // ignore this for now... 22043 22044 console.warn("[CGL UNIFORM] unknown glsl type string ", t); 22045}; 22046 22047/** 22048 * @function setValue 22049 * @memberof Uniform 22050 * @instance 22051 * @param {Number|Array|Matrix|Texture} value 22052 */ 22053 22054 22055/***/ }), 22056
22057/***/ "./src/corelibs/cgl/cgl_simplerect.js": 22058/*!********************************************!*\ 22059 !*** ./src/corelibs/cgl/cgl_simplerect.js ***! 22060 \********************************************/ 22061/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 22062 22063"use strict"; 22064/* harmony export */ __webpack_require__.d(__webpack_exports__, { 22065/* harmony export */ MESHES: () => (/* binding */ MESHES) 22066/* harmony export */ }); 22067/* harmony import */ var _cg_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../cg/index.js */ "./src/corelibs/cg/cg_geom.js"); 22068/* harmony import */ var _cgl_mesh_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cgl_mesh.js */ "./src/corelibs/cgl/cgl_mesh.js"); 22069 22070 22071 22072const MESHES = {}; 22073 22074MESHES.getSimpleRect = function (cgl, name, size = 1.0) 22075{ 22076 const geom = new _cg_index_js__WEBPACK_IMPORTED_MODULE_0__.Geometry(name); 22077 22078 geom.vertices = [1.0 * size, 1.0 * size, 0.0, -1.0 * size, 1.0 * size, 0.0, 1.0 * size, -1.0 * size, 0.0, -1.0 * size, -1.0 * size, 0.0]; 22079 geom.texCoords = [1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0]; 22080 geom.verticesIndices = [0, 1, 2, 2, 1, 3]; 22081 geom.vertexNormals = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; 22082 22083 return cgl.createMesh(geom); 22084}; 22085 22086MESHES.getSimpleCube = function (cgl, name) 22087{ 22088 const geom = new _cg_index_js__WEBPACK_IMPORTED_MODULE_0__.Geometry(name); 22089 geom.vertices = [-1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1]; 22090 geom.setTexCoords([0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0,]); 22091 geom.verticesIndices = [0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23]; 22092 geom.vertexNormals = new Float32Array([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); 22093 geom.tangents = new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]); 22094 geom.biTangents = new Float32Array([-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1]); 22095 22096 return new _cgl_mesh_js__WEBPACK_IMPORTED_MODULE_1__.Mesh(cgl, geom); 22097}; 22098 22099 22100 22101 22102/***/ }), 22103
22104/***/ "./src/corelibs/cgl/cgl_state.js": 22105/*!***************************************!*\ 22106 !*** ./src/corelibs/cgl/cgl_state.js ***! 22107 \***************************************/ 22108/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 22109 22110"use strict"; 22111/* harmony export */ __webpack_require__.d(__webpack_exports__, { 22112/* harmony export */ CglContext: () => (/* binding */ CglContext) 22113/* harmony export */ }); 22114/* unused harmony export BLENDS */ 22115/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 22116/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! cables */ "./src/core/utils.js"); 22117/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants.js */ "./src/corelibs/cgl/constants.js"); 22118/* harmony import */ var _cgl_shader_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./cgl_shader.js */ "./src/corelibs/cgl/cgl_shader.js"); 22119/* harmony import */ var _cg_cg_context_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../cg/cg_context.js */ "./src/corelibs/cg/cg_context.js"); 22120/* harmony import */ var _cgl_mesh_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./cgl_mesh.js */ "./src/corelibs/cgl/cgl_mesh.js"); 22121/* harmony import */ var _cgl_texture_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./cgl_texture.js */ "./src/corelibs/cgl/cgl_texture.js"); 22122 22123 22124 22125 22126 22127 22128 22129 22130 22131 22132const BLENDS = { 22133 "BLEND_NONE": 0, 22134 "BLEND_NORMAL": 1, 22135 "BLEND_ADD": 2, 22136 "BLEND_SUB": 3, 22137 "BLEND_MUL": 4, 22138}; 22139 22140/** 22141 * cables gl context/state manager 22142 * @class 22143 * @namespace external:CGL 22144 * @hideconstructor 22145 */ 22146class CglContext extends _cg_cg_context_js__WEBPACK_IMPORTED_MODULE_0__.CgContext 22147{ 22148 22149 /** 22150 * @param {Patch} _patch 22151 */ 22152 constructor(_patch) 22153 { 22154 super(_patch); 22155 22156 this.gApi = _cg_cg_context_js__WEBPACK_IMPORTED_MODULE_0__.CgContext.API_WEBGL; 22157 this.aborted = false; 22158 22159 /** @deprecated */ 22160 this.pushMvMatrix = this.pushModelMatrix; // deprecated and wrong... still used?? 22161 /** @deprecated */ 22162 this.popMvMatrix = this.popmMatrix = this.popModelMatrix;// deprecated and wrong... still used?? 22163 22164 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_1__["default"]("cgl_context", { "onError": _patch.config.onError }); 22165 22166 this.glVersion = 0; 22167 this.glUseHalfFloatTex = false; 22168 this.clearCanvasTransparent = true; 22169 this.clearCanvasDepth = true; 22170 this.debugOneFrame = false; 22171 this.checkGlErrors = false; // true is slow // false should be default... 22172 this.maxTextureUnits = 0; 22173 this.maxVaryingVectors = 0; 22174 this.currentProgram = null; 22175 this._hadStackError = false; 22176 this.glSlowRendere = false; 22177 this._isSafariCrap = false; 22178 22179 this.temporaryTexture = null; 22180 22181 /** @type {WebGL2RenderingContext} */ 22182 this.gl = null; 22183 22184 this._cursor = "auto"; 22185 this._currentCursor = ""; 22186 22187 this._viewPortStack = []; 22188 this._glFrameBufferStack = []; 22189 this._frameBufferStack = []; 22190 this._shaderStack = []; 22191 this._stackDepthTest = []; 22192 this.mainloopOp = null; 22193 this._stackBlendMode = []; 22194 this._stackBlendModePremul = []; 22195 this._stackBlend = []; 22196 this._stackDepthFunc = []; 22197 this._stackCullFaceFacing = []; 22198 this._stackCullFace = []; 22199 this._stackDepthWrite = []; 22200 this._stackDepthTest = []; 22201 this._stackStencil = []; 22202 22203 this._simpleShader = new _cgl_shader_js__WEBPACK_IMPORTED_MODULE_2__.Shader(this, "simpleshader"); 22204 this._simpleShader.setModules(["MODULE_VERTEX_POSITION", "MODULE_COLOR", "MODULE_BEGIN_FRAG", "MODULE_VERTEX_MODELVIEW"]); 22205 this._simpleShader.setSource(_cgl_shader_js__WEBPACK_IMPORTED_MODULE_2__.Shader.getDefaultVertexShader(), _cgl_shader_js__WEBPACK_IMPORTED_MODULE_2__.Shader.getDefaultFragmentShader()); 22206 22207 this._currentShader = this._simpleShader; 22208 22209 this._oldCanvasWidth = -1; 22210 this._oldCanvasHeight = -1; 22211 this._enabledExtensions = {}; 22212 22213 this.errorShader = null; 22214 } 22215 22216 // set pixelDensity(p) 22217 // { 22218 // this._pixelDensity = p; 22219 // } 22220 22221 // get pixelDensity() 22222 // { 22223 // return this._pixelDensity; 22224 // } 22225 22226 get viewPort() 22227 { 22228 if (this._viewPortStack.length > 3) 22229 { 22230 const l = this._viewPortStack.length; 22231 22232 return [ 22233 this._viewPortStack[l - 4], 22234 this._viewPortStack[l - 3], 22235 this._viewPortStack[l - 2], 22236 this._viewPortStack[l - 1] 22237 ]; 22238 } 22239 else 22240 { 22241 // workaround pre viewport stack times / or+and initial value... 22242 22243 return this._viewPort; 22244 } 22245 } 22246 22247 get mvMatrix() // deprecate 22248 { 22249 return this.mMatrix; 22250 } 22251 22252 set mvMatrix(m) // deprecate 22253 { 22254 this.mMatrix = m; 22255 } 22256 22257 /** 22258 * @param {HTMLCanvasElement} canv 22259 */ 22260 _setCanvas(canv) 22261 { 22262 if (!canv) this._log.stack("_setCanvas undef"); 22263 22264 if (!this.patch.config.canvas) this.patch.config.canvas = {}; 22265 if (!this.patch.config.canvas.hasOwnProperty("preserveDrawingBuffer")) this.patch.config.canvas.preserveDrawingBuffer = true; 22266 if (!this.patch.config.canvas.hasOwnProperty("premultipliedAlpha")) this.patch.config.canvas.premultipliedAlpha = false;
22267 if (!this.patch.config.canvas.hasOwnProperty("alpha")) this.patch.config.canvas.alpha = false; 22268 22269 this.patch.config.canvas.stencil = true; 22270 22271 if (this.patch.config.hasOwnProperty("clearCanvasColor")) this.clearCanvasTransparent = this.patch.config.clearCanvasColor; 22272 if (this.patch.config.hasOwnProperty("clearCanvasDepth")) this.clearCanvasDepth = this.patch.config.clearCanvasDepth; 22273 22274 // safari stuff.......... ipad is not detectable,just do it for any safari 22275 if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent))// && ((navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)))) 22276 { 22277 this._isSafariCrap = true; 22278 this.glUseHalfFloatTex = true; 22279 } 22280 22281 if (!this.patch.config.canvas.forceWebGl1) this.gl = canv.getContext("webgl2", this.patch.config.canvas); 22282 22283 if (!this.gl || this.gl.isContextLost()) 22284 { 22285 this.aborted = true; 22286 this._log.error("NO_WEBGL", "sorry, could not initialize WebGL. Please check if your Browser supports WebGL or try to restart your browser."); 22287 return; 22288 } 22289 22290 if (this.gl.getParameter(this.gl.VERSION) != "WebGL 1.0") 22291 { 22292 this.glVersion = 2; 22293 } 22294 else 22295 { 22296 this.gl = canv.getContext("webgl", this.patch.config.canvas) || canv.getContext("experimental-webgl", this.patch.config.canvas); 22297 this.glVersion = 1; 22298 22299 // safari 22300 // if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent) && (navigator.userAgent.match(/iPhone/i))) 22301 // { 22302 // this.glUseHalfFloatTex = true; 22303 // } 22304 22305 // ios 22306 // @ts-ignore 22307 if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) 22308 { 22309 if (!this.patch.config.canvas.hasOwnProperty("powerPreference")) this.patch.config.canvas.powerPreference = "high-performance"; 22310 } 22311 22312 this.enableExtension("OES_standard_derivatives"); 22313 // this.enableExtension("GL_OES_standard_derivatives"); 22314 const instancingExt = this.enableExtension("ANGLE_instanced_arrays") || this.gl; 22315 if (instancingExt.vertexAttribDivisorANGLE) 22316 { 22317 this.gl.vertexAttribDivisor = instancingExt.vertexAttribDivisorANGLE.bind(instancingExt); 22318 this.gl.drawElementsInstanced = instancingExt.drawElementsInstancedANGLE.bind(instancingExt); 22319 } 22320 } 22321 22322 const dbgRenderInfo = this.enableExtension("WEBGL_debug_renderer_info"); 22323 if (dbgRenderInfo) 22324 { 22325 this.glRenderer = this.gl.getParameter(dbgRenderInfo.UNMASKED_RENDERER_WEBGL); 22326 if (this.glRenderer === "Google SwiftShader") this.glSlowRenderer = true; 22327 } 22328 22329 this.canvas.addEventListener("webglcontextlost", (event) => 22330 { 22331 if (this.aborted) return this._log.warn("[cgl_state] aborted context lost... can be ignored..."); 22332 this._log.error("canvas lost...", event); 22333 this.emitEvent("webglcontextlost"); 22334 this.aborted = true; 22335 }); 22336 22337 this.maxAnisotropic = 0; 22338 if (this.enableExtension("EXT_texture_filter_anisotropic")) 22339 this.maxAnisotropic = this.gl.getParameter(this.enableExtension("EXT_texture_filter_anisotropic").MAX_TEXTURE_MAX_ANISOTROPY_EXT); 22340 22341 this.maxVaryingVectors = this.gl.getParameter(this.gl.MAX_VARYING_VECTORS); 22342 this.maxTextureUnits = this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS); 22343 this.maxTexSize = this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE); 22344 this.maxUniformsFrag = this.gl.getParameter(this.gl.MAX_FRAGMENT_UNIFORM_VECTORS); 22345 this.maxUniformsVert = this.gl.getParameter(this.gl.MAX_VERTEX_UNIFORM_VECTORS); 22346 this.maxSamples = 0; 22347 if (this.gl.MAX_SAMPLES) this.maxSamples = this.gl.getParameter(this.gl.MAX_SAMPLES); 22348 22349 if (this.glVersion == 1) 22350 { 22351 this.enableExtension("OES_standard_derivatives"); 22352 const instancingExt = this.enableExtension("ANGLE_instanced_arrays") || this.gl; 22353 22354 if (instancingExt.vertexAttribDivisorANGLE) 22355 { 22356 this.gl.vertexAttribDivisor = instancingExt.vertexAttribDivisorANGLE.bind(instancingExt); 22357 this.gl.drawElementsInstanced = instancingExt.drawElementsInstancedANGLE.bind(instancingExt); 22358 } 22359 } 22360 22361 this.DEPTH_FUNCS = [ 22362 this.gl.NEVER, 22363 this.gl.ALWAYS, 22364 this.gl.LESS, 22365 this.gl.LEQUAL, 22366 this.gl.GREATER, 22367 this.gl.GEQUAL, 22368 this.gl.EQUAL, 22369 this.gl.NOTEQUAL 22370 ]; 22371 this.CULL_MODES = [ 22372 null, 22373 this.gl.BACK, 22374 this.gl.FRONT, 22375 this.gl.FRONT_AND_BACK 22376 ]; 22377 } 22378 22379 getInfo() 22380 { 22381 return { 22382 "glVersion": this.glVersion, 22383 "glRenderer": this.glRenderer, 22384 "glUseHalfFloatTex": this.glUseHalfFloatTex, 22385 "maxVaryingVectors": this.maxVaryingVectors, 22386 "maxTextureUnits": this.maxTextureUnits, 22387 "maxTexSize": this.maxTexSize, 22388 "maxUniformsFrag": this.maxUniformsFrag, 22389 "maxUniformsVert": this.maxUniformsVert, 22390 "maxSamples": this.maxSamples 22391 }; 22392 } 22393 22394 /** 22395 * @function popViewPort 22396 * @memberof Context 22397 * @instance
22398 * @description pop viewPort stack 22399 */ 22400 popViewPort() 22401 { 22402 this._viewPortStack.pop(); 22403 this._viewPortStack.pop(); 22404 this._viewPortStack.pop(); 22405 this._viewPortStack.pop(); 22406 22407 if (this._viewPortStack.length == 0) 22408 this.setViewPort(0, 0, this.canvasWidth, this.canvasHeight); 22409 else 22410 this.setViewPort(this._viewPortStack[this._viewPort.length - 4], this._viewPortStack[this._viewPort.length - 3], this._viewPortStack[this._viewPort.length - 2], this._viewPortStack[this._viewPort.length - 1]); 22411 } 22412 22413 /** 22414 * @function pushViewPort 22415 * @memberof Context 22416 * @instance 22417 * @description push a new viewport onto stack 22418 * @param {Number} x 22419 * @param {Number} y 22420 * @param {Number} w 22421 * @param {Number} h 22422 */ 22423 22424 pushViewPort(x, y, w, h) 22425 { 22426 this._viewPortStack.push(x, y, w, h); 22427 this.setViewPort(x, y, w, h); 22428 } 22429 22430 // old 22431 getViewPort() 22432 { 22433 return this._viewPort; 22434 } 22435 22436 // old 22437 resetViewPort() 22438 { 22439 this.gl.viewport(this._viewPort[0], this._viewPort[1], this._viewPort[2], this._viewPort[3]); 22440 } 22441 22442 // old 22443 /** 22444 * @param {number} x 22445 * @param {number} y 22446 * @param {number} w 22447 * @param {number} h 22448 */ 22449 setViewPort(x, y, w, h) 22450 { 22451 this._viewPort[0] = Math.round(x); 22452 this._viewPort[1] = Math.round(y); 22453 this._viewPort[2] = Math.round(w); 22454 this._viewPort[3] = Math.round(h); 22455 this.gl.viewport(this._viewPort[0], this._viewPort[1], this._viewPort[2], this._viewPort[3]); 22456 } 22457 22458 /** 22459 * @param {function} cb 22460 * @param {boolean} doScreenshotClearAlpha 22461 * @param {string} mimeType 22462 * @param {number} quality 22463 */ 22464 screenShot(cb, doScreenshotClearAlpha, mimeType, quality) 22465 { 22466 if (doScreenshotClearAlpha) 22467 { 22468 this.gl.clearColor(1, 1, 1, 1); 22469 this.gl.colorMask(false, false, false, true); 22470 this.gl.clear(this.gl.COLOR_BUFFER_BIT); 22471 this.gl.colorMask(true, true, true, true); 22472 } 22473 22474 if (this.canvas && this.canvas.toBlob) 22475 { 22476 this.canvas.toBlob( 22477 (blob) => 22478 { 22479 if (cb) cb(blob); 22480 else this._log.log("no screenshot callback..."); 22481 }, mimeType, quality); 22482 } 22483 } 22484 22485 endFrame() 22486 { 22487 if (this.patch.isEditorMode()) CABLES.GL_MARKER.drawMarkerLayer(this); 22488 22489 this.setPreviousShader(); 22490 22491 if (this._vMatrixStack.length() > 0) this.logStackError("view matrix stack length !=0 at end of rendering..."); 22492 if (this._mMatrixStack.length() > 0) this.logStackError("mvmatrix stack length !=0 at end of rendering..."); 22493 if (this._pMatrixStack.length() > 0) this.logStackError("pmatrix stack length !=0 at end of rendering..."); 22494 if (this._glFrameBufferStack.length > 0) this.logStackError("glFrameBuffer stack length !=0 at end of rendering..."); 22495 if (this._stackDepthTest.length > 0) this.logStackError("depthtest stack length !=0 at end of rendering..."); 22496 if (this._stackDepthWrite.length > 0) this.logStackError("depthwrite stack length !=0 at end of rendering..."); 22497 if (this._stackDepthFunc.length > 0) this.logStackError("depthfunc stack length !=0 at end of rendering..."); 22498 if (this._stackBlend.length > 0) this.logStackError("blend stack length !=0 at end of rendering..."); 22499 if (this._stackBlendMode.length > 0) this.logStackError("blendMode stack length !=0 at end of rendering..."); 22500 if (this._shaderStack.length > 0) this.logStackError("this._shaderStack length !=0 at end of rendering..."); 22501 if (this._stackCullFace.length > 0) this.logStackError("this._stackCullFace length !=0 at end of rendering..."); 22502 if (this._stackCullFaceFacing.length > 0) this.logStackError("this._stackCullFaceFacing length !=0 at end of rendering..."); 22503 if (this._viewPortStack.length > 0) this.logStackError("viewport stack length !=0 at end of rendering..."); 22504 22505 this._frameStarted = false;
22506 22507 if (this._oldCanvasWidth != this.canvasWidth || this._oldCanvasHeight != this.canvasHeight) 22508 { 22509 this._oldCanvasWidth = this.canvasWidth; 22510 this._oldCanvasHeight = this.canvasHeight; 22511 this.emitEvent(_cg_cg_context_js__WEBPACK_IMPORTED_MODULE_0__.CgContext.EVENT_RESIZE); 22512 } 22513 22514 if (this._cursor != this._currentCursor) 22515 { 22516 this._currentCursor = this.canvas.style.cursor = this._cursor; 22517 } 22518 22519 this.emitEvent("endframe"); 22520 22521 this.fpsCounter.endFrame(); 22522 } 22523 22524 logStackError(str) 22525 { 22526 if (!this._hadStackError) 22527 { 22528 this._hadStackError = true; 22529 this._log.warn("[" + this.canvas.id + "]: ", str); 22530 } 22531 } 22532 22533 // shader stack 22534 getShader() 22535 { 22536 if (this._currentShader) if (!this.tempData || ((this.tempData.renderOffscreen === true) == this._currentShader.offScreenPass) === true) return this._currentShader; 22537 22538 for (let i = this._shaderStack.length - 1; i >= 0; i--) if (this._shaderStack[i]) if (this.tempData.renderOffscreen == this._shaderStack[i].offScreenPass) return this._shaderStack[i]; 22539 } 22540 22541 getDefaultShader() 22542 { 22543 return this._simpleShader; 22544 } 22545 22546 /** 22547 * @deprecated 22548 * @param {Shader} s 22549 */ 22550 setShader(s) 22551 { 22552 this.pushShader(s); 22553 } 22554 22555 /** 22556 * push a shader to the shader stack 22557 * @function pushShader 22558 * @memberof Context 22559 * @instance 22560 * @param {Shader} shader 22561 * @function 22562 */ 22563 pushShader(shader) 22564 { 22565 if (this.tempData.forceShaderMods) 22566 { 22567 for (let i = 0; i < this.tempData.forceShaderMods.length; i++) 22568 { 22569 // if (!currentShader.forcedMod && currentShader != this.tempData.forceShaderMods[i]) 22570 // { 22571 // currentShader.forcedMod = this.tempData.forceShaderMods[i]; 22572 shader = this.tempData.forceShaderMods[i].bind(shader, false); 22573 // } 22574 // return currentShader; 22575 // if (this.tempData.forceShaderMods[i].currentShader() && shader != this.tempData.forceShaderMods[i].currentShader().shader) 22576 } 22577 } 22578 22579 this._shaderStack.push(shader); 22580 this._currentShader = shader; 22581 } 22582 22583 popShader() 22584 { 22585 this.setPreviousShader(); 22586 } 22587 22588 /** 22589 * pop current used shader from shader stack 22590 * @function popShader 22591 * @memberof Context 22592 * @instance 22593 * @function 22594 */ 22595 setPreviousShader() 22596 { 22597 if (this.tempData.forceShaderMods) 22598 { 22599 for (let i = 0; i < this.tempData.forceShaderMods.length; i++) 22600 { 22601 // const a = 22602 this.tempData.forceShaderMods[i].unbind(false); 22603 // if (a) return; 22604 // this.popShader(); 22605 } 22606 } 22607 22608 if (this._shaderStack.length === 0) throw new Error("Invalid shader stack pop!"); 22609 this._shaderStack.pop(); 22610 this._currentShader = this._shaderStack[this._shaderStack.length - 1]; 22611 } 22612 22613 /** 22614 * push a framebuffer to the framebuffer stack 22615 * @function pushGlFrameBuffer 22616 * @memberof Context 22617 * @instance 22618 * @param {Object} fb framebuffer 22619 * @function 22620 */ 22621 pushGlFrameBuffer(fb) 22622 { 22623 this._glFrameBufferStack.push(fb); 22624 } 22625 22626 /** 22627 * pop framebuffer stack 22628 * @function popGlFrameBuffer 22629 * @memberof Context 22630 * @instance 22631 * @returns {Object} current framebuffer or null 22632 */ 22633 popGlFrameBuffer() 22634 { 22635 if (this._glFrameBufferStack.length == 0) return null; 22636 this._glFrameBufferStack.pop(); 22637 return this._glFrameBufferStack[this._glFrameBufferStack.length - 1]; 22638 } 22639 22640 /** 22641 * get current framebuffer 22642 * @function getCurrentFrameBuffer 22643 * @memberof Context 22644 * @instance 22645 * @returns {Object} current framebuffer or null 22646 */ 22647 getCurrentGlFrameBuffer() 22648 { 22649 if (this._glFrameBufferStack.length === 0) return null; 22650 return this._glFrameBufferStack[this._glFrameBufferStack.length - 1]; 22651 } 22652 22653 /** 22654 * push a framebuffer to the framebuffer stack 22655 * @function pushGlFrameBuffer 22656 * @memberof Context 22657 * @instance 22658 * @param {Framebuffer2} fb framebuffer 22659 */ 22660 pushFrameBuffer(fb) 22661 { 22662 this._frameBufferStack.push(fb); 22663 } 22664 22665 /** 22666 * pop framebuffer stack 22667 * @function popFrameBuffer 22668 * @memberof Context 22669 * @instance 22670 * @returns {Framebuffer2} current framebuffer or null 22671 */ 22672 popFrameBuffer() 22673 { 22674 if (this._frameBufferStack.length == 0) return null; 22675 this._frameBufferStack.pop(); 22676 return this._frameBufferStack[this._frameBufferStack.length - 1]; 22677 } 22678 22679 /** 22680 * get current framebuffer 22681 * @function getCurrentFrameBuffer 22682 * @memberof Context 22683 * @instance 22684 * @returns {Framebuffer2} current framebuffer or null 22685 */ 22686 getCurrentFrameBuffer() 22687 { 22688 if (this._frameBufferStack.length === 0) return null; 22689 return this._frameBufferStack[this._frameBufferStack.length - 1]; 22690 } 22691 22692 renderStart(cgl, identTranslate, identTranslateView) 22693 { 22694 this.fpsCounter.startFrame(); 22695 this.pushDepthTest(true); 22696 this.pushDepthWrite(true); 22697 this.pushDepthFunc(cgl.gl.LEQUAL); 22698 this.pushCullFaceFacing(cgl.gl.BACK); 22699 this.pushCullFace(false); 22700 22701 // if (this.clearCanvasTransparent) 22702 // { 22703 // cgl.gl.clearColor(0, 0, 0, 0); 22704 // cgl.gl.clear(cgl.gl.COLOR_BUFFER_BIT); 22705 // } 22706 // if (this.clearCanvasDepth) cgl.gl.clear(cgl.gl.DEPTH_BUFFER_BIT); 22707 22708 cgl.setViewPort(0, 0, cgl.canvasWidth, cgl.canvasHeight); 22709 22710 this._startMatrixStacks(identTranslate, identTranslateView); 22711 22712 cgl.pushBlendMode(_constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.BLEND_MODES.BLEND_NORMAL, false); 22713 22714 for (let i = 0; i < this._textureslots.length; i++) this._textureslots[i] = null; 22715 22716 this.pushShader(this._simpleShader); 22717 22718 this._frameStarted = true; 22719 22720 this._execOneTimeCallbacks(); 22721 22722 for (let i = 0; i < this._textureslots.length; i++) 22723 { 22724 this.gl.activeTexture(this.gl.TEXTURE0 + i); 22725 this.gl.bindTexture(this.gl.TEXTURE_2D, null); 22726 this._textureslots[i] = null; 22727 } 22728 22729 this.emitEvent("beginFrame"); 22730 } 22731 22732 /** 22733 * @param {CglContext} cgl 22734 */ 22735 renderEnd(cgl) 22736 { 22737 this._endMatrixStacks(); 22738 22739 this.popDepthTest(); 22740 this.popDepthWrite(); 22741 this.popDepthFunc(); 22742 this.popCullFaceFacing(); 22743 this.popCullFace(); 22744 this.popBlend(); 22745 this.popBlendMode(); 22746 22747 cgl.endFrame(); 22748 22749 this.emitEvent("endFrame"); 22750 } 22751 22752 /** 22753 * @param {number} slot 22754 */ 22755 getTexture(slot) 22756 { 22757 return this._textureslots[slot]; 22758 } 22759 22760 hasFrameStarted() 22761 { 22762 return this._frameStarted; 22763 } 22764 22765 /** 22766 * log warning to console if the rendering of one frame has not been started / handy to check for async problems 22767 * @function checkFrameStarted 22768 * @memberof Context 22769 * @param {string} string 22770 * @instance 22771 */ 22772 checkFrameStarted(string) 22773 { 22774 if (!this._frameStarted) 22775 { 22776 this._log.warn("frame not started " + string); 22777 22778 Error.stackTraceLimit = 25; 22779 cables__WEBPACK_IMPORTED_MODULE_4__.logStack(); 22780 this.patch.printTriggerStack(); 22781 } 22782 } 22783 22784 /** 22785 * @param {number} slot 22786 * @param {WebGLTexture} t 22787 * @param {undefined} [type] 22788 */ 22789 setTexture(slot, t, type) 22790 { 22791 this.checkFrameStarted("cgl setTexture"); 22792 22793 if (t === null) t = _cgl_texture_js__WEBPACK_IMPORTED_MODULE_5__.Texture.getEmptyTexture(this).tex; 22794 22795 if (this._textureslots[slot] != t) 22796 { 22797 this.gl.activeTexture(this.gl.TEXTURE0 + slot); 22798 this.gl.bindTexture(type || this.gl.TEXTURE_2D, t); 22799 this._textureslots[slot] = t; 22800 } 22801 22802 return true; 22803 } 22804 22805 fullScreen() 22806 { 22807 if (this.canvas.requestFullscreen) this.canvas.requestFullscreen(); 22808 else if (this.canvas.mozRequestFullScreen) this.canvas.mozRequestFullScreen(); 22809 else if (this.canvas.webkitRequestFullscreen) this.canvas.webkitRequestFullscreen(); 22810 else if (this.canvas.msRequestFullscreen) this.canvas.msRequestFullscreen(); 22811 } 22812 22813 /** 22814 * @param {string} [str] 22815 */ 22816 printError(str) 22817 { 22818 if (!this.checkGlErrors) return; 22819 let found = false;
22820 let error = this.gl.getError(); 22821 22822 if (error != this.gl.NO_ERROR) 22823 { 22824 let errStr = ""; 22825 if (error == this.gl.OUT_OF_MEMORY) errStr = "OUT_OF_MEMORY"; 22826 if (error == this.gl.INVALID_ENUM) errStr = "INVALID_ENUM"; 22827 if (error == this.gl.INVALID_OPERATION) errStr = "INVALID_OPERATION"; 22828 if (error == this.gl.INVALID_FRAMEBUFFER_OPERATION) errStr = "INVALID_FRAMEBUFFER_OPERATION"; 22829 if (error == this.gl.INVALID_VALUE) errStr = "INVALID_VALUE"; 22830 if (error == this.gl.CONTEXT_LOST_WEBGL) 22831 { 22832 this.aborted = true; 22833 errStr = "CONTEXT_LOST_WEBGL"; 22834 } 22835 if (error == this.gl.NO_ERROR) errStr = "NO_ERROR"; 22836 22837 found = true; 22838 22839 this._log.warn("gl error [" + this.canvas.id + "]: ", str, error, errStr); 22840 22841 if (this.canvas.id.includes("glGuiCanvas")) 22842 if (!this._loggedGlError) 22843 { 22844 this.patch.printTriggerStack(); 22845 this._log.stack("glerror"); 22846 this._loggedGlError = true; 22847 } 22848 } 22849 error = this.gl.getError(); 22850 22851 return found; 22852 } 22853 22854 _dispose() 22855 { 22856 this._simpleShader.dispose(); 22857 this.gl = null; 22858 } 22859 22860 // state depthtest 22861 22862 /** 22863 * push depth testing enabled state 22864 * @function pushDepthTest 22865 * @param {Boolean} enabled 22866 * @memberof Context 22867 * @instance 22868 */ 22869 22870 pushDepthTest(enabled) 22871 { 22872 this._stackDepthTest.push(enabled); 22873 if (!enabled) this.gl.disable(this.gl.DEPTH_TEST); 22874 else this.gl.enable(this.gl.DEPTH_TEST); 22875 } 22876 22877 /** 22878 * current state of depth testing 22879 * @function stateCullFace 22880 * @returns {Boolean} enabled 22881 * @memberof Context 22882 * @instance 22883 */ 22884 stateDepthTest() 22885 { 22886 return this._stackDepthTest[this._stackDepthTest.length - 1]; 22887 } 22888 22889 /** 22890 * pop depth testing state 22891 * @function popCullFace 22892 * @memberof Context 22893 * @instance 22894 */ 22895 popDepthTest() 22896 { 22897 this._stackDepthTest.pop(); 22898 22899 if (!this._stackDepthTest[this._stackDepthTest.length - 1]) this.gl.disable(this.gl.DEPTH_TEST); 22900 else this.gl.enable(this.gl.DEPTH_TEST); 22901 } 22902 22903 // -------------------------------------- 22904 // state depthwrite 22905 22906 /** 22907 * push depth write enabled state 22908 * @function pushDepthTest 22909 * @param {Boolean} enabled 22910 * @memberof Context 22911 * @instance 22912 */ 22913 pushDepthWrite(enabled) 22914 { 22915 enabled = enabled || false; 22916 this._stackDepthWrite.push(enabled); 22917 this.gl.depthMask(enabled); 22918 } 22919 22920 /** 22921 * current state of depth writing 22922 * @function stateDepthWrite 22923 * @returns {Boolean} enabled 22924 * @memberof Context 22925 * @instance 22926 */ 22927 stateDepthWrite() 22928 { 22929 return this._stackDepthWrite[this._stackDepthWrite.length - 1]; 22930 } 22931 22932 /** 22933 * pop depth writing state 22934 * @function popDepthWrite 22935 * @memberof Context 22936 * @instance 22937 */ 22938 popDepthWrite() 22939 { 22940 this._stackDepthWrite.pop(); 22941 this.gl.depthMask(this._stackDepthWrite[this._stackDepthWrite.length - 1] || false); 22942 } 22943 22944 // -------------------------------------- 22945 // state CullFace 22946 22947 /** 22948 * push face culling face enabled state 22949 * @function pushCullFace 22950 * @param {Boolean} enabled 22951 * @memberof Context 22952 * @instance 22953 */ 22954 pushCullFace(enabled) 22955 { 22956 this._stackCullFace.push(enabled); 22957 22958 if (enabled) this.gl.enable(this.gl.CULL_FACE); 22959 else this.gl.disable(this.gl.CULL_FACE); 22960 } 22961 22962 /** 22963 * current state of face culling 22964 * @function stateCullFace 22965 * @returns {Boolean} enabled 22966 * @memberof Context 22967 * @instance 22968 */ 22969 stateCullFace() 22970 { 22971 return this._stackCullFace[this._stackCullFace.length - 1]; 22972 } 22973 22974 /** 22975 * pop face culling enabled state 22976 * @function popCullFace 22977 * @memberof Context 22978 * @instance 22979 */ 22980 popCullFace() 22981 { 22982 this._stackCullFace.pop(); 22983 22984 if (this._stackCullFace[this._stackCullFace.length - 1]) this.gl.enable(this.gl.CULL_FACE); 22985 else this.gl.disable(this.gl.CULL_FACE); 22986 } 22987 22988 // -------------------------------------- 22989 // state CullFace Facing 22990 22991 /** 22992 * push face culling face side 22993 * @function pushCullFaceFacing 22994 * @param {Number} face - cgl.gl.FRONT_AND_BACK, cgl.gl.BACK or cgl.gl.FRONT 22995 * @memberof Context 22996 * @instance 22997 */ 22998 22999 pushCullFaceFacing(face) 23000 { 23001 this._stackCullFaceFacing.push(face); 23002 this.gl.cullFace(this._stackCullFaceFacing[this._stackCullFaceFacing.length - 1]); 23003 } 23004 23005 /** 23006 * current state of face culling side 23007 * @function stateCullFaceFacing 23008 * @returns {Boolean} enabled 23009 * @memberof Context 23010 * @instance 23011 */ 23012 stateCullFaceFacing() 23013 { 23014 return this._stackCullFaceFacing[this._stackCullFaceFacing.length - 1]; 23015 } 23016 23017 /** 23018 * pop face culling face side 23019 * @function popCullFaceFacing 23020 * @memberof Context 23021 * @instance 23022 */ 23023 popCullFaceFacing() 23024 { 23025 this._stackCullFaceFacing.pop(); 23026 if (this._stackCullFaceFacing.length > 0) this.gl.cullFace(this._stackCullFaceFacing[this._stackCullFaceFacing.length - 1]); 23027 } 23028 23029 // -------------------------------------- 23030 // state depthfunc 23031 23032 /** 23033 * enable / disable depth testing 23034 * like `gl.depthFunc(boolean);` 23035 * @function pushDepthFunc 23036 * @memberof Context 23037 * @instance 23038 * @param {Boolean} f depthtesting 23039 */ 23040 pushDepthFunc(f) 23041 { 23042 this._stackDepthFunc.push(f); 23043 this.gl.depthFunc(f); 23044 } 23045 23046 /** 23047 * current state of blend 23048 * @function stateDepthFunc 23049 * @memberof Context 23050 * @instance 23051 * @returns {Boolean} depth testing enabled/disabled 23052 */ 23053 stateDepthFunc() 23054 { 23055 if (this._stackDepthFunc.length > 0) return this._stackDepthFunc[this._stackDepthFunc.length - 1]; 23056 return false;
23057 } 23058 23059 /** 23060 * pop depth testing and set the previous state 23061 * @function popDepthFunc 23062 * @memberof Context 23063 * @instance 23064 */ 23065 popDepthFunc() 23066 { 23067 this._stackDepthFunc.pop(); 23068 if (this._stackDepthFunc.length > 0) this.gl.depthFunc(this._stackDepthFunc[this._stackDepthFunc.length - 1]); 23069 } 23070 23071 // -------------------------------------- 23072 // state blending 23073 23074 /** 23075 * enable / disable blend 23076 * like gl.enable(gl.BLEND); / gl.disable(gl.BLEND); 23077 * @function pushBlend 23078 * @memberof Context 23079 * @instance 23080 * @param {boolean} b blending 23081 */ 23082 pushBlend(b) 23083 { 23084 this._stackBlend.push(b); 23085 if (!b) this.gl.disable(this.gl.BLEND); 23086 else this.gl.enable(this.gl.BLEND); 23087 } 23088 23089 /** 23090 * pop blend state and set the previous state 23091 * @function popBlend 23092 * @memberof Context 23093 * @instance 23094 */ 23095 popBlend() 23096 { 23097 this._stackBlend.pop(); 23098 23099 if (!this._stackBlend[this._stackBlend.length - 1]) this.gl.disable(this.gl.BLEND); 23100 else this.gl.enable(this.gl.BLEND); 23101 } 23102 23103 /** 23104 * current state of blend 23105 * @function stateBlend 23106 * @returns {boolean} blending enabled/disabled 23107 * @memberof Context 23108 * @instance 23109 */ 23110 stateBlend() 23111 { 23112 return this._stackBlend[this._stackBlend.length - 1]; 23113 } 23114 23115 /** 23116 * push and switch to predefined blendmode (CONSTANTS.BLEND_MODES.BLEND_NONE,CONSTANTS.BLEND_MODES.BLEND_NORMAL,CONSTANTS.BLEND_MODES.BLEND_ADD,CONSTANTS.BLEND_MODES.BLEND_SUB,CONSTANTS.BLEND_MODES.BLEND_MUL) 23117 * @function pushBlendMode 23118 * @memberof Context 23119 * @instance 23120 * @param {Number} blendMode 23121 * @param {Boolean} premul premultiplied mode 23122 */ 23123 pushBlendMode(blendMode, premul) 23124 { 23125 this._stackBlendMode.push(blendMode); 23126 this._stackBlendModePremul.push(premul); 23127 23128 const n = this._stackBlendMode.length - 1; 23129 23130 this.pushBlend(this._stackBlendMode[n] !== _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.BLEND_MODES.BLEND_NONE); 23131 this._setBlendMode(this._stackBlendMode[n], this._stackBlendModePremul[n]); 23132 } 23133 23134 /** 23135 * pop predefined blendmode / switch back to previous blendmode 23136 * @function popBlendMode 23137 * @memberof Context 23138 * @instance 23139 */ 23140 popBlendMode() 23141 { 23142 this._stackBlendMode.pop(); 23143 this._stackBlendModePremul.pop(); 23144 23145 const n = this._stackBlendMode.length - 1; 23146 23147 this.popBlend(); 23148 23149 if (n >= 0) this._setBlendMode(this._stackBlendMode[n], this._stackBlendModePremul[n]); 23150 } 23151 23152 // -------------------------------------- 23153 // state stencil 23154 23155 /** 23156 * enable / disable stencil testing 23157 23158 * @function pushStencil 23159 * @memberof Context 23160 * @instance 23161 * @param {Boolean} b enable 23162 */ 23163 pushStencil(b) 23164 { 23165 this._stackStencil.push(b); 23166 if (!b) this.gl.disable(this.gl.STENCIL_TEST); 23167 else this.gl.enable(this.gl.STENCIL_TEST); 23168 } 23169 23170 /** 23171 * pop stencil test state and set the previous state 23172 * @function popStencil 23173 * @memberof Context 23174 * @instance 23175 */ 23176 popStencil() 23177 { 23178 this._stackStencil.pop(); 23179 23180 if (!this._stackStencil[this._stackStencil.length - 1]) this.gl.disable(this.gl.STENCIL_TEST); 23181 else this.gl.enable(this.gl.STENCIL_TEST); 23182 } 23183 23184 // -------------------------------------- 23185 23186 glGetAttribLocation(prog, name) 23187 { 23188 const l = this.gl.getAttribLocation(prog, name); 23189 // if (l == -1) 23190 // { 23191 // this._log.warn("get attr loc -1 ", name); 23192 // } 23193 return l; 23194 } 23195 23196 /** 23197 * should an op now draw helpermeshes 23198 * @param {Op} op 23199 */ 23200 shouldDrawHelpers(op) 23201 { 23202 if (this.tempData.shadowPass) return false; 23203 if (!op.patch.isEditorMode()) return false; 23204 return gui.shouldDrawOverlay; 23205 } 23206 23207 _setBlendMode(blendMode, premul) 23208 { 23209 const gl = this.gl; 23210 23211 if (blendMode == _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.BLEND_MODES.BLEND_NONE) 23212 { 23213 // this.gl.disable(this.gl.BLEND); 23214 } 23215 else if (blendMode == _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.BLEND_MODES.BLEND_ADD) 23216 { 23217 if (premul) 23218 { 23219 gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); 23220 gl.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE); 23221 } 23222 else 23223 { 23224 gl.blendEquation(gl.FUNC_ADD); 23225 gl.blendFunc(gl.SRC_ALPHA, gl.ONE); 23226 } 23227 } 23228 else if (blendMode == _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.BLEND_MODES.BLEND_SUB) 23229 { 23230 if (premul) 23231 { 23232 gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); 23233 gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA); 23234 } 23235 else 23236 { 23237 gl.blendEquation(gl.FUNC_ADD); 23238 gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR); 23239 } 23240 } 23241 else if (blendMode == _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.BLEND_MODES.BLEND_MUL) 23242 { 23243 if (premul) 23244 { 23245 gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); 23246 gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA); 23247 } 23248 else 23249 { 23250 gl.blendEquation(gl.FUNC_ADD); 23251 gl.blendFunc(gl.ZERO, gl.SRC_COLOR); 23252 } 23253 } 23254 else if (blendMode == _constants_js__WEBPACK_IMPORTED_MODULE_3__.CONSTANTS.BLEND_MODES.BLEND_NORMAL) 23255 { 23256 if (premul) 23257 { 23258 gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); 23259 gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); 23260 } 23261 else 23262 { 23263 gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); 23264 gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); 23265 } 23266 } 23267 else 23268 { 23269 this._log.log("setblendmode: unknown blendmode"); 23270 } 23271 } 23272 23273 /** 23274 * @param {Geometry} geom 23275 * @param {CglMeshOptions} options 23276 */ 23277 createMesh(geom, options) 23278 { 23279 if (cables__WEBPACK_IMPORTED_MODULE_4__.isNumeric(options))options = { "glPrimitive": options }; // old constructor fallback... 23280 return new _cgl_mesh_js__WEBPACK_IMPORTED_MODULE_6__.Mesh(this, geom, options); 23281 } 23282 23283 /** 23284 * set cursor 23285 * @function setCursor 23286 * @memberof Context 23287 * @instance 23288 * @param {String} str css cursor string 23289 */ 23290 setCursor(str) 23291 { 23292 this._cursor = str; 23293 } 23294 23295 /** 23296 * enable a webgl extension 23297 * @function enableExtension 23298 * @memberof Context 23299 * @instance 23300 * @param {String} name extension name 23301 * @returns {Object} extension object or null 23302 */ 23303 enableExtension(name) 23304 { 23305 if (!this.gl) return null; 23306 23307 if (this._enabledExtensions.hasOwnProperty(name)) 23308 return this._enabledExtensions[name]; 23309 23310 const o = this.gl.getExtension(name); 23311 this._enabledExtensions[name] = o; 23312 23313 if (!o) this._log.warn("[cgl_state] extension not available " + name); 23314 23315 return o; 23316 } 23317 23318 getErrorShader() 23319 { 23320 if (this.errorShader) return this.errorShader; 23321 23322 this.errorShader = new _cgl_shader_js__WEBPACK_IMPORTED_MODULE_2__.Shader(this, "errormaterial"); 23323 this.errorShader.setSource(_cgl_shader_js__WEBPACK_IMPORTED_MODULE_2__.Shader.getDefaultVertexShader(), _cgl_shader_js__WEBPACK_IMPORTED_MODULE_2__.Shader.getErrorFragmentShader()); 23324 return this.errorShader; 23325 } 23326 23327} 23328 23329 23330/***/ }), 23331
23332/***/ "./src/corelibs/cgl/cgl_texture.js": 23333/*!*****************************************!*\ 23334 !*** ./src/corelibs/cgl/cgl_texture.js ***! 23335 \*****************************************/ 23336/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 23337 23338"use strict"; 23339/* harmony export */ __webpack_require__.d(__webpack_exports__, { 23340/* harmony export */ Texture: () => (/* binding */ Texture) 23341/* harmony export */ }); 23342/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 23343/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! cables */ "./src/core/utils.js"); 23344/* harmony import */ var _cg_cg_texture_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../cg/cg_texture.js */ "./src/corelibs/cg/cg_texture.js"); 23345 23346 23347 23348 23349 23350const DEFAULT_TEXTURE_SIZE = 8; 23351 23352const log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"]("cgl_texture"); 23353 23354/** 23355 * A Texture 23356 * @namespace external:CGL 23357 * @class 23358 * @param {CglContext} __cgl cgl 23359 * @param {Object} options 23360 * @hideconstructor 23361 * @example 23362 * // generate a 256x256 pixel texture of random colors 23363 * const size=256; 23364 * const data = new Uint8Array(size*size*4); 23365 * 23366 * for(var x=0;x<size*size*4;x++) data[ x*4+3]=255; 23367 * 23368 * const tex=new CGL.Texture(cgl); 23369 * tex.initFromData(data,size,size,CGL.Texture.FILTER_NEAREST,CGL.Texture.WRAP_REPEAT); 23370 */ 23371class Texture extends _cg_cg_texture_js__WEBPACK_IMPORTED_MODULE_1__.CgTexture 23372{ 23373 23374 /** 23375 * @param {CglContext} __cgl 23376 */ 23377 constructor(__cgl, options = {}) 23378 { 23379 super(options); 23380 if (!__cgl) throw new Error("no cgl"); 23381 23382 this._cgl = __cgl; 23383 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"]("tex"); 23384 this.tex = this._cgl.gl.createTexture(); 23385 this.loading = false; 23386 this.flip = true; 23387 this.flipped = false; 23388 this.shadowMap = false; 23389 this.deleted = false; 23390 this.image = null; 23391 this.anisotropic = 0; 23392 this.filter = Texture.FILTER_NEAREST; 23393 this.wrap = Texture.WRAP_CLAMP_TO_EDGE; 23394 this.texTarget = this._cgl.gl.TEXTURE_2D; 23395 if (options && options.type) this.texTarget = options.type; 23396 this.textureType = Texture.TYPE_DEFAULT; 23397 this.unpackAlpha = true; 23398 this._fromData = true; 23399 23400 this._glDataType = -1; 23401 this._glInternalFormat = -1; 23402 this._glDataFormat = -1; 23403 23404 if (options) 23405 { 23406 if (options.isDepthTexture) this.textureType = Texture.TYPE_DEPTH; 23407 if (options.isFloatingPointTexture === true) this.textureType = Texture.TYPE_FLOAT; 23408 23409 if ("textureType" in options) this.textureType = options.textureType; 23410 if ("filter" in options) this.filter = options.filter; 23411 if ("wrap" in options) this.wrap = options.wrap; 23412 if ("unpackAlpha" in options) this.unpackAlpha = options.unpackAlpha; 23413 if ("flip" in options) this.flip = options.flip; 23414 if ("shadowMap" in options) this.shadowMap = options.shadowMap; 23415 if ("anisotropic" in options) this.anisotropic = options.anisotropic; 23416 } 23417 else 23418 { 23419 options = {}; 23420 } 23421 23422 if (!options.pixelFormat && options.isFloatingPointTexture) this.pixelFormat = Texture.PFORMATSTR_RGBA32F; 23423 23424 if (this.textureType == Texture.TYPE_DEPTH) this.pixelFormat = Texture.PFORMATSTR_DEPTH; 23425 23426 this._cgl.profileData.profileTextureNew++; 23427 23428 this.setFormat(Texture.setUpGlPixelFormat(this._cgl, this.pixelFormat)); 23429 this._cgl.profileData.addHeavyEvent("texture created", this.name, options.width + "x" + options.height); 23430 23431 this.setSize(options.width, options.height); 23432 this.getInfoOneLine(); 23433 } 23434 23435 isFloatingPoint() 23436 { 23437 return Texture.isPixelFormatFloat(this.pixelFormat); 23438 } 23439 23440 /** 23441 * returns true if otherTexture has same options (width/height/filter/wrap etc) 23442 * @function compareSettings 23443 * @memberof Texture 23444 * @instance 23445 * @param {Texture} tex otherTexture 23446 * @returns {Boolean} 23447 */ 23448 compareSettings(tex) 23449 { 23450 // if (!tex) { this._log.warn("compare: no tex"); return false; } 23451 // if (tex.width != this.width) this._log.warn("tex.width not equal", tex.width, this.width); 23452 // if (tex.height != this.height) this._log.warn("tex.height not equal", tex.height, this.height); 23453 // if (tex.filter != this.filter) this._log.warn("tex.filter not equal"); 23454 // if (tex.wrap != this.wrap) this._log.warn("tex.wrap not equal"); 23455 // if (tex.textureType != this.textureType) this._log.warn("tex.textureType not equal"); 23456 // if (tex.unpackAlpha != this.unpackAlpha) this._log.warn("tex.unpackAlpha not equal"); 23457 // if (tex.anisotropic != this.anisotropic) this._log.warn("tex.anisotropic not equal"); 23458 // if (tex.shadowMap != this.shadowMap) this._log.warn("tex.shadowMap not equal"); 23459 // if (tex.texTarget != this.texTarget) this._log.warn("tex.texTarget not equal"); 23460 // if (tex.flip != this.flip) this._log.warn("tex.flip not equal"); 23461 23462 if (!tex) return false;
23463 return ( 23464 tex.width == this.width && 23465 tex.height == this.height && 23466 tex.filter == this.filter && 23467 tex.wrap == this.wrap && 23468 tex.textureType == this.textureType && 23469 tex.unpackAlpha == this.unpackAlpha && 23470 tex.anisotropic == this.anisotropic && 23471 tex.shadowMap == this.shadowMap && 23472 tex.texTarget == this.texTarget && 23473 tex.flip == this.flip 23474 ); 23475 } 23476 23477 /** 23478 * returns a new texture with the same settings (does not copy texture itself) 23479 * @function clone 23480 * @memberof Texture 23481 * @instance 23482 * @returns {Texture} 23483 */ 23484 clone() 23485 { 23486 const newTex = new Texture(this._cgl, { 23487 "name": this.name, 23488 "filter": this.filter, 23489 "anisotropic": this.anisotropic, 23490 "wrap": this.wrap, 23491 "textureType": this.textureType, 23492 "pixelFormat": this.pixelFormat, 23493 "unpackAlpha": this.unpackAlpha, 23494 "flip": this.flip, 23495 "width": this.width, 23496 "height": this.height, 23497 }); 23498 23499 this._cgl.profileData.addHeavyEvent("texture created", this.name, this.width + "x" + this.height); 23500 23501 if (!this.compareSettings(newTex)) 23502 { 23503 this._log.error("Cloned texture settings do not compare!"); 23504 this._log.error(this); 23505 this._log.error(newTex); 23506 } 23507 23508 return newTex; 23509 } 23510 23511 /** 23512 * @param {object} o 23513 */ 23514 setFormat(o) 23515 { 23516 this.pixelFormat = o.pixelFormat; 23517 this._glDataFormat = o.glDataFormat; 23518 this._glInternalFormat = o.glInternalFormat; 23519 this._glDataType = o.glDataType; 23520 } 23521 23522 /** 23523 * set pixel size of texture 23524 * @function setSize 23525 * @memberof Texture 23526 * @instance 23527 * @param {Number} w width 23528 * @param {Number} h height 23529 */ 23530 setSize(w, h) 23531 { 23532 if (this._cgl.aborted) return; 23533 if (w != w || w <= 0 || !w) w = DEFAULT_TEXTURE_SIZE; 23534 if (h != h || h <= 0 || !h) h = DEFAULT_TEXTURE_SIZE; 23535 23536 if (w > this._cgl.maxTexSize || h > this._cgl.maxTexSize) this._log.error("texture size too big! " + w + "x" + h + " / max: " + this._cgl.maxTexSize); 23537 23538 w = Math.min(w, this._cgl.maxTexSize); 23539 h = Math.min(h, this._cgl.maxTexSize); 23540 23541 w = Math.floor(w); 23542 h = Math.floor(h); 23543 if (this.width == w && this.height == h) return; 23544 23545 w = this._cgl.checkTextureSize(w); 23546 h = this._cgl.checkTextureSize(h); 23547 23548 this.width = w; 23549 this.height = h; 23550 this.deleted = false; 23551 23552 this.setFormat(Texture.setUpGlPixelFormat(this._cgl, this.pixelFormat)); 23553 23554 this.shortInfoString = this.getInfoOneLine();// w + "x" + h + ""; 23555 23556 this._cgl.gl.bindTexture(this.texTarget, this.tex); 23557 this._cgl.profileData.profileTextureResize++; 23558 23559 const uarr = null; 23560 23561 this._cgl.gl.texImage2D(this.texTarget, 0, this._glInternalFormat, w, h, 0, this._glDataFormat, this._glDataType, uarr); 23562 23563 this._setFilter(); 23564 23565 this.updateMipMap(); 23566 23567 this._cgl.gl.bindTexture(this.texTarget, null); 23568 } 23569 23570 /** 23571 * @function initFromData 23572 * @memberof Texture 23573 * @instance 23574 * @description create texturem from rgb data 23575 * @param {Array<Number>} data rgb color array [r,g,b,a,r,g,b,a,...] 23576 * @param {Number} w width 23577 * @param {Number} h height 23578 * @param {Number} filter 23579 * @param {Number} wrap 23580 */ 23581 initFromData(data, w, h, filter, wrap) 23582 { 23583 this.filter = filter; 23584 this.wrap = wrap; 23585 if (filter == undefined) this.filter = Texture.FILTER_LINEAR; 23586 if (wrap == undefined) this.wrap = Texture.WRAP_CLAMP_TO_EDGE; 23587 this.width = w; 23588 this.height = h; 23589 this._fromData = true; 23590 this.deleted = false; 23591 23592 if (this.height > this._cgl.maxTexSize || this.width > this._cgl.maxTexSize) 23593 { 23594 const t = CGL.Texture.getTempTexture(this._cgl); 23595 this.width = t.width; 23596 this.height = t.height; 23597 this.tex = t.tex; 23598 this._log.warn("[cgl_texture] texture size too big!", this.width, this.height, this._cgl.maxTexSize); 23599 return; 23600 } 23601 23602 if (this.flip) this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_FLIP_Y_WEBGL, this.flip); 23603 23604 this._cgl.gl.bindTexture(this.texTarget, this.tex); 23605 23606 this.setFormat(Texture.setUpGlPixelFormat(this._cgl, this.pixelFormat)); 23607 23608 this._cgl.gl.texImage2D(this.texTarget, 0, this._glInternalFormat, w, h, 0, this._glDataFormat, this._glDataType, data); 23609 23610 this._setFilter(); 23611 this.updateMipMap(); 23612 23613 if (this.flip) this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_FLIP_Y_WEBGL, false); 23614 this._cgl.gl.bindTexture(this.texTarget, null); 23615 } 23616 23617 updateMipMap() 23618 { 23619 if ((this._cgl.glVersion == 2 || this.isPowerOfTwo()) && this.filter == Texture.FILTER_MIPMAP) 23620 { 23621 this._cgl.gl.generateMipmap(this.texTarget); 23622 this._cgl.profileData.profileGenMipMap++; 23623 } 23624 } 23625 23626 /** 23627 * set texture data from an image/canvas object 23628 * @function initTexture 23629 * @memberof Texture 23630 * @instance 23631 * @param {Object} img image 23632 * @param {Number} filter 23633 */ 23634 initTexture(img, filter = null) 23635 { 23636 this._cgl.printError("before initTexture"); 23637 this._cgl.checkFrameStarted("texture inittexture"); 23638 this._fromData = false;
23639 23640 this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.unpackAlpha); 23641 if (img.width || img.videoWidth) this.width = img.videoWidth || img.width; 23642 if (img.height || img.videoHeight) this.height = img.videoHeight || img.height; 23643 23644 if (filter !== null) this.filter = filter; // todo: can we remove this filter param? 23645 23646 if (img.height > this._cgl.maxTexSize || img.width > this._cgl.maxTexSize) 23647 { 23648 const t = CGL.Texture.getTempTexture(this._cgl); 23649 this.width = t.width; 23650 this.height = t.height; 23651 this.tex = t.tex; 23652 this._log.warn("[cgl_texture] texture size too big!", img.width, img.height, this._cgl.maxTexSize); 23653 return; 23654 } 23655 23656 this._cgl.gl.bindTexture(this.texTarget, this.tex); 23657 23658 this.deleted = false; 23659 this.flipped = !this.flip; 23660 if (this.flipped) this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_FLIP_Y_WEBGL, this.flipped); 23661 23662 this.setFormat(Texture.setUpGlPixelFormat(this._cgl, this.pixelFormat)); 23663 23664 this._cgl.gl.texImage2D(this.texTarget, 0, this._glInternalFormat, this._glDataFormat, this._glDataType, img); 23665 23666 this._setFilter(); 23667 this.updateMipMap(); 23668 23669 this._cgl.gl.bindTexture(this.texTarget, null); 23670 this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); 23671 if (this.flipped) this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_FLIP_Y_WEBGL, false); 23672 23673 this.getInfoOneLine(); 23674 this._cgl.printError("initTexture"); 23675 } 23676 23677 /** 23678 * delete texture. use this when texture is no longer needed 23679 * @function delete 23680 * @memberof Texture 23681 * @instance 23682 */ 23683 dispose() 23684 { 23685 this.delete(); 23686 } 23687 23688 delete() 23689 { 23690 if (this.loading) 23691 { 23692 // cant delete texture when still loading 23693 // setTimeout(this.delete.bind(this), 50); 23694 return; 23695 } 23696 23697 this.deleted = true; 23698 this.width = 0; 23699 this.height = 0; 23700 this._cgl.profileData.profileTextureDelete++; 23701 this._cgl.gl.deleteTexture(this.tex); 23702 this.image = null; 23703 23704 this.tex = null; 23705 } 23706 23707 /** 23708 * @function isPowerOfTwo 23709 * @memberof Texture 23710 * @instance 23711 * @description return true if texture width and height are both power of two 23712 * @return {Boolean} 23713 */ 23714 isPowerOfTwo() 23715 { 23716 return Texture.isPowerOfTwo(this.width) && Texture.isPowerOfTwo(this.height); 23717 } 23718 23719 printInfo() 23720 { 23721 log.log(this.getInfo()); 23722 } 23723 23724 getInfoReadable() 23725 { 23726 const info = this.getInfo(); 23727 let html = ""; 23728 23729 info.name = info.name.substr(0, info.name.indexOf("?rnd=")); 23730 23731 for (const i in info) 23732 { 23733 html += "* " + i + ": **" + info[i] + "**\n"; 23734 } 23735 23736 return html; 23737 } 23738 23739 getInfoOneLine() 23740 { 23741 let txt = "" + this.width + "x" + this.height; 23742 txt += " "; 23743 // if (this.textureType === CGL.Texture.TYPE_FLOAT) txt += " 32bit"; else txt += " 8bit"; 23744 // if (this.textureType === CGL.Texture.TYPE_FLOAT) txt += " 32bit"; else txt += " 8bit"; 23745 txt += this.pixelFormat; 23746 23747 if (this.filter === Texture.FILTER_NEAREST) txt += " nearest"; 23748 if (this.filter === Texture.FILTER_LINEAR) txt += " linear"; 23749 if (this.filter === Texture.FILTER_MIPMAP) txt += " mipmap"; 23750 23751 if (this.wrap === Texture.WRAP_CLAMP_TO_EDGE) txt += " clamp"; 23752 if (this.wrap === Texture.WRAP_REPEAT) txt += " repeat"; 23753 if (this.wrap === Texture.WRAP_MIRRORED_REPEAT) txt += " repeatmir"; 23754 23755 this.shortInfoString = txt; 23756 23757 return txt; 23758 } 23759 23760 getInfoOneLineShort() 23761 { 23762 let txt = "" + this.width + "x" + this.height; 23763 // if (this.textureType === CGL.Texture.TYPE_FLOAT) txt += " 32bit"; else txt += " 8bit"; 23764 txt += " "; 23765 txt += this.pixelFormat; 23766 23767 this.shortInfoString = txt; 23768 23769 return txt; 23770 } 23771 23772 getInfo() 23773 { 23774 return Texture.getTexInfo(this); 23775 } 23776 23777 _setFilter() 23778 { 23779 this._cgl.printError("before _setFilter"); 23780 23781 if (!this._fromData) 23782 { 23783 this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.unpackAlpha); 23784 } 23785 23786 if (this.shadowMap) 23787 { 23788 this._cgl.gl.texParameteri(this._cgl.gl.TEXTURE_2D, this._cgl.gl.TEXTURE_COMPARE_MODE, this._cgl.gl.COMPARE_REF_TO_TEXTURE); 23789 this._cgl.gl.texParameteri(this._cgl.gl.TEXTURE_2D, this._cgl.gl.TEXTURE_COMPARE_FUNC, this._cgl.gl.LEQUAL); 23790 } 23791 23792 if (this.textureType == Texture.TYPE_FLOAT && this.filter == Texture.FILTER_MIPMAP) 23793 { 23794 this.filter = Texture.FILTER_LINEAR; 23795 this._log.stack("texture: HDR and mipmap filtering at the same time is not possible"); 23796 } 23797 23798 if (this._cgl.glVersion == 1 && !this.isPowerOfTwo()) 23799 { 23800 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_MAG_FILTER, this._cgl.gl.NEAREST); 23801 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_MIN_FILTER, this._cgl.gl.NEAREST); 23802 23803 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_WRAP_S, this._cgl.gl.CLAMP_TO_EDGE); 23804 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_WRAP_T, this._cgl.gl.CLAMP_TO_EDGE); 23805 23806 this.filter = Texture.FILTER_NEAREST; 23807 this.wrap = Texture.WRAP_CLAMP_TO_EDGE; 23808 } 23809 else 23810 { 23811 if (this.wrap == Texture.WRAP_CLAMP_TO_EDGE) 23812 { 23813 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_WRAP_S, this._cgl.gl.CLAMP_TO_EDGE); 23814 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_WRAP_T, this._cgl.gl.CLAMP_TO_EDGE); 23815 } 23816 else if (this.wrap == Texture.WRAP_REPEAT) 23817 { 23818 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_WRAP_S, this._cgl.gl.REPEAT); 23819 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_WRAP_T, this._cgl.gl.REPEAT); 23820 } 23821 else if (this.wrap == Texture.WRAP_MIRRORED_REPEAT) 23822 { 23823 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_WRAP_S, this._cgl.gl.MIRRORED_REPEAT); 23824 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_WRAP_T, this._cgl.gl.MIRRORED_REPEAT); 23825 } 23826 23827 if (this.filter == Texture.FILTER_NEAREST) 23828 { 23829 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_MAG_FILTER, this._cgl.gl.NEAREST); 23830 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_MIN_FILTER, this._cgl.gl.NEAREST); 23831 } 23832 else if (this.filter == Texture.FILTER_LINEAR) 23833 { 23834 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_MIN_FILTER, this._cgl.gl.LINEAR); 23835 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_MAG_FILTER, this._cgl.gl.LINEAR); 23836 } 23837 else if (this.filter == Texture.FILTER_MIPMAP) 23838 { 23839 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_MAG_FILTER, this._cgl.gl.LINEAR); 23840 this._cgl.gl.texParameteri(this.texTarget, this._cgl.gl.TEXTURE_MIN_FILTER, this._cgl.gl.LINEAR_MIPMAP_LINEAR); 23841 } 23842 else 23843 { 23844 this._log.log("unknown texture filter!", this.filter); 23845 throw new Error("unknown texture filter!" + this.filter); 23846 } 23847 23848 if (this.anisotropic) 23849 { 23850 const ext = this._cgl.enableExtension("EXT_texture_filter_anisotropic"); 23851 23852 if (this._cgl.maxAnisotropic) 23853 { 23854 const aniso = Math.min(this._cgl.maxAnisotropic, this.anisotropic); 23855 this._cgl.gl.texParameterf(this._cgl.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, aniso); 23856 } 23857 } 23858 } 23859 this.getInfoOneLine(); 23860 this._cgl.printError("_setFilter"); 23861 } 23862} 23863 23864/** 23865 * @function load 23866 * @static 23867 * @memberof Texture 23868 * @description load an image from an url 23869 * @param {CglContext} cgl 23870 * @param {String} url 23871 * @param {Function} finishedCallback 23872 * @param {Object} settings 23873 * @return {Texture} 23874 */ 23875Texture.load = function (cgl, url, finishedCallback, settings) 23876{ 23877 if (!url) return finishedCallback({ "error": true }); 23878 let loadingId = null; 23879 if (!cgl.patch.loading.existByName(url)) loadingId = cgl.patch.loading.start("cgl.texture", url); 23880 23881 const texture = new Texture(cgl); 23882 texture.name = url; 23883 23884 texture.image = new Image(); 23885 texture.image.crossOrigin = "anonymous"; 23886 texture.loading = true; 23887 23888 if (settings && settings.hasOwnProperty("filter")) texture.filter = settings.filter; 23889 if (settings && settings.hasOwnProperty("flip")) texture.flip = settings.flip; 23890 if (settings && settings.hasOwnProperty("wrap")) texture.wrap = settings.wrap; 23891 if (settings && settings.hasOwnProperty("anisotropic")) texture.anisotropic = settings.anisotropic; 23892 if (settings && settings.hasOwnProperty("unpackAlpha")) texture.unpackAlpha = settings.unpackAlpha; 23893 if (settings && settings.hasOwnProperty("pixelFormat")) texture.pixelFormat = settings.pixelFormat; 23894 23895 texture.image.onabort = texture.image.onerror = (e) => 23896 { 23897 console.warn("[cgl.texture.load] error loading texture", url, e); 23898 texture.loading = false;
23899 if (loadingId) cgl.patch.loading.finished(loadingId); 23900 const error = { "error": true }; 23901 if (finishedCallback) finishedCallback(error, texture); 23902 }; 23903 23904 texture.image.onload = function (e) 23905 { 23906 cgl.addNextFrameOnceCallback(() => 23907 { 23908 texture.initTexture(texture.image); 23909 if (loadingId) cgl.patch.loading.finished(loadingId); 23910 texture.loading = false; 23911 23912 if (finishedCallback) finishedCallback(null, texture); 23913 }); 23914 }; 23915 texture.image.src = url; 23916 23917 return texture; 23918}; 23919 23920/** 23921 * @static 23922 * @function getTempTexture 23923 * @memberof Texture 23924 * @description returns the default temporary texture (grey diagonal stipes) 23925 // * @param {CglContext} cgl 23926 * @return {Texture} 23927 */ 23928Texture.getTempTexture = function (cgl) 23929{ 23930 if (!cgl) console.error("[getTempTexture] no cgl!"); 23931 if (!cgl.tempTexture) cgl.tempTexture = Texture.getTemporaryTexture(cgl, 256, Texture.FILTER_LINEAR, Texture.REPEAT); 23932 return cgl.tempTexture; 23933}; 23934 23935/** 23936 * @static 23937 * @function getErrorTexture 23938 * @memberof Texture 23939 * @description returns the default temporary texture (grey diagonal stipes) 23940 * @param {CglContext} cgl 23941 * @return {Texture} 23942 */ 23943Texture.getErrorTexture = function (cgl) 23944{ 23945 if (!cgl) console.error("[getTempTexture] no cgl!"); 23946 if (!cgl.errorTexture) cgl.errorTexture = Texture.getTemporaryTexture(cgl, 256, Texture.FILTER_LINEAR, Texture.REPEAT, 1, 0.2, 0.2); 23947 return cgl.errorTexture; 23948}; 23949 23950/** 23951 * @function getEmptyTexture 23952 * @memberof Texture 23953 * @instance 23954 * @param cgl 23955 * @param fp 23956 * @description returns a reference to a small empty (transparent) texture 23957 * @return {Texture} 23958 */ 23959Texture.getEmptyTexture = function (cgl, fp) 23960{ 23961 if (fp) return Texture.getEmptyTextureFloat(cgl); 23962 if (!cgl) console.error("[getEmptyTexture] no cgl!"); 23963 if (cgl.tempTextureEmpty) return cgl.tempTextureEmpty; 23964 23965 let size = 8; 23966 23967 cgl.tempTextureEmpty = new Texture(cgl, { "name": "emptyTexture" }); 23968 const data = Texture.getDefaultTextureData("empty", size); 23969 23970 cgl.tempTextureEmpty.initFromData(data, size, size, Texture.FILTER_NEAREST, Texture.WRAP_REPEAT); 23971 23972 return cgl.tempTextureEmpty; 23973}; 23974 23975/** 23976 * @function getEmptyTextureFloat 23977 * @memberof Texture 23978 * @instance 23979 * @param cgl 23980 * @description returns a reference to a small empty (transparent) 32bit texture 23981 * @return {Texture} 23982 */ 23983Texture.getEmptyTextureFloat = function (cgl) 23984{ 23985 if (!cgl) console.error("[getEmptyTextureFloat] no cgl!"); 23986 if (cgl.tempTextureEmptyFloat) return cgl.tempTextureEmptyFloat; 23987 23988 cgl.tempTextureEmptyFloat = new Texture(cgl, { "name": "emptyTexture", "isFloatingPointTexture": true }); 23989 const data = new Float32Array(8 * 8 * 4).fill(1); 23990 for (let i = 0; i < 8 * 8 * 4; i += 4) data[i + 3] = 0; 23991 23992 cgl.tempTextureEmptyFloat.initFromData(data, 8, 8, Texture.FILTER_NEAREST, Texture.WRAP_REPEAT); 23993 23994 return cgl.tempTextureEmptyFloat; 23995}; 23996 23997/** 23998 * @function getRandomTexture 23999 * @memberof Texture 24000 * @static 24001 * @param cgl 24002 * @description returns a reference to a random texture 24003 * @return {Texture} 24004 */ 24005Texture.getRandomTexture = function (cgl) 24006{ 24007 if (!cgl) console.error("[getRandomTexture] no cgl!"); 24008 if (cgl.randomTexture) return cgl.randomTexture; 24009 24010 const size = 256; 24011 const data = Texture.getDefaultTextureData("randomUInt", size); 24012 24013 cgl.randomTexture = new Texture(cgl); 24014 cgl.randomTexture.initFromData(data, size, size, Texture.FILTER_NEAREST, Texture.WRAP_REPEAT); 24015 24016 return cgl.randomTexture; 24017}; 24018 24019/** 24020 * @function getRandomFloatTexture 24021 * @memberof Texture 24022 * @static 24023 * @param cgl 24024 * @description returns a reference to a texture containing random numbers between -1 and 1 24025 * @return {Texture} 24026 */ 24027Texture.getRandomFloatTexture = function (cgl) 24028{ 24029 if (!cgl) console.error("[getRandomTexture] no cgl!"); 24030 if (cgl.getRandomFloatTexture) return cgl.getRandomFloatTexture; 24031 24032 const size = 256; 24033 const data = Texture.getDefaultTextureData("randomFloat", size); 24034 24035 cgl.getRandomFloatTexture = new Texture(cgl, { "isFloatingPointTexture": true }); 24036 cgl.getRandomFloatTexture.initFromData(data, size, size, Texture.FILTER_NEAREST, Texture.WRAP_REPEAT); 24037 24038 return cgl.getRandomFloatTexture; 24039}; 24040 24041/** 24042 * @function getBlackTexture 24043 * @memberof Texture 24044 * @static 24045 * @param {CglContext} cgl 24046 * @description returns a reference to a black texture 24047 * @return {Texture} 24048 */ 24049Texture.getBlackTexture = function (cgl) 24050{ 24051 if (cgl.blackTexture) return cgl.blackTexture; 24052 24053 const size = 8;
24054 const data = Texture.getDefaultTextureData("color", size, { "r": 0, "g": 0, "b": 0 }); 24055 24056 cgl.blackTexture = new Texture(cgl); 24057 cgl.blackTexture.initFromData(data, size, size, Texture.FILTER_NEAREST, Texture.WRAP_REPEAT); 24058 24059 return cgl.blackTexture; 24060}; 24061 24062/** 24063 * @function getEmptyCubemapTexture 24064 * @memberof Texture 24065 * @static 24066 * @param cgl 24067 * @description returns an empty cubemap texture with rgba = [0, 0, 0, 0] 24068 * @return {Texture} 24069 */ 24070Texture.getEmptyCubemapTexture = function (cgl) 24071{ 24072 const faces = [ 24073 cgl.gl.TEXTURE_CUBE_MAP_POSITIVE_X, 24074 cgl.gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 24075 cgl.gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 24076 cgl.gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 24077 cgl.gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 24078 cgl.gl.TEXTURE_CUBE_MAP_NEGATIVE_Z 24079 ]; 24080 24081 const tex = cgl.gl.createTexture(); 24082 const target = cgl.gl.TEXTURE_CUBE_MAP; 24083 const filter = Texture.FILTER_NEAREST; 24084 const wrap = Texture.WRAP_CLAMP_TO_EDGE; 24085 const width = 8; 24086 const height = 8; 24087 24088 cgl.profileData.profileTextureNew++; 24089 24090 cgl.gl.bindTexture(target, tex); 24091 cgl.profileData.profileTextureResize++; 24092 24093 for (let i = 0; i < 6; i += 1) 24094 { 24095 const data = new Uint8Array(8 * 8 * 4); 24096 24097 cgl.gl.texImage2D(faces[i], 0, cgl.gl.RGBA, 8, 8, 0, cgl.gl.RGBA, cgl.gl.UNSIGNED_BYTE, data); 24098 cgl.gl.texParameteri(target, cgl.gl.TEXTURE_MAG_FILTER, cgl.gl.NEAREST); 24099 cgl.gl.texParameteri(target, cgl.gl.TEXTURE_MIN_FILTER, cgl.gl.NEAREST); 24100 24101 cgl.gl.texParameteri(target, cgl.gl.TEXTURE_WRAP_S, cgl.gl.CLAMP_TO_EDGE); 24102 cgl.gl.texParameteri(target, cgl.gl.TEXTURE_WRAP_T, cgl.gl.CLAMP_TO_EDGE); 24103 } 24104 24105 cgl.gl.bindTexture(target, null); 24106 24107 return { 24108 "id": cables__WEBPACK_IMPORTED_MODULE_2__.uuid(), 24109 "tex": tex, 24110 "cubemap": tex, 24111 "width": width, 24112 "height": height, 24113 "filter": filter, 24114 "wrap": wrap, 24115 "unpackAlpha": true, 24116 "flip": true, 24117 "_fromData": true, 24118 "name": "emptyCubemapTexture", 24119 "anisotropic": 0, 24120 }; 24121}; 24122 24123Texture.getTempGradientTexture = function (cgl) // deprecated... 24124{ 24125 if (!cgl) console.error("[getTempGradientTexture] no cgl!"); 24126 return Texture.getTempTexture(cgl); 24127}; 24128 24129Texture.getTemporaryTexture = function (cgl, size, filter, wrap, r, g, b) 24130{ 24131 const data = Texture.getDefaultTextureData("stripes", 256, { "r": r, "g": g, "b": b }); 24132 const temptex = new Texture(cgl); 24133 temptex.initFromData(data, size, size, filter, wrap); 24134 return temptex; 24135}; 24136 24137/** 24138 * @static 24139 * @function createFromImage 24140 * @memberof Texture 24141 * @description create texturem from image data (e.g. image or canvas) 24142 * @param {CglContext} cgl 24143 * @param {Object} img image 24144 * @param {Object} options 24145 */ 24146Texture.createFromImage = function (cgl, img, options) 24147{ 24148 options = options || {}; 24149 const texture = new Texture(cgl, options); 24150 texture.flip = false; 24151 texture.image = img; 24152 texture.width = img.videoWidth || img.width || 8; 24153 texture.height = img.videoHeight || img.height || 8; 24154 if (options.hasOwnProperty("wrap"))texture.wrap = options.wrap; 24155 24156 texture.initTexture(img, options.filter); 24157 24158 return texture; 24159}; 24160 24161// deprecated! 24162Texture.fromImage = function (cgl, img, filter, wrap) 24163{ 24164 console.error("deprecated texture from image..."); 24165 24166 const texture = new Texture(cgl); 24167 texture.flip = false; 24168 if (filter) texture.filter = filter; 24169 if (wrap) texture.wrap = wrap; 24170 texture.image = img; 24171 texture.initTexture(img); 24172 return texture; 24173}; 24174 24175/** 24176 * @static 24177 * @function isPowerOfTwo 24178 * @memberof Texture 24179 * @description returns true if x is power of two 24180 * @param {Number} x 24181 * @return {Boolean} 24182 */ 24183Texture.isPowerOfTwo = function (x) 24184{ 24185 return x == 1 || x == 2 || x == 4 || x == 8 || x == 16 || x == 32 || x == 64 || x == 128 || x == 256 || x == 512 || x == 1024 || x == 2048 || x == 4096 || x == 8192 || x == 16384; 24186}; 24187 24188Texture.getTexInfo = function (tex) 24189{ 24190 const obj = {}; 24191 24192 obj.name = tex.name; 24193 obj["power of two"] = tex.isPowerOfTwo(); 24194 obj.size = tex.width + " x " + tex.height; 24195 24196 let targetString = tex.texTarget; 24197 if (tex.texTarget == tex._cgl.gl.TEXTURE_2D) targetString = "TEXTURE_2D"; 24198 obj.target = targetString; 24199 24200 obj.unpackAlpha = tex.unpackAlpha; 24201 24202 if (tex.cubemap)obj.cubemap = true; 24203 24204 if (tex.textureType == Texture.TYPE_FLOAT) obj.textureType = "TYPE_FLOAT"; 24205 if (tex.textureType == Texture.TYPE_HALF_FLOAT) obj.textureType = "TYPE_HALF_FLOAT"; 24206 else if (tex.textureType == Texture.TYPE_DEPTH) obj.textureType = "TYPE_DEPTH"; 24207 else if (tex.textureType == Texture.TYPE_DEFAULT) obj.textureType = "TYPE_DEFAULT"; 24208 else obj.textureType = "UNKNOWN " + this.textureType; 24209 24210 if (tex.wrap == Texture.WRAP_CLAMP_TO_EDGE) obj.wrap = "CLAMP_TO_EDGE"; 24211 else if (tex.wrap == Texture.WRAP_REPEAT) obj.wrap = "WRAP_REPEAT"; 24212 else if (tex.wrap == Texture.WRAP_MIRRORED_REPEAT) obj.wrap = "WRAP_MIRRORED_REPEAT"; 24213 else obj.wrap = "UNKNOWN"; 24214 24215 if (tex.filter == Texture.FILTER_NEAREST) obj.filter = "FILTER_NEAREST"; 24216 else if (tex.filter == Texture.FILTER_LINEAR) obj.filter = "FILTER_LINEAR"; 24217 else if (tex.filter == Texture.FILTER_MIPMAP) obj.filter = "FILTER_MIPMAP"; 24218 else obj.filter = "UNKNOWN"; 24219 24220 obj.pixelFormat = tex.pixelFormat || "unknown"; 24221 24222 return obj; 24223}; 24224 24225Texture.setUpGlPixelFormat = function (cgl, pixelFormatStr) 24226{ 24227 const o = {}; 24228 24229 if (!pixelFormatStr) 24230 { 24231 cgl._log.error("no pixelformatstr!"); 24232 cgl._log.log(new Error()); 24233 pixelFormatStr = Texture.PFORMATSTR_RGBA8UB; 24234 } 24235 24236 o.pixelFormatBase = pixelFormatStr; 24237 o.pixelFormat = pixelFormatStr; 24238 o.glDataType = cgl.gl.UNSIGNED_BYTE; 24239 o.glInternalFormat = cgl.gl.RGBA8; 24240 o.glDataFormat = cgl.gl.RGBA; 24241 24242 let floatDatatype = cgl.gl.FLOAT; 24243 24244 if (cgl.glUseHalfFloatTex) 24245 { 24246 if (pixelFormatStr == Texture.PFORMATSTR_RGBA32F) pixelFormatStr = Texture.PFORMATSTR_RGBA16F; 24247 if (pixelFormatStr == Texture.PFORMATSTR_RG32F) pixelFormatStr = Texture.PFORMATSTR_RG16F; 24248 if (pixelFormatStr == Texture.PFORMATSTR_R32F) pixelFormatStr = Texture.PFORMATSTR_R16F; 24249 } 24250 24251 if (pixelFormatStr.includes("16bit")) 24252 { 24253 if (cgl.glVersion == 2) 24254 { 24255 // cgl.enableExtension("OES_texture_half_float"); 24256 const hasExt = cgl.enableExtension("EXT_color_buffer_half_float"); 24257 24258 if (!hasExt) 24259 { 24260 console.warn("no 16bit extension, fallback to 32bit", pixelFormatStr); 24261 // fallback to 32 bit? 24262 if (pixelFormatStr == Texture.PFORMATSTR_RGBA16F) pixelFormatStr = Texture.PFORMATSTR_RGBA32F; 24263 if (pixelFormatStr == Texture.PFORMATSTR_RGB16F) pixelFormatStr = Texture.PFORMATSTR_RGB32F; 24264 if (pixelFormatStr == Texture.PFORMATSTR_RG16F) pixelFormatStr = Texture.PFORMATSTR_RG32F; 24265 if (pixelFormatStr == Texture.PFORMATSTR_R16F) pixelFormatStr = Texture.PFORMATSTR_R32F; 24266 } 24267 else 24268 { 24269 floatDatatype = cgl.gl.HALF_FLOAT; 24270 } 24271 } 24272 } 24273 24274 if (cgl.glVersion == 1) 24275 { 24276 o.glInternalFormat = cgl.gl.RGBA; 24277 24278 if (pixelFormatStr == Texture.PFORMATSTR_RGBA16F || pixelFormatStr == Texture.PFORMATSTR_RG16F || pixelFormatStr == Texture.PFORMATSTR_R16F) 24279 { 24280 const ext = cgl.enableExtension("OES_texture_half_float"); 24281 if (!ext) throw new Error("no half float texture extension"); 24282 24283 floatDatatype = ext.HALF_FLOAT_OES; 24284 } 24285 } 24286 24287 if (pixelFormatStr == Texture.PFORMATSTR_RGBA8UB) 24288 { 24289 } 24290 else if (pixelFormatStr == Texture.PFORMATSTR_RGB565) 24291 { 24292 o.glInternalFormat = cgl.gl.RGB565; 24293 o.glDataFormat = cgl.gl.RGB; 24294 } 24295 else if (pixelFormatStr == Texture.PFORMATSTR_R8UB) 24296 { 24297 o.glInternalFormat = cgl.gl.R8; 24298 o.glDataFormat = cgl.gl.RED; 24299 } 24300 else if (pixelFormatStr == Texture.PFORMATSTR_RG8UB) 24301 { 24302 o.glInternalFormat = cgl.gl.RG8; 24303 o.glDataFormat = cgl.gl.RG; 24304 } 24305 else if (pixelFormatStr == Texture.PFORMATSTR_RGB8UB) 24306 { 24307 o.glInternalFormat = cgl.gl.RGB8; 24308 o.glDataFormat = cgl.gl.RGB; 24309 } 24310 else if (pixelFormatStr == Texture.PFORMATSTR_SRGBA8) 24311 { 24312 o.glInternalFormat = cgl.gl.SRGB8_ALPHA8; 24313 } 24314 24315 else if (pixelFormatStr == Texture.PFORMATSTR_R32F) 24316 { 24317 o.glInternalFormat = cgl.gl.R32F; 24318 o.glDataFormat = cgl.gl.RED; 24319 o.glDataType = floatDatatype; 24320 } 24321 else if (pixelFormatStr == Texture.PFORMATSTR_R16F) 24322 { 24323 o.glInternalFormat = cgl.gl.R16F; 24324 o.glDataType = floatDatatype; 24325 o.glDataFormat = cgl.gl.RED; 24326 } 24327 else if (pixelFormatStr == Texture.PFORMATSTR_RG16F) 24328 { 24329 o.glInternalFormat = cgl.gl.RG16F; 24330 o.glDataType = floatDatatype; 24331 o.glDataFormat = cgl.gl.RG; 24332 } 24333 else if (pixelFormatStr == Texture.PFORMATSTR_RGBA16F) 24334 { 24335 if (cgl.glVersion == 1) o.glInternalFormat = cgl.gl.RGBA; 24336 else o.glInternalFormat = cgl.gl.RGBA16F; 24337 o.glDataType = floatDatatype; 24338 } 24339 else if (pixelFormatStr == Texture.PFORMATSTR_R11FG11FB10F) 24340 { 24341 o.glInternalFormat = cgl.gl.R11F_G11F_B10F; 24342 o.glDataType = floatDatatype; 24343 o.glDataFormat = cgl.gl.RGB; 24344 } 24345 else if (pixelFormatStr == Texture.PFORMATSTR_RGBA32F) 24346 { 24347 if (cgl.glVersion == 1) o.glInternalFormat = cgl.gl.RGBA; 24348 else o.glInternalFormat = cgl.gl.RGBA32F; 24349 o.glDataType = floatDatatype; 24350 } 24351 else if (pixelFormatStr == Texture.PFORMATSTR_DEPTH) 24352 { 24353 if (cgl.glVersion == 1) 24354 { 24355 o.glInternalFormat = cgl.gl.DEPTH_COMPONENT; 24356 o.glDataType = cgl.gl.UNSIGNED_SHORT; 24357 o.glDataFormat = cgl.gl.DEPTH_COMPONENT; 24358 } 24359 else 24360 { 24361 o.glInternalFormat = cgl.gl.DEPTH_COMPONENT32F; 24362 o.glDataType = cgl.gl.FLOAT; 24363 o.glDataFormat = cgl.gl.DEPTH_COMPONENT; 24364 } 24365 } 24366 else 24367 { 24368 log.log("unknown pixelformat ", pixelFormatStr); 24369 } 24370 24371 /// ////// 24372 24373 if (pixelFormatStr.includes("32bit") || pixelFormatStr == Texture.PFORMATSTR_R11FG11FB10F) 24374 { 24375 if (cgl.glVersion == 2) cgl.enableExtension("EXT_color_buffer_float"); 24376 if (cgl.glVersion == 2) cgl.enableExtension("EXT_float_blend"); 24377 24378 cgl.enableExtension("OES_texture_float_linear"); // yes, i am sure, this is a webgl 1 and 2 ext 24379 } 24380 24381 o.numColorChannels = Texture.getPixelFormatNumChannels(pixelFormatStr); 24382 24383 if (!o.glDataType || !o.glInternalFormat || !o.glDataFormat) log.log("pixelformat wrong ?!", pixelFormatStr, o.glDataType, o.glInternalFormat, o.glDataFormat, this); 24384 24385 return o; 24386}; 24387 24388Texture.getPixelFormatNumChannels = 24389 (pxlFrmtStr) => 24390 { 24391 if (pxlFrmtStr.startsWith("RGBA")) return 4; 24392 if (pxlFrmtStr.startsWith("RGB")) return 3; 24393 if (pxlFrmtStr.startsWith("RG")) return 2; 24394 return 1; 24395 }; 24396 24397Texture.isPixelFormatFloat = 24398 (pxlFrmtStr) => 24399 { 24400 return (pxlFrmtStr || "").includes("float"); 24401 }; 24402 24403Texture.isPixelFormatHalfFloat = 24404 (pxlFrmtStr) => 24405 { 24406 return (pxlFrmtStr || "").includes("float") && (pxlFrmtStr || "").includes("16bit"); 24407 }; 24408 24409 24410/***/ }), 24411
24412/***/ "./src/corelibs/cgl/cgl_textureeffect.js": 24413/*!***********************************************!*\ 24414 !*** ./src/corelibs/cgl/cgl_textureeffect.js ***! 24415 \***********************************************/ 24416/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 24417 24418"use strict"; 24419/* harmony export */ __webpack_require__.d(__webpack_exports__, { 24420/* harmony export */ TextureEffect: () => (/* binding */ TextureEffect) 24421/* harmony export */ }); 24422/* harmony import */ var cables_shared_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables-shared-client */ "../shared/client/src/logger.js"); 24423/* harmony import */ var _cgl_texture_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cgl_texture.js */ "./src/corelibs/cgl/cgl_texture.js"); 24424/* harmony import */ var _cgl_simplerect_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./cgl_simplerect.js */ "./src/corelibs/cgl/cgl_simplerect.js"); 24425 24426 24427 24428 24429class TextureEffect 24430{ 24431 constructor(cgl, options) 24432 { 24433 this._cgl = cgl; 24434 this._log = new cables_shared_client__WEBPACK_IMPORTED_MODULE_0__["default"]("cgl_TextureEffect"); 24435 24436 if (!cgl.TextureEffectMesh) this.createMesh(); 24437 24438 this._textureSource = null; 24439 this._options = options; 24440 this.name = options.name || "unknown"; 24441 24442 this.imgCompVer = 0; 24443 this.aspectRatio = 1; 24444 this._textureTarget = null; // new CGL.Texture(this._cgl,opts); 24445 this._frameBuf = this._cgl.gl.createFramebuffer(); 24446 this._frameBuf2 = this._cgl.gl.createFramebuffer(); 24447 this._renderbuffer = this._cgl.gl.createRenderbuffer(); 24448 this._renderbuffer2 = this._cgl.gl.createRenderbuffer(); 24449 this.switched = false; 24450 this.depth = false; 24451 } 24452 24453 dispose() 24454 { 24455 if (this._renderbuffer) this._cgl.gl.deleteRenderbuffer(this._renderbuffer); 24456 if (this._frameBuf) this._cgl.gl.deleteFramebuffer(this._frameBuf); 24457 if (this._renderbuffer2) this._cgl.gl.deleteRenderbuffer(this._renderbuffer2); 24458 if (this._frameBuf2) this._cgl.gl.deleteFramebuffer(this._frameBuf2); 24459 } 24460 24461 getWidth() 24462 { 24463 return this._textureSource.width; 24464 } 24465 24466 getHeight() 24467 { 24468 return this._textureSource.height; 24469 } 24470 24471 setSourceTexture(tex) 24472 { 24473 if (tex === null) 24474 { 24475 this._textureSource = new _cgl_texture_js__WEBPACK_IMPORTED_MODULE_1__.Texture(this._cgl); 24476 this._textureSource.setSize(16, 16); 24477 } 24478 else 24479 { 24480 this._textureSource = tex; 24481 } 24482 24483 if (!this._textureSource.compareSettings(this._textureTarget)) 24484 { 24485 if (this._textureTarget) this._textureTarget.delete(); 24486 24487 this._textureTarget = this._textureSource.clone(); 24488 24489 this._cgl.profileData.profileEffectBuffercreate++; 24490 24491 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._frameBuf); 24492 24493 this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER, this._renderbuffer); 24494 24495 // if(tex.textureType==CGL.Texture.TYPE_FLOAT) this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER,this._cgl.gl.RGBA32F, this._textureSource.width,this._textureSource.height); 24496 // else this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER,this._cgl.gl.RGBA8, this._textureSource.width,this._textureSource.height); 24497 24498 if (this.depth) this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER, this._cgl.gl.DEPTH_COMPONENT16, this._textureSource.width, this._textureSource.height); 24499 this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.COLOR_ATTACHMENT0, this._cgl.gl.TEXTURE_2D, this._textureTarget.tex, 0); 24500 if (this.depth) this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.DEPTH_ATTACHMENT, this._cgl.gl.RENDERBUFFER, this._renderbuffer); 24501 24502 // this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.COLOR_ATTACHMENT0, this._cgl.gl.TEXTURE_2D, this._textureTarget.tex, 0); 24503 24504 this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D, null); 24505 this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER, null); 24506 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, null); 24507 24508 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._frameBuf2); 24509 24510 this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER, this._renderbuffer2); 24511 24512 // if(tex.textureType==CGL.Texture.TYPE_FLOAT) this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER,this._cgl.gl.RGBA32F, this._textureSource.width,this._textureSource.height); 24513 // else this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER,this._cgl.gl.RGBA8, this._textureSource.width,this._textureSource.height); 24514 24515 if (this.depth) this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER, this._cgl.gl.DEPTH_COMPONENT16, this._textureSource.width, this._textureSource.height); 24516 this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.COLOR_ATTACHMENT0, this._cgl.gl.TEXTURE_2D, this._textureSource.tex, 0); 24517 24518 if (this.depth) this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.DEPTH_ATTACHMENT, this._cgl.gl.RENDERBUFFER, this._renderbuffer2); 24519 24520 // this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.COLOR_ATTACHMENT0, this._cgl.gl.TEXTURE_2D, this._textureSource.tex, 0); 24521 24522 this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D, null); 24523 this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER, null); 24524 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, null); 24525 } 24526 24527 this.aspectRatio = this._textureSource.width / this._textureSource.height; 24528 } 24529 24530 continueEffect() 24531 { 24532 this._cgl.pushDepthTest(false); 24533 this._cgl.pushModelMatrix(); 24534 this._cgl.pushPMatrix(); 24535 // todo why two pushs? 24536 24537 this._cgl.pushViewPort(0, 0, this.getCurrentTargetTexture().width, this.getCurrentTargetTexture().height); 24538 24539 mat4.perspective(this._cgl.pMatrix, 45, this.getCurrentTargetTexture().width / this.getCurrentTargetTexture().height, 0.1, 1100.0); // todo: why? 24540 24541 this._cgl.pushPMatrix(); 24542 mat4.identity(this._cgl.pMatrix); 24543 24544 this._cgl.pushViewMatrix(); 24545 mat4.identity(this._cgl.vMatrix); 24546 24547 this._cgl.pushModelMatrix(); 24548 mat4.identity(this._cgl.mMatrix); 24549 } 24550 24551 startEffect(bgTex) 24552 { 24553 if (!this._textureTarget) 24554 { 24555 this._log.warn("effect has no target"); 24556 return; 24557 } 24558 24559 this.switched = false;
24560 24561 this.continueEffect(); 24562 24563 if (bgTex) 24564 { 24565 this._bgTex = bgTex; 24566 } 24567 this._countEffects = 0; 24568 } 24569 24570 endEffect() 24571 { 24572 this._cgl.popDepthTest(); 24573 this._cgl.popModelMatrix(); 24574 24575 this._cgl.popPMatrix(); 24576 this._cgl.popModelMatrix(); 24577 this._cgl.popViewMatrix(); 24578 24579 this._cgl.popPMatrix(); 24580 this._cgl.popViewPort(); 24581 } 24582 24583 bind() 24584 { 24585 if (this._textureSource === null) 24586 { 24587 this._log.warn("no base texture set!"); 24588 return; 24589 } 24590 24591 if (!this.switched) 24592 { 24593 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._frameBuf); 24594 this._cgl.pushGlFrameBuffer(this._frameBuf); 24595 } 24596 else 24597 { 24598 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._frameBuf2); 24599 this._cgl.pushGlFrameBuffer(this._frameBuf2); 24600 } 24601 } 24602 24603 finish() 24604 { 24605 if (this._textureSource === null) 24606 { 24607 this._log.warn("no base texture set!"); 24608 return; 24609 } 24610 24611 this._cgl.TextureEffectMesh.render(this._cgl.getShader()); 24612 24613 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._cgl.popGlFrameBuffer()); 24614 24615 this._cgl.profileData.profileTextureEffect++; 24616 24617 if (this._textureTarget.filter == _cgl_texture_js__WEBPACK_IMPORTED_MODULE_1__.Texture.FILTER_MIPMAP) 24618 { 24619 if (!this.switched) 24620 { 24621 this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D, this._textureTarget.tex); 24622 this._textureTarget.updateMipMap(); 24623 } 24624 else 24625 { 24626 this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D, this._textureSource.tex); 24627 this._textureSource.updateMipMap(); 24628 } 24629 24630 this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D, null); 24631 } 24632 24633 this.switched = !this.switched; 24634 this._countEffects++; 24635 } 24636 24637 getCurrentTargetTexture() 24638 { 24639 if (this.switched) return this._textureSource; 24640 return this._textureTarget; 24641 } 24642 24643 getCurrentSourceTexture() 24644 { 24645 if (this._countEffects == 0 && this._bgTex) return this._bgTex; 24646 24647 if (this.switched) return this._textureTarget; 24648 return this._textureSource; 24649 } 24650 24651 delete() 24652 { 24653 if (this._textureTarget) this._textureTarget.delete(); 24654 if (this._textureSource) this._textureSource.delete(); 24655 this._cgl.gl.deleteRenderbuffer(this._renderbuffer); 24656 this._cgl.gl.deleteFramebuffer(this._frameBuf); 24657 } 24658 24659 createMesh() 24660 { 24661 this._cgl.TextureEffectMesh = _cgl_simplerect_js__WEBPACK_IMPORTED_MODULE_2__.MESHES.getSimpleRect(this._cgl, "texEffectRect"); 24662 } 24663 24664 // --------------------------------------------------------------------------------- 24665} 24666 24667TextureEffect.checkOpNotInTextureEffect = function (op) 24668{ 24669 if (!op.patch.cgl) return true; 24670 if (op.uiAttribs.error && !op.patch.cgl.currentTextureEffect) 24671 { 24672 op.setUiError("textureeffect", null); 24673 return true; 24674 } 24675 if (!op.patch.cgl.currentTextureEffect) return true; 24676 24677 if (op.patch.cgl.currentTextureEffect && !op.uiAttribs.error) 24678 { 24679 op.setUiError("textureeffect", "This op can not be a child of a ImageCompose/texture effect! imagecompose should only have textureeffect childs.", 0); 24680 return false; 24681 } 24682 24683 if (op.patch.cgl.currentTextureEffect) return false; 24684 return true; 24685}; 24686 24687TextureEffect.checkOpInEffect = function (op, minver) 24688{ 24689 minver = minver || 0; 24690 24691 if (op.patch.cgl.currentTextureEffect) 24692 { 24693 if (op.uiAttribs.uierrors && op.patch.cgl.currentTextureEffect.imgCompVer >= minver) 24694 { 24695 op.setUiError("texeffect", null); 24696 return true; 24697 } 24698 24699 if (minver && op.patch.cgl.currentTextureEffect.imgCompVer < minver) 24700 { 24701 op.setUiError("texeffect", "This op must be a child of an ImageCompose op with version >=" + minver + " <span class=\"button-small\" onclick=\"gui.patchView.downGradeOp('" + op.id + "','" + op.name + "')\">Downgrade</span> to previous version", 1); 24702 } 24703 } 24704 24705 if (op.patch.cgl.currentTextureEffect) return true; 24706 24707 if (!op.patch.cgl.currentTextureEffect && (!op.uiAttribs.uierrors || op.uiAttribs.uierrors.length == 0)) 24708 { 24709 op.setUiError("texeffect", "This op must be a child of an ImageCompose op! More infos <a href=\"https://cables.gl/docs/image_composition/image_composition.html\" target=\"_blank\">here</a>. ", 1); 24710 return false;
24711 } 24712 24713 if (!op.patch.cgl.currentTextureEffect) return false; 24714 return true; 24715}; 24716 24717TextureEffect.getBlendCode = function (ver) 24718{ 24719 let src = "".endl() 24720 + "vec3 _blend(vec3 base,vec3 blend)".endl() 24721 + "{".endl() 24722 + " vec3 colNew=blend;".endl() 24723 + " #ifdef BM_MULTIPLY".endl() 24724 + " colNew=base*blend;".endl() 24725 + " #endif".endl() 24726 + " #ifdef BM_MULTIPLY_INV".endl() 24727 + " colNew=base* vec3(1.0)-blend;".endl() 24728 + " #endif".endl() 24729 + " #ifdef BM_AVERAGE".endl() 24730 + " colNew=((base + blend) / 2.0);".endl() 24731 + " #endif".endl() 24732 + " #ifdef BM_ADD".endl() 24733 + " colNew=min(base + blend, vec3(1.0));".endl() 24734 + " #endif".endl() 24735 + " #ifdef BM_SUBTRACT_ONE".endl() 24736 + " colNew=max(base + blend - vec3(1.0), vec3(0.0));".endl() 24737 + " #endif".endl() 24738 24739 + " #ifdef BM_SUBTRACT".endl() 24740 + " colNew=base - blend;".endl() 24741 + " #endif".endl() 24742 24743 + " #ifdef BM_DIFFERENCE".endl() 24744 + " colNew=abs(base - blend);".endl() 24745 + " #endif".endl() 24746 + " #ifdef BM_NEGATION".endl() 24747 + " colNew=(vec3(1.0) - abs(vec3(1.0) - base - blend));".endl() 24748 + " #endif".endl() 24749 + " #ifdef BM_EXCLUSION".endl() 24750 + " colNew=(base + blend - 2.0 * base * blend);".endl() 24751 + " #endif".endl() 24752 + " #ifdef BM_LIGHTEN".endl() 24753 + " colNew=max(blend, base);".endl() 24754 + " #endif".endl() 24755 + " #ifdef BM_DARKEN".endl() 24756 + " colNew=min(blend, base);".endl() 24757 + " #endif".endl() 24758 + " #ifdef BM_OVERLAY".endl() 24759 + " #define BlendOverlayf(base, blend) (base < 0.5 ? (2.0 * base * blend) : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend)))" 24760 // .endl()+' #define BlendOverlay(base, blend) Blend(base, blend, BlendOverlayf)' 24761 // .endl()+' colNew=Blend(base, blend, BlendOverlayf);' 24762 .endl() 24763 + " colNew=vec3(BlendOverlayf(base.r, blend.r),BlendOverlayf(base.g, blend.g),BlendOverlayf(base.b, blend.b));".endl() 24764 + " #endif".endl() 24765 + " #ifdef BM_SCREEN".endl() 24766 + " #define BlendScreenf(base, blend) (1.0 - ((1.0 - base) * (1.0 - blend)))" 24767 // .endl()+' #define BlendScreen(base, blend) Blend(base, blend, BlendScreenf)' 24768 // .endl()+' colNew=Blend(base, blend, BlendScreenf);' 24769 .endl() 24770 + " colNew=vec3(BlendScreenf(base.r, blend.r),BlendScreenf(base.g, blend.g),BlendScreenf(base.b, blend.b));".endl() 24771 + " #endif".endl() 24772 + " #ifdef BM_SOFTLIGHT".endl() 24773 + " #define BlendSoftLightf(base, blend) ((blend < 0.5) ? (2.0 * base * blend + base * base * (1.0 - 2.0 * blend)) : (sqrt(base) * (2.0 * blend - 1.0) + 2.0 * base * (1.0 - blend)))" 24774 // .endl()+' #define BlendSoftLight(base, blend) Blend(base, blend, BlendSoftLightf)' 24775 // .endl()+' colNew=Blend(base, blend, BlendSoftLightf);' 24776 .endl() 24777 + " colNew=vec3(BlendSoftLightf(base.r, blend.r),BlendSoftLightf(base.g, blend.g),BlendSoftLightf(base.b, blend.b));".endl() 24778 + " #endif".endl() 24779 + " #ifdef BM_HARDLIGHT".endl() 24780 + " #define BlendOverlayf(base, blend) (base < 0.5 ? (2.0 * base * blend) : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend)))" 24781 // .endl()+' #define BlendOverlay(base, blend) Blend(base, blend, BlendOverlayf)' 24782 // .endl()+' colNew=Blend(blend, base, BlendOverlayf);' 24783 .endl() 24784 + " colNew=vec3(BlendOverlayf(base.r, blend.r),BlendOverlayf(base.g, blend.g),BlendOverlayf(base.b, blend.b));".endl() 24785 + " #endif".endl() 24786 + " #ifdef BM_COLORDODGE".endl() 24787 + " #define BlendColorDodgef(base, blend) ((blend == 1.0) ? blend : min(base / (1.0 - blend), 1.0))" 24788 // .endl()+' colNew=Blend(base, blend, BlendColorDodgef);' 24789 .endl() 24790 + " colNew=vec3(BlendColorDodgef(base.r, blend.r),BlendColorDodgef(base.g, blend.g),BlendColorDodgef(base.b, blend.b));".endl() 24791 + " #endif".endl() 24792 + " #ifdef BM_COLORBURN".endl() 24793 + " #define BlendColorBurnf(base, blend) ((blend == 0.0) ? blend : max((1.0 - ((1.0 - base) / blend)), 0.0))" 24794 // .endl()+' colNew=Blend(base, blend, BlendColorBurnf);' 24795 .endl() 24796 + " colNew=vec3(BlendColorBurnf(base.r, blend.r),BlendColorBurnf(base.g, blend.g),BlendColorBurnf(base.b, blend.b));".endl() 24797 + " #endif".endl() 24798
24799 + " return colNew;".endl() 24800 + "}".endl(); 24801 24802 if (!ver) 24803 src += "vec4 cgl_blend(vec4 oldColor,vec4 newColor,float amount)".endl() 24804 + "{".endl() 24805 + "vec4 col=vec4( _blend(oldColor.rgb,newColor.rgb) ,1.0);".endl() 24806 + "col=vec4( mix( col.rgb, oldColor.rgb ,1.0-oldColor.a*amount),1.0);".endl() 24807 + "return col;".endl() 24808 + "}".endl(); 24809 24810 if (ver >= 3) 24811 src += "vec4 cgl_blendPixel(vec4 base,vec4 col,float amount)".endl() + 24812 "{".endl() + 24813 24814 "#ifdef BM_MATH_ADD".endl() + 24815 " return vec4(base.rgb+col.rgb*amount,1.0);".endl() + 24816 "#endif".endl() + 24817 24818 "#ifdef BM_MATH_SUB".endl() + 24819 " return vec4(base.rgb-col.rgb*amount,1.0);".endl() + 24820 "#endif".endl() + 24821 24822 "#ifdef BM_MATH_MUL".endl() + 24823 " return vec4(base.rgb*col.rgb*amount,1.0);".endl() + 24824 "#endif".endl() + 24825 24826 "#ifdef BM_MATH_DIV".endl() + 24827 " return vec4(base.rgb/col.rgb*amount,1.0);".endl() + 24828 "#endif".endl() + 24829 24830 "#ifndef BM_MATH".endl() + 24831 "vec3 colNew=_blend(base.rgb,col.rgb);".endl() + 24832 24833 "float newA=clamp(base.a+(col.a*amount),0.,1.);".endl() + 24834 24835 "#ifdef BM_ALPHAMASKED".endl() + 24836 "newA=base.a;".endl() + 24837 "#endif".endl() + 24838 24839 "return vec4(".endl() + 24840 "mix(colNew,base.rgb,1.0-(amount*col.a)),".endl() + 24841 "newA);".endl() + 24842 24843 "#endif".endl() + 24844 "}".endl(); 24845 24846 return src; 24847}; 24848 24849TextureEffect.onChangeBlendSelect = function (shader, blendName, maskAlpha = false) 24850{ 24851 blendName = String(blendName); 24852 shader.toggleDefine("BM_NORMAL", blendName == "normal"); 24853 shader.toggleDefine("BM_MULTIPLY", blendName == "multiply"); 24854 shader.toggleDefine("BM_MULTIPLY_INV", blendName == "multiply invert"); 24855 shader.toggleDefine("BM_AVERAGE", blendName == "average"); 24856 shader.toggleDefine("BM_ADD", blendName == "add"); 24857 shader.toggleDefine("BM_SUBTRACT_ONE", blendName == "subtract one"); 24858 shader.toggleDefine("BM_SUBTRACT", blendName == "subtract"); 24859 shader.toggleDefine("BM_DIFFERENCE", blendName == "difference"); 24860 shader.toggleDefine("BM_NEGATION", blendName == "negation"); 24861 shader.toggleDefine("BM_EXCLUSION", blendName == "exclusion"); 24862 shader.toggleDefine("BM_LIGHTEN", blendName == "lighten"); 24863 shader.toggleDefine("BM_DARKEN", blendName == "darken"); 24864 shader.toggleDefine("BM_OVERLAY", blendName == "overlay"); 24865 shader.toggleDefine("BM_SCREEN", blendName == "screen"); 24866 shader.toggleDefine("BM_SOFTLIGHT", blendName == "softlight"); 24867 shader.toggleDefine("BM_HARDLIGHT", blendName == "hardlight"); 24868 shader.toggleDefine("BM_COLORDODGE", blendName == "color dodge"); 24869 shader.toggleDefine("BM_COLORBURN", blendName == "color burn"); 24870 24871 shader.toggleDefine("BM_MATH_ADD", blendName == "Math Add"); 24872 shader.toggleDefine("BM_MATH_SUB", blendName == "Math Subtract"); 24873 shader.toggleDefine("BM_MATH_MUL", blendName == "Math Multiply"); 24874 shader.toggleDefine("BM_MATH_DIV", blendName == "Math Divide"); 24875 24876 shader.toggleDefine("BM_MATH", blendName.indexOf("Math ") == 0); 24877 24878 shader.toggleDefine("BM_ALPHAMASKED", maskAlpha); 24879}; 24880 24881TextureEffect.AddBlendSelect = function (op, name, defaultMode) 24882{ 24883 const p = op.inValueSelect(name || "Blend Mode", [ 24884 "normal", "lighten", "darken", "multiply", "multiply invert", "average", "add", "subtract", "difference", "negation", "exclusion", "overlay", "screen", "color dodge", "color burn", "softlight", "hardlight", "subtract one", 24885 "Math Add", 24886 "Math Subtract", 24887 "Math Multiply", 24888 "Math Divide", 24889 24890 ], defaultMode || "normal"); 24891 return p; 24892}; 24893 24894TextureEffect.AddBlendAlphaMask = function (op, name, defaultMode) 24895{ 24896 const p = op.inSwitch(name || "Alpha Mask", ["Off", "On"], defaultMode || "Off"); 24897 return p; 24898}; 24899 24900TextureEffect.setupBlending = function (op, shader, blendPort, amountPort, alphaMaskPort) 24901{ 24902 const onChange = () => 24903 { 24904 let maskAlpha = false;
24905 if (alphaMaskPort) maskAlpha = alphaMaskPort.get() == "On"; 24906 TextureEffect.onChangeBlendSelect(shader, blendPort.get(), maskAlpha); 24907 24908 let str = blendPort.get(); 24909 if (str == "normal") str = null; 24910 else if (str == "multiply") str = "mul"; 24911 else if (str == "multiply invert") str = "mulinv"; 24912 else if (str == "lighten") str = "light"; 24913 else if (str == "darken") str = "darken"; 24914 else if (str == "average") str = "avg"; 24915 else if (str == "subtract one") str = "sub one"; 24916 else if (str == "subtract") str = "sub"; 24917 else if (str == "difference") str = "diff"; 24918 else if (str == "negation") str = "neg"; 24919 else if (str == "exclusion") str = "exc"; 24920 else if (str == "overlay") str = "ovl"; 24921 else if (str == "color dodge") str = "dodge"; 24922 else if (str == "color burn") str = "burn"; 24923 else if (str == "softlight") str = "soft"; 24924 else if (str == "hardlight") str = "hard"; 24925 else if (str == "Math Add") str = "+"; 24926 else if (str == "Math Subtract") str = "-"; 24927 else if (str == "Math Multiply") str = "*"; 24928 else if (str == "Math Divide") str = "/"; 24929 24930 op.setUiAttrib({ "extendTitle": str }); 24931 }; 24932 op.setPortGroup("Blending", [blendPort, amountPort, alphaMaskPort]); 24933 24934 let maskAlpha = false; 24935 24936 blendPort.onChange = onChange; 24937 if (alphaMaskPort) 24938 { 24939 alphaMaskPort.onChange = onChange; 24940 maskAlpha = alphaMaskPort.get() == "On"; 24941 } 24942 24943 TextureEffect.onChangeBlendSelect(shader, blendPort.get(), maskAlpha); 24944}; 24945 24946 24947/***/ }), 24948
24949/***/ "./src/corelibs/cgl/constants.js": 24950/*!***************************************!*\ 24951 !*** ./src/corelibs/cgl/constants.js ***! 24952 \***************************************/ 24953/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 24954 24955"use strict"; 24956/* harmony export */ __webpack_require__.d(__webpack_exports__, { 24957/* harmony export */ CONSTANTS: () => (/* binding */ CONSTANTS), 24958/* harmony export */ nl: () => (/* binding */ nl) 24959/* harmony export */ }); 24960const SHADER = { 24961 // default attributes 24962 "SHADERVAR_VERTEX_POSITION": "vPosition", 24963 "SHADERVAR_VERTEX_NUMBER": "attrVertIndex", 24964 "SHADERVAR_VERTEX_NORMAL": "attrVertNormal", 24965 "SHADERVAR_VERTEX_TEXCOORD": "attrTexCoord", 24966 "SHADERVAR_INSTANCE_MMATRIX": "instMat", 24967 "SHADERVAR_VERTEX_COLOR": "attrVertColor", 24968 24969 "SHADERVAR_INSTANCE_INDEX": "instanceIndex", 24970 24971 // default uniforms 24972 "SHADERVAR_UNI_PROJMAT": "projMatrix", 24973 "SHADERVAR_UNI_VIEWMAT": "viewMatrix", 24974 "SHADERVAR_UNI_MODELMAT": "modelMatrix", 24975 "SHADERVAR_UNI_NORMALMAT": "normalMatrix", 24976 "SHADERVAR_UNI_INVVIEWMAT": "inverseViewMatrix", 24977 "SHADERVAR_UNI_INVPROJMAT": "invProjMatrix", 24978 "SHADERVAR_UNI_MATERIALID": "materialId", 24979 "SHADERVAR_UNI_OBJECTID": "objectId", 24980 24981 "SHADERVAR_UNI_VIEWPOS": "camPos", 24982}; 24983 24984const BLEND_MODES = { 24985 "BLEND_NONE": 0, 24986 "BLEND_NORMAL": 1, 24987 "BLEND_ADD": 2, 24988 "BLEND_SUB": 3, 24989 "BLEND_MUL": 4, 24990}; 24991 24992const RAD2DEG = 180.0 / Math.PI; 24993const DEG2RAD = Math.PI / 180.0; 24994 24995const CONSTANTS = { 24996 "MATH": { 24997 "DEG2RAD": DEG2RAD, 24998 "RAD2DEG": RAD2DEG, 24999 }, 25000 "SHADER": SHADER, 25001 "BLEND_MODES": BLEND_MODES, 25002}; 25003const nl = "\n";// newline 25004 25005 25006 25007/***/ }), 25008
25009/***/ "./src/corelibs/cgl/index.js": 25010/*!***********************************************!*\ 25011 !*** ./src/corelibs/cgl/index.js + 4 modules ***! 25012 \***********************************************/ 25013/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 25014 25015"use strict"; 25016 25017// EXPORTS 25018__webpack_require__.d(__webpack_exports__, { 25019 CGL: () => (/* binding */ cgl_CGL) 25020}); 25021 25022// UNUSED EXPORTS: Framebuffer2, Geometry, Mesh, Shader, Texture, Uniform 25023 25024// EXTERNAL MODULE: ./src/core/anim.js 25025var anim = __webpack_require__("./src/core/anim.js"); 25026// EXTERNAL MODULE: ../shared/client/src/logger.js 25027var logger = __webpack_require__("../shared/client/src/logger.js"); 25028// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_texture.js 25029var cgl_texture = __webpack_require__("./src/corelibs/cgl/cgl_texture.js"); 25030;// CONCATENATED MODULE: ./src/corelibs/cgl/cgl_framebuffer2.js 25031 25032 25033 25034 25035class Framebuffer2 25036{ 25037 25038 /** 25039 * @param {CglContext} cgl 25040 * @param {number} w 25041 * @param {number} h 25042 * @param {object} options 25043 */ 25044 constructor(cgl, w, h, options) 25045 { 25046 this._log = new logger["default"]("cgl_framebuffer2"); 25047 if (cgl.glVersion == 1) this._log.error("framebuffer2 used on webgl1"); 25048 this.Framebuffer2DrawTargetsDefault = null; 25049 this.Framebuffer2BlittingFramebuffer = null; 25050 this.Framebuffer2FinalFramebuffer = null; 25051 this._cgl = cgl; 25052 25053 this._cgl.printError("before framebuffer2 constructor"); 25054 25055 this._width = 0; 25056 this._height = 0; 25057 this.valid = true; 25058 25059 this._depthRenderbuffer = null; 25060 this._frameBuffer = null; 25061 this._textureFrameBuffer = null; 25062 this._colorRenderbuffers = []; 25063 this._drawTargetArray = []; 25064 this._disposed = false; 25065 25066 if (!this.Framebuffer2BlittingFramebuffer) this.Framebuffer2BlittingFramebuffer = cgl.gl.createFramebuffer(); 25067 if (!this.Framebuffer2FinalFramebuffer) this.Framebuffer2FinalFramebuffer = cgl.gl.createFramebuffer(); 25068 25069 if (!this.Framebuffer2DrawTargetsDefault) this.Framebuffer2DrawTargetsDefault = [cgl.gl.COLOR_ATTACHMENT0]; 25070 25071 this._options = options || { 25072 "isFloatingPointTexture": false, 25073 }; 25074 25075 this.name = this._options.name || "unknown"; 25076 25077 this._cgl.profileData.addHeavyEvent("framebuffer create", this.name); 25078 25079 if (!this._options.hasOwnProperty("numRenderBuffers")) this._options.numRenderBuffers = 1; 25080 if (!this._options.hasOwnProperty("depth")) this._options.depth = true; 25081 if (!this._options.hasOwnProperty("clear")) this._options.clear = true; 25082 if (!this._options.hasOwnProperty("multisampling")) 25083 { 25084 this._options.multisampling = false; 25085 this._options.multisamplingSamples = 0; 25086 } 25087 25088 if (this._options.multisamplingSamples) 25089 { 25090 if (this._cgl.glSlowRenderer) this._options.multisamplingSamples = 0; 25091 if (!this._cgl.gl.MAX_SAMPLES) this._options.multisamplingSamples = 0; 25092 else this._options.multisamplingSamples = Math.min(this._cgl.maxSamples, this._options.multisamplingSamples); 25093 } 25094 25095 if (!this._options.hasOwnProperty("filter")) this._options.filter = cgl_texture.Texture.FILTER_LINEAR; 25096 if (!this._options.hasOwnProperty("wrap")) this._options.wrap = cgl_texture.Texture.WRAP_REPEAT; 25097 25098 this._numRenderBuffers = this._options.numRenderBuffers; 25099 this._colorTextures = []; 25100 25101 this.clearColors = []; 25102 for (let i = 0; i < this._numRenderBuffers; i++) this.clearColors.push([0, 0, 0, 1]); 25103 25104 if (!options.pixelFormat) 25105 { 25106 if (options.isFloatingPointTexture) this._options.pixelFormat = cgl_texture.Texture.PFORMATSTR_RGBA32F; 25107 else this._options.pixelFormat = cgl_texture.Texture.PFORMATSTR_RGBA8UB; 25108 } 25109 25110 for (let i = 0; i < this._numRenderBuffers; i++) 25111 { 25112 this._colorTextures[i] = new cgl_texture.Texture(cgl, { 25113 "name": "fb2 " + this.name + " " + i, 25114 "isFloatingPointTexture": this._options.isFloatingPointTexture, 25115 "anisotropic": this._options.anisotropic || 0, 25116 "pixelFormat": this._options.pixelFormat, 25117 "filter": this._options.filter, 25118 "wrap": this._options.wrap, 25119 }); 25120 } 25121 25122 let fil = cgl_texture.Texture.FILTER_NEAREST; 25123 if (this._options.shadowMap) fil = cgl_texture.Texture.FILTER_LINEAR; 25124 25125 const defaultTexSize = 512; 25126 25127 if (this._options.depth) 25128 { 25129 this._textureDepth = new cgl_texture.Texture(cgl, 25130 { 25131 "name": "fb2 depth " + this.name, 25132 "isDepthTexture": true, 25133 "filter": fil, 25134 "shadowMap": this._options.shadowMap || false, 25135 "width": w || defaultTexSize, 25136 "height": h || defaultTexSize, 25137 }); 25138 } 25139 25140 if (cgl.aborted) return; 25141 25142 this.setSize(w || defaultTexSize, h || defaultTexSize); 25143 25144 this._cgl.printError("framebuffer2 constructor"); 25145 } 25146 25147 getWidth() 25148 { 25149 return this._width; 25150 } 25151 25152 getHeight() 25153 { 25154 return this._height; 25155 } 25156 25157 getGlFrameBuffer() 25158 { 25159 return this._frameBuffer; 25160 } 25161 25162 getDepthRenderBuffer() 25163 { 25164 return this._depthRenderbuffer; 25165 } 25166 25167 getTextureColor() 25168 { 25169 return this._colorTextures[0]; 25170 } 25171 25172 getTextureColorNum(i) 25173 { 25174 return this._colorTextures[i]; 25175 } 25176 25177 getTextureDepth() 25178 { 25179 return this._textureDepth; 25180 } 25181 25182 setFilter(f) 25183 { 25184 for (let i = 0;
25184 i < this._numRenderBuffers; i++) 25185 { 25186 this._colorTextures[i].filter = f; 25187 this._colorTextures[i].setSize(this._width, this._height); 25188 } 25189 } 25190 25191 delete() 25192 { 25193 this.dispose(); 25194 } 25195 25196 dispose() 25197 { 25198 this._disposed = true; 25199 let i = 0; 25200 for (i = 0; i < this._numRenderBuffers; i++) this._colorTextures[i].delete(); 25201 // this._texture.delete(); 25202 if (this._textureDepth) this._textureDepth.delete(); 25203 for (i = 0; i < this._numRenderBuffers; i++) this._cgl.gl.deleteRenderbuffer(this._colorRenderbuffers[i]); 25204 this._cgl.gl.deleteRenderbuffer(this._depthRenderbuffer); 25205 this._cgl.gl.deleteFramebuffer(this._frameBuffer); 25206 this._cgl.gl.deleteFramebuffer(this._textureFrameBuffer); 25207 } 25208 25209 /** 25210 * @param {number} w 25211 * @param {number} h 25212 */ 25213 setSize(w, h) 25214 { 25215 if (this._disposed) return this._log.warn("disposed framebuffer setsize..."); 25216 this._cgl.profileData.addHeavyEvent("framebuffer resize", this.name); 25217 25218 let i = 0; 25219 25220 this._width = this._cgl.checkTextureSize(w); 25221 this._height = this._cgl.checkTextureSize(h); 25222 25223 this._cgl.profileData.profileFrameBuffercreate++; 25224 25225 if (this._frameBuffer) 25226 { 25227 for (i = 0; i < this._numRenderBuffers; i++) this._cgl.gl.deleteRenderbuffer(this._colorRenderbuffers[i]); 25228 // this._cgl.gl.deleteRenderbuffer(this._colorRenderbuffer); 25229 this._cgl.gl.deleteRenderbuffer(this._depthRenderbuffer); 25230 this._cgl.gl.deleteFramebuffer(this._frameBuffer); 25231 this._cgl.gl.deleteFramebuffer(this._textureFrameBuffer); 25232 } 25233 25234 this._frameBuffer = this._cgl.gl.createFramebuffer(); 25235 this._textureFrameBuffer = this._cgl.gl.createFramebuffer(); 25236 25237 const depth = this._options.depth; 25238 25239 for (i = 0; i < this._numRenderBuffers; i++) 25240 { 25241 this._colorTextures[i].setSize(this._width, this._height); 25242 } 25243 25244 for (i = 0; i < this._numRenderBuffers; i++) 25245 { 25246 const renderBuffer = this._cgl.gl.createRenderbuffer(); 25247 25248 // color renderbuffer 25249 25250 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._frameBuffer); 25251 this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER, renderBuffer); 25252 25253 const info = cgl_texture.Texture.setUpGlPixelFormat(this._cgl, this._options.pixelFormat); 25254 let internFormat = info.glInternalFormat; 25255 25256 // if (this._options.isFloatingPointTexture) 25257 // { 25258 if (CGL.Texture.isPixelFormatHalfFloat(info.pixelFormat)) 25259 { 25260 if (!this._cgl.enableExtension("OES_texture_float_linear")) 25261 { 25262 this._options.filter = cgl_texture.Texture.FILTER_NEAREST; 25263 this.setFilter(this._options.filter); 25264 } 25265 } 25266 else if (CGL.Texture.isPixelFormatFloat(info.pixelFormat)) 25267 { 25268 if (!this._cgl.enableExtension("OES_texture_float_linear")) 25269 { 25270 this._log.warn("no linear pixelformat,using nearest"); 25271 this._options.filter = cgl_texture.Texture.FILTER_NEAREST; 25272 this.setFilter(this._options.filter); 25273 } 25274 } 25275 // else if (info.pixelFormat == Texture.PFORMATSTR_RGBA32F || info.pixelFormat == Texture.PFORMATSTR_R11FG11FB10F 25276 // else if (info.pixelFormat == Texture.PFORMATSTR_RGBA32F || info.pixelFormat == Texture.PFORMATSTR_R11FG11FB10F 25277 // else if (info.pixelFormat == Texture.PFORMATSTR_RG16F) 25278 // { 25279 // const extcb = this._cgl.enableExtension("EXT_color_buffer_float"); 25280 25281 // if (!this._cgl.enableExtension("OES_texture_float_linear")) 25282 // { 25283 // console.log("no linear pixelformat,switching to nearest"); 25284 // this._options.filter = Texture.FILTER_NEAREST; 25285 // this.setFilter(this._options.filter); 25286 // } 25287 // } 25288 // } 25289 25290 if (this._options.multisampling && this._options.multisamplingSamples) 25291 { 25292 this._cgl.gl.renderbufferStorageMultisample(this._cgl.gl.RENDERBUFFER, this._options.multisamplingSamples, internFormat, this._width, this._height); 25293 } 25294 else 25295 { 25296 this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER, internFormat, this._width, this._height); 25297 } 25298 25299 this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.COLOR_ATTACHMENT0 + i, this._cgl.gl.RENDERBUFFER, renderBuffer);
25300 this._colorRenderbuffers[i] = renderBuffer; 25301 } 25302 25303 // this._cgl.gl.bindFramebuffer(this._cgl.gl.DRAW_FRAMEBUFFER, this._textureFrameBuffer); 25304 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._textureFrameBuffer); 25305 25306 for (i = 0; i < this._numRenderBuffers; i++) 25307 { 25308 this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.COLOR_ATTACHMENT0 + i, this._cgl.gl.TEXTURE_2D, this._colorTextures[i].tex, 0); 25309 } 25310 25311 if (this._options.depth) 25312 { 25313 this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.DEPTH_ATTACHMENT, this._cgl.gl.TEXTURE_2D, this._textureDepth.tex, 0); 25314 } 25315 25316 // depth renderbuffer 25317 25318 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._frameBuffer); 25319 25320 let depthType = this._cgl.gl.DEPTH_COMPONENT32F; 25321 25322 if (this._cgl.glSlowRenderer) depthType = this._cgl.gl.DEPTH_COMPONENT16; 25323 if (depth) 25324 { 25325 this._textureDepth.setSize(this._width, this._height); 25326 this._depthRenderbuffer = this._cgl.gl.createRenderbuffer(); 25327 25328 this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER, this._depthRenderbuffer); 25329 if (this._options.isFloatingPointTexture) 25330 { 25331 if (this._options.multisampling) this._cgl.gl.renderbufferStorageMultisample(this._cgl.gl.RENDERBUFFER, this._options.multisamplingSamples, depthType, this._width, this._height); 25332 else this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER, depthType, this._width, this._height); 25333 } 25334 else if (this._options.multisampling) 25335 { 25336 this._cgl.gl.renderbufferStorageMultisample(this._cgl.gl.RENDERBUFFER, this._options.multisamplingSamples, depthType, this._width, this._height); 25337 // this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER,depthType, this._width, this._height); 25338 } 25339 else 25340 { 25341 this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER, depthType, this._width, this._height); 25342 } 25343 25344 this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.DEPTH_ATTACHMENT, this._cgl.gl.RENDERBUFFER, this._depthRenderbuffer); 25345 } 25346 25347 // this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, null); 25348 // this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._textureFrameBuffer); 25349 25350 this._drawTargetArray.length = 0; 25351 for (i = 0; i < this._numRenderBuffers; i++) this._drawTargetArray.push(this._cgl.gl.COLOR_ATTACHMENT0 + i); 25352 25353 // this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, null); 25354 25355 if (!this._cgl.gl.isFramebuffer(this._textureFrameBuffer)) this._log.warn("invalid framebuffer");// throw new Error("Invalid framebuffer"); 25356 const status = this._cgl.gl.checkFramebufferStatus(this._cgl.gl.FRAMEBUFFER); 25357 25358 if (status != this._cgl.gl.FRAMEBUFFER_COMPLETE) 25359 { 25360 this._log.error("framebuffer incomplete: " + this.name, this); 25361 this._log.log("options", this._options); 25362 this._log.log("options pixelformat", this._options.pixelFormat); 25363 25364 switch (status) 25365 { 25366 case this._cgl.gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: 25367 this._log.warn("FRAMEBUFFER_INCOMPLETE_ATTACHMENT...", this); 25368 throw new Error("Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); 25369 case this._cgl.gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: 25370 this._log.warn("FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); 25371 throw new Error("Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); 25372 case this._cgl.gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: 25373 this._log.warn("FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); 25374 throw new Error("Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); 25375 case this._cgl.gl.FRAMEBUFFER_UNSUPPORTED: 25376 this._log.warn("FRAMEBUFFER_UNSUPPORTED"); 25377 throw new Error("Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED"); 25378 default: 25379 this.valid = false;
25380 this._log.error("incomplete framebuffer", status, this._frameBuffer); 25381 this._cgl.printError(); 25382 25383 this._frameBuffer = null; 25384 // debugger; 25385 throw new Error("Incomplete framebuffer: " + status); 25386 25387 // throw("Incomplete framebuffer: " + status); 25388 } 25389 } 25390 25391 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, null); 25392 this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER, null); 25393 25394 // this._cgl.printError("fb setsize"); 25395 } 25396 25397 renderStart() 25398 { 25399 if (this._disposed) return this._log.warn("disposed framebuffer renderStart..."); 25400 this._cgl.checkFrameStarted("fb2 renderstart"); 25401 this._cgl.pushModelMatrix(); // needed ?? 25402 25403 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._frameBuffer); 25404 this._cgl.pushGlFrameBuffer(this._frameBuffer); 25405 this._cgl.pushFrameBuffer(this); 25406 25407 this._cgl.pushPMatrix(); 25408 this._cgl.pushViewPort(0, 0, this._width, this._height); 25409 25410 this._cgl.gl.drawBuffers(this._drawTargetArray); 25411 25412 if (this._options.clear) 25413 { 25414 this._cgl.gl.clearColor(0, 0, 0, 0); 25415 this._cgl.gl.clear(this._cgl.gl.COLOR_BUFFER_BIT | this._cgl.gl.DEPTH_BUFFER_BIT); 25416 } 25417 } 25418 25419 clear() 25420 { 25421 if (this._numRenderBuffers <= 1) 25422 { 25423 this._cgl.gl.bindFramebuffer(this._cgl.gl.READ_FRAMEBUFFER, this._frameBuffer); 25424 this._cgl.gl.bindFramebuffer(this._cgl.gl.DRAW_FRAMEBUFFER, this._textureFrameBuffer); 25425 } 25426 else this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._frameBuffer); 25427 25428 this._cgl.gl.drawBuffers(this._drawTargetArray); 25429 25430 for (let i = 0; i < this._numRenderBuffers; i++) 25431 { 25432 this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.COLOR_ATTACHMENT0 + i, this._cgl.gl.TEXTURE_2D, this._colorTextures[i].tex, 0); 25433 this._cgl.gl.clearBufferfv(this._cgl.gl.COLOR, i, this.clearColors[i]); 25434 } 25435 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, null); 25436 } 25437 25438 renderEnd() 25439 { 25440 if (this._disposed) return this._log.warn("disposed framebuffer renderEnd..."); 25441 this._cgl.popPMatrix(); 25442 25443 this._cgl.profileData.profileFramebuffer++; 25444 25445 if (this._numRenderBuffers <= 1) 25446 { 25447 this._cgl.gl.bindFramebuffer(this._cgl.gl.READ_FRAMEBUFFER, this._frameBuffer); 25448 this._cgl.gl.bindFramebuffer(this._cgl.gl.DRAW_FRAMEBUFFER, this._textureFrameBuffer); 25449 25450 this._cgl.gl.clearBufferfv(this._cgl.gl.COLOR, 0, [0.0, 0.0, 0.0, 1.0]); 25451 this._cgl.gl.blitFramebuffer(0, 0, this._width, this._height, 0, 0, this._width, this._height, this._cgl.gl.COLOR_BUFFER_BIT | this._cgl.gl.DEPTH_BUFFER_BIT, this._cgl.gl.NEAREST); 25452 } 25453 else 25454 { 25455 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this.Framebuffer2BlittingFramebuffer); 25456 this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.DEPTH_ATTACHMENT, this._cgl.gl.RENDERBUFFER, this._depthRenderbuffer); 25457 25458 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this.Framebuffer2FinalFramebuffer); 25459 this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.DEPTH_ATTACHMENT, this._cgl.gl.TEXTURE_2D, this._textureDepth.tex, 0); 25460 25461 for (let i = 0; i < this._numRenderBuffers; i++) 25462 { 25463 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this.Framebuffer2BlittingFramebuffer); 25464 this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.COLOR_ATTACHMENT0, this._cgl.gl.RENDERBUFFER, this._colorRenderbuffers[i]); 25465 25466 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this.Framebuffer2FinalFramebuffer); 25467 this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER, this._cgl.gl.COLOR_ATTACHMENT0, this._cgl.gl.TEXTURE_2D, this._colorTextures[i].tex, 0); 25468 25469 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, null); 25470 25471 this._cgl.gl.bindFramebuffer(this._cgl.gl.READ_FRAMEBUFFER, this.Framebuffer2BlittingFramebuffer); 25472 this._cgl.gl.bindFramebuffer(this._cgl.gl.DRAW_FRAMEBUFFER, this.Framebuffer2FinalFramebuffer); 25473
25474 // this._cgl.gl.clearBufferfv(this._cgl.gl.COLOR, i, [0.0, 0.0, 0.0, 1.0]); 25475 25476 let flags = this._cgl.gl.COLOR_BUFFER_BIT; 25477 if (i == 0) flags |= this._cgl.gl.DEPTH_BUFFER_BIT; 25478 25479 this._cgl.gl.blitFramebuffer(0, 0, this._width, this._height, 0, 0, this._width, this._height, flags, this._cgl.gl.NEAREST); 25480 } 25481 } 25482 25483 this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER, this._cgl.popGlFrameBuffer()); 25484 this._cgl.popFrameBuffer(); 25485 25486 this._cgl.popModelMatrix(); 25487 this._cgl.popViewPort(); 25488 25489 if (this._colorTextures[0].filter == cgl_texture.Texture.FILTER_MIPMAP) 25490 { 25491 for (let i = 0; i < this._numRenderBuffers; i++) 25492 { 25493 this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D, this._colorTextures[i].tex); 25494 this._colorTextures[i].updateMipMap(); 25495 this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D, null); 25496 } 25497 } 25498 } 25499} 25500 25501;// CONCATENATED MODULE: ./src/corelibs/cgl/cgl_marker.js 25502/** @type {function} 25503 * @deprecated 25504*/ 25505const Marker = function (_cgl) // deprecated... 25506{ 25507 this.draw = function (cgl, _size, depthTest) {}; 25508}; 25509 25510/** @type {function} 25511 * @deprecated 25512*/ 25513const WirePoint = function (cgl) // deprecated... 25514{ 25515 this.render = function (_cgl, _size) {}; 25516}; 25517 25518/** @type {function} 25519 * @deprecated 25520*/ 25521const WireCube = function (cgl) // deprecated... 25522{ 25523 this.render = function (_cgl, sizeX, sizeY, sizeZ) {}; 25524}; 25525 25526// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_mesh.js 25527var cgl_mesh = __webpack_require__("./src/corelibs/cgl/cgl_mesh.js"); 25528// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_shader_uniform.js 25529var cgl_shader_uniform = __webpack_require__("./src/corelibs/cgl/cgl_shader_uniform.js"); 25530// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_shader_lib.js 25531var cgl_shader_lib = __webpack_require__("./src/corelibs/cgl/cgl_shader_lib.js"); 25532;// CONCATENATED MODULE: ./src/corelibs/cgl/cgl_unicolorshader.js 25533 25534 25535class UniColorShader 25536{ 25537 constructor(_cgl) 25538 { 25539 this.shader = new CGL.Shader(_cgl, "markermaterial"); 25540 25541 const frag = "" 25542 .endl() + "void main()" 25543 .endl() + "{" 25544 .endl() + " outColor = vec4(color.rgb,1.0);" 25545 .endl() + "}"; 25546 25547 const vert = "" 25548 .endl() + "IN vec3 vPosition;" 25549 .endl() + "UNI mat4 projMatrix;" 25550 .endl() + "UNI mat4 mvMatrix;" 25551 25552 .endl() + "void main()" 25553 .endl() + "{" 25554 .endl() + " gl_Position = projMatrix * mvMatrix * vec4(vPosition,1.0);" 25555 .endl() + "}"; 25556 25557 this.shader.setSource(vert, frag); 25558 this.coloruni = this.shader.addUniformFrag("4f", "color", [1, 0.777, 1, 1]); 25559 } 25560 25561 setColor(r, g, b, a) 25562 { 25563 this.coloruni.set(r, g, b, a); 25564 } 25565} 25566 25567// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_shader.js 25568var cgl_shader = __webpack_require__("./src/corelibs/cgl/cgl_shader.js"); 25569// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_simplerect.js 25570var cgl_simplerect = __webpack_require__("./src/corelibs/cgl/cgl_simplerect.js"); 25571;// CONCATENATED MODULE: ./src/corelibs/cgl/cgl_utils.js 25572/** 25573 * @namespace CGL 25574 */ 25575 25576/** 25577 * multiply to get radians from degree, e.g. `360 * CGL.DEG2RAD` 25578 * @const {Number} 25579 * @memberof CGL 25580 * @static 25581 */ 25582const DEG2RAD = Math.PI / 180.0; 25583 25584/** 25585 * to get degrees from radians, e.g. `3.14 * CGL.RAD2DEG` 25586 * @const {number} 25587 * @memberof CGL 25588 */ 25589const RAD2DEG = 180.0 / Math.PI; 25590 25591const onLoadingAssetsFinished = null; // deprecated / remove later 25592 25593/** 25594 * get normalized mouse wheel delta (including browser specific adjustment) 25595 * @function getWheelDelta 25596 * @static 25597 * @memberof CGL 25598 * @param {MouseEvent} event 25599 * @return {Number} normalized delta 25600 */ 25601const isWindows = window.navigator.userAgent.includes("Windows"); 25602const getWheelDelta_ = function (event) 25603{ 25604 let normalized; 25605 if (event.wheelDelta) 25606 { 25607 // chrome 25608 normalized = (event.wheelDelta % 120) - 0 == -0 ? event.wheelDelta / 120 : event.wheelDelta / 30; 25609 normalized *= -1.5; 25610 if (isWindows) normalized *= 2; 25611 } 25612 else 25613 { 25614 // firefox 25615 let d = event.deltaY; 25616 if (event.shiftKey) d = event.deltaX; 25617 const rawAmmount = d || event.detail; 25618 normalized = -(rawAmmount % 3 ? rawAmmount * 10 : rawAmmount / 3); 25619 normalized *= -3; 25620 } 25621 25622 if (normalized > 20) normalized = 20; 25623 if (normalized < -20) normalized = -20; 25624 25625 return normalized; 25626}; 25627 25628const getWheelSpeed = getWheelDelta_; 25629const getWheelDelta = getWheelDelta_; 25630 25631// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_textureeffect.js 25632var cgl_textureeffect = __webpack_require__("./src/corelibs/cgl/cgl_textureeffect.js"); 25633// EXTERNAL MODULE: ./src/corelibs/cgl/constants.js 25634var constants = __webpack_require__("./src/corelibs/cgl/constants.js"); 25635// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_profiledata.js 25636var cgl_profiledata = __webpack_require__("./src/corelibs/cgl/cgl_profiledata.js"); 25637// EXTERNAL MODULE: ./src/corelibs/cg/cg_geom.js 25638var cg_geom = __webpack_require__("./src/corelibs/cg/cg_geom.js"); 25639// EXTERNAL MODULE: ./src/corelibs/cg/cg_boundingbox.js 25640var cg_boundingbox = __webpack_require__("./src/corelibs/cg/cg_boundingbox.js"); 25641// EXTERNAL MODULE: ./src/corelibs/cg/cg_matrixstack.js 25642var cg_matrixstack = __webpack_require__("./src/corelibs/cg/cg_matrixstack.js"); 25643// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_state.js 25644var cgl_state = __webpack_require__("./src/corelibs/cgl/cgl_state.js"); 25645;// CONCATENATED MODULE: ./src/corelibs/cgl/index.js 25646 25647 25648 25649 25650 25651 25652 25653 25654 25655 25656 25657 25658 25659 25660 25661 25662 25663const cgl_CGL = { 25664 "Framebuffer2": Framebuffer2, 25665 "Geometry": cg_geom.Geometry, 25666 "BoundingBox": cg_boundingbox.BoundingBox, 25667 "Marker": Marker, 25668 "WirePoint": WirePoint, 25669 "WireCube": WireCube, 25670 "MatrixStack": cg_matrixstack.MatrixStack, 25671 "Mesh": cgl_mesh.Mesh, 25672 "MESH": cgl_mesh.MESH, 25673 "ShaderLibMods": cgl_shader_lib.ShaderLibMods, 25674 "Shader": cgl_shader.Shader, 25675 "Uniform": cgl_shader_uniform.Uniform, 25676 "MESHES": cgl_simplerect.MESHES, 25677 "getWheelSpeed": getWheelSpeed, 25678 "getWheelDelta": getWheelDelta, 25679 "Context": cgl_state.CglContext, 25680 "Texture": cgl_texture.Texture, 25681 "TextureEffect": cgl_textureeffect.TextureEffect, 25682 "onLoadingAssetsFinished": onLoadingAssetsFinished, 25683 "ProfileData": cgl_profiledata.ProfileData, 25684 "UniColorShader": UniColorShader, 25685 ...constants.CONSTANTS.BLEND_MODES, 25686 ...constants.CONSTANTS.SHADER, 25687 ...constants.CONSTANTS.MATH, 25688 ...constants.CONSTANTS.BLEND_MODES, 25689}; 25690 25691window.CABLES = window.CABLES || {}; 25692window.CABLES.CGL = window.CABLES.CGL || cgl_CGL; 25693window.CGL = window.CGL || cgl_CGL; 25694 25695/** 25696 * @param {number} time 25697 * @param {quat} q 25698 * @param {Anim} animx 25699 * @param {Anim} animy 25700 * @param {Anim} animz 25701 * @param {Anim} animw 25702 */ 25703anim.Anim.slerpQuaternion = function (time, q, animx, animy, animz, animw) 25704{ 25705 if (!anim.Anim.slerpQuaternion.q1) 25706 { 25707 anim.Anim.slerpQuaternion.q1 = quat.create(); 25708 anim.Anim.slerpQuaternion.q2 = quat.create(); 25709 } 25710 25711 const i1 = animx.getKeyIndex(time); 25712 let i2 = i1 + 1; 25713 if (i2 >= animx.keys.length) i2 = animx.keys.length - 1; 25714 25715 if (i1 == i2) 25716 { 25717 quat.set(q, animx.keys[i1].value, animy.keys[i1].value, animz.keys[i1].value, animw.keys[i1].value); 25718 } 25719 else 25720 {
25721 const key1Time = animx.keys[i1].time; 25722 const key2Time = animx.keys[i2].time; 25723 const perc = (time - key1Time) / (key2Time - key1Time); 25724 25725 quat.set(anim.Anim.slerpQuaternion.q1, animx.keys[i1].value, animy.keys[i1].value, animz.keys[i1].value, animw.keys[i1].value); 25726 25727 quat.set(anim.Anim.slerpQuaternion.q2, animx.keys[i2].value, animy.keys[i2].value, animz.keys[i2].value, animw.keys[i2].value); 25728 25729 quat.slerp(q, anim.Anim.slerpQuaternion.q1, anim.Anim.slerpQuaternion.q2, perc); 25730 } 25731 return q; 25732}; 25733 25734 25735 25736 25737/***/ }), 25738
25739/***/ "./src/corelibs/cgp/index.js": 25740/*!************************************************!*\ 25741 !*** ./src/corelibs/cgp/index.js + 18 modules ***! 25742 \************************************************/ 25743/***/ ((__unused_webpack___webpack_module__, __unused_webpack___webpack_exports__, __webpack_require__) => { 25744 25745"use strict"; 25746 25747// UNUSED EXPORTS: CGP 25748 25749// EXTERNAL MODULE: ../shared/client/src/logger.js 25750var logger = __webpack_require__("../shared/client/src/logger.js"); 25751// EXTERNAL MODULE: ./src/corelibs/cg/cg_context.js 25752var cg_context = __webpack_require__("./src/corelibs/cg/cg_context.js"); 25753// EXTERNAL MODULE: ./src/corelibs/cg/cg_texture.js 25754var cg_texture = __webpack_require__("./src/corelibs/cg/cg_texture.js"); 25755// EXTERNAL MODULE: ./node_modules/gl-matrix/esm/mat4.js 25756var mat4 = __webpack_require__("./node_modules/gl-matrix/esm/mat4.js"); 25757// EXTERNAL MODULE: ./src/core/timer.js 25758var timer = __webpack_require__("./src/core/timer.js"); 25759// EXTERNAL MODULE: ./src/corelibs/cg/cg_uniform.js 25760var cg_uniform = __webpack_require__("./src/corelibs/cg/cg_uniform.js"); 25761;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_uniform.js 25762 25763 25764 25765 25766class CgpUniform extends cg_uniform.CgUniform 25767{ 25768 25769 /** @type {CgpContext} */ 25770 #cgp = null; 25771 25772 /** @type {GPUBuffer} */ 25773 gpuBuffer = null; 25774 25775 gpuBufferChanged = false; 25776 25777 /** 25778 * Description 25779 * @param {CgpShader} __shader 25780 * @param {string} __type 25781 * @param {string} __name 25782 * @param {any} _value 25783 * @param {any} _port2 25784 * @param {any} _port3 25785 * @param {any} _port4 25786 */ 25787 constructor(__shader, __type, __name, _value, _port2, _port3, _port4) 25788 { 25789 super(__shader, __type, __name, _value, _port2, _port3, _port4); 25790 this.#cgp = __shader._cgp; 25791 25792 if (!_value || (_value.get && !_value.get())) 25793 { 25794 // if (this.getType() == "m4") this._value = mat4.create(); 25795 if (this.getType() == "t") 25796 { 25797 this._value = this.#cgp.getEmptyTexture(); 25798 } 25799 // else if (this.getType() == "2f") this._value = [0, 0]; 25800 // else if (this.getType() == "4f") this._value = [0, 1, 0, 1]; 25801 // else if (this.getType() == "3f") this._value = [0, 1, 0]; 25802 } 25803 25804 } 25805 25806 getInfo() 25807 { 25808 return { "name": this.name, "type": this.type, "value": this.getValue() }; 25809 } 25810 25811 updateValueF() { } 25812 25813 updateValueArrayF() {} 25814 25815 setValueArrayF(v) 25816 { 25817 this.needsUpdate = true; 25818 this._value = v; 25819 } 25820 25821 setValueF(v) 25822 { 25823 this.needsUpdate = true; 25824 this._value = v; 25825 } 25826 25827 updateValue2F() { } 25828 25829 setValue2F(v) 25830 { 25831 this.needsUpdate = true; 25832 this._value = v; 25833 } 25834 25835 updateValue3F() { } 25836 25837 setValue3F(v) 25838 { 25839 this.needsUpdate = true; 25840 this._value = v; 25841 } 25842 25843 updateValue4F() { } 25844 25845 setValue4F(v) 25846 { 25847 if (v[0] == undefined) 25848 { 25849 this._log.stack("uniform value undefined"); 25850 console.error("uniform value undefined"); 25851 } 25852 this.needsUpdate = true; 25853 this._value = v; 25854 } 25855 25856 setValueT(v) 25857 { 25858 // if (this._value != v) 25859 // this._shader.needsPipelineUpdate = "texture changed"; // todo really needed ? change binding instead? 25860 25861 this.needsUpdate = true; 25862 this._value = v; 25863 } 25864 25865 updateValueM4(v) {} 25866 25867 setValueM4(v) 25868 { 25869 this.needsUpdate = true; 25870 this._value = v; 25871 } 25872 25873 setValueAny(v) 25874 { 25875 this.needsUpdate = true; 25876 this._value = v; 25877 } 25878 25879 updateValueAny() {} 25880 25881 updateValueT() {} 25882 25883 /** 25884 * @param {GPUBuffer} b 25885 */ 25886 setGpuBuffer(b) 25887 { 25888 this.gpuBufferChanged = true; 25889 this.gpuBuffer = b; 25890 } 25891 25892 copyToBuffer(buff, pos = 0) 25893 { 25894 if (this._type == "f") 25895 { 25896 buff[pos] = this._value; 25897 } 25898 else if (this._type == "t") 25899 { 25900 } 25901 else if (this._type == "4f") 25902 { 25903 buff[pos] = this._value[0]; 25904 buff[pos + 1] = this._value[1]; 25905 buff[pos + 2] = this._value[2]; 25906 buff[pos + 3] = this._value[3]; 25907 } 25908 else if (this._type == "2f") 25909 { 25910 buff[pos] = this._value[0]; 25911 buff[pos + 1] = this._value[1]; 25912 } 25913 else if (this._type == "3f") 25914 { 25915 buff[pos] = this._value[0]; 25916 buff[pos + 1] = this._value[1]; 25917 buff[pos + 2] = this._value[2]; 25918 } 25919 else if (this._type == "f[]") 25920 { 25921 for (let i = 0; i < this._value.length; i++) 25922 buff[pos + i] = this._value[i]; 25923 } 25924 else if (this._type == "m4") 25925 { 25926 for (let i = 0; i < 16; i++) 25927 buff[pos + i] = this._value[i]; 25928 } 25929 else 25930 { 25931 this._log.warn("uniform copy to buffer unknown", this._type); 25932 } 25933 } 25934 25935 getWgslTypeStr() 25936 { 25937 if (this._type == "m4") return "mat4x4f"; 25938 if (this._type == "4f") return "vec4f"; 25939 if (this._type == "3f") return "vec3f"; 25940 if (this._type == "2f") return "vec2f"; 25941 if (this._type == "f") return "f32"; 25942 if (this._type == "f[]") return "array<vec4f>"; 25943 if (this._type == "i") return "int"; 25944 if (this._type == "sampler") return "sampler"; 25945 if (this._type == "t") return "texture_2d<f32>"; 25946 this._log.warn("unknown type getWgslTypeStr", this._type); 25947 return "???"; 25948 } 25949 25950 getSizeBytes() 25951 { 25952 const bytesPerFloat = 4; 25953 const bytesPerInt = 4; 25954 if (this._type == "t") return 4; 25955 if (this._type == "sampler") return 4; 25956 if (this._type == "f") return 1 * bytesPerFloat; 25957 if (this._type == "2f") return 2 * bytesPerFloat; 25958 if (this._type == "3f") return 3 * bytesPerFloat; 25959 if (this._type == "4f") return 4 * bytesPerFloat; 25960 if (this._type == "f[]") return this._value.length * bytesPerFloat; 25961 if (this._type == "m4") return 4 * 4 * bytesPerFloat; 25962 if (this._type == "i") return 1 * bytesPerInt; 25963 if (this._type == "2i") return 2 * bytesPerInt; 25964
25965 this._log.warn("unknown type getSizeBytes", this._type); 25966 return 4; 25967 } 25968 25969 /** 25970 * @param {CgpShader} shader 25971 */ 25972 copy(shader) 25973 { 25974 const uni = new CgpUniform(shader, this._type, this._name, this._value, this._port2, this._port3, this._port4); 25975 uni.shaderType = this.shaderType; 25976 25977 // console.log(this._name, this._value, uni._value); 25978 25979 return uni; 25980 } 25981 25982} 25983 25984;// CONCATENATED MODULE: ./src/corelibs/cg/preproc.js 25985/** 25986 * @param {string} str 25987 * @param {object} vars 25988 */ 25989function preproc(str, vars) 25990{ 25991 if (!str) 25992 { 25993 console.warn("shader preproc no shader code given"); 25994 } 25995 str = str || ""; 25996 const lines = str.split("\n"); 25997 const outLines = []; 25998 let stack = []; 25999 26000 for (let i = 0; i < lines.length; i++) 26001 { 26002 let line = lines[i].trim(); 26003 let parts = line.split(" "); 26004 26005 if (line.startsWith("#ifdef ")) 26006 { 26007 const s = vars[parts[1]]; 26008 stack.push({ "state": s }); 26009 continue; 26010 } 26011 if (line.startsWith("#ifndef ")) 26012 { 26013 const s = vars[parts[1]]; 26014 stack.push({ "state": !s }); 26015 continue; 26016 } 26017 if (line.startsWith("#endif")) 26018 { 26019 stack.pop(); 26020 continue; 26021 } 26022 const state = stack[stack.length - 1]; 26023 26024 if (line.startsWith("#else")) 26025 { 26026 state.state = !state.state; 26027 continue; 26028 } 26029 26030 if (!state || state.state) 26031 { 26032 outLines.push(lines[i]); 26033 } 26034 } 26035 26036 return outLines.join("\n"); 26037} 26038 26039// EXTERNAL MODULE: ./src/corelibs/cg/cg_shader.js 26040var cg_shader = __webpack_require__("./src/corelibs/cg/cg_shader.js"); 26041;// CONCATENATED MODULE: ./src/corelibs/cgp/binding/bindgroup.js 26042 26043 26044 26045 26046class BindGroup 26047{ 26048 26049 /** @type {Array<GPUBindGroup>} */ 26050 #gpuBindGroups = []; 26051 26052 /** @type {Array<Binding>} */ 26053 #bindings = []; 26054 26055 name = ""; 26056 26057 needsPipelineUpdate = false; 26058 26059 bla = 1; 26060 26061 /** @type {CgpContext} */ 26062 #cgp; 26063 26064 /** 26065 * @param {CgpContext} cgp 26066 * @param {string} name 26067 */ 26068 constructor(cgp, name) 26069 { 26070 this.#cgp = cgp; 26071 this.name = name; 26072 } 26073 26074 /** 26075 * @returns {GPUBindGroup} 26076 */ 26077 // get gpuBindgroup() 26078 // { 26079 // if (!this.#gpuBindGroup) 26080 // { 26081 // this.create(); 26082 // } 26083 // // console.log(this.#gpuBindGroup); 26084 // return this.#gpuBindGroup; 26085 // } 26086 26087 /** 26088 * @param {Binding} b 26089 * @returns {boolean} 26090 */ 26091 hasBinding(b) 26092 { 26093 return this.#bindings.includes(b); 26094 } 26095 26096 /** 26097 * @param {string} n 26098 * @returns {Binding} 26099 */ 26100 getBindingByName(n) 26101 { 26102 26103 for (let i = 0; i < this.#bindings.length; i++) 26104 { 26105 if (this.#bindings[i].name == n) return this.#bindings[i]; 26106 } 26107 } 26108 26109 /** 26110 * @param {Binding} b 26111 */ 26112 removeBinding(b) 26113 { 26114 const idx = this.#bindings.indexOf(b); 26115 this.#bindings.splice(idx, 1); 26116 } 26117 26118 /** 26119 * @param {Binding} b 26120 * @returns {Binding} 26121 */ 26122 addBinding(b) 26123 { 26124 const oldBinding = this.getBindingByName(b.name); 26125 if (oldBinding) this.removeBinding(oldBinding); 26126 b.needsRebuildBindgroup = true; 26127 b.bindNum = this.#bindings.length; 26128 this.#bindings.push(b); 26129 26130 return b; 26131 } 26132 26133 // /** 26134 // * @param {CgpShader} shader 26135 // */ 26136 // bind(shader) 26137 // { 26138 // shader.setBindgroup(this); 26139 // } 26140 26141 /** 26142 * @param {CgpShader} [shader] 26143 */ 26144 getLayoutEntries(shader) 26145 { 26146 const arr = []; 26147 for (let i = 0; i < this.#bindings.length; i++) 26148 { 26149 arr.push(this.#bindings[i].getLayoutEntry(shader)); 26150 } 26151 26152 if (arr.length == 0) 26153 { 26154 // console.log("nooooooooooooooooooooooo"); 26155 } 26156 return arr; 26157 } 26158 26159 /** 26160 * @returns {Array<GPUBindGroupEntry>} 26161 * @param {number} inst 26162 */ 26163 getEntries(inst) 26164 { 26165 const arr = []; 26166 for (let i = 0; i < this.#bindings.length; i++) 26167 { 26168 arr.push(this.#bindings[i].getBindgroupEntry(inst)); 26169 } 26170 26171 if (arr.length == 0) 26172 { 26173 // console.log("nooooooooooooooooooooooo"); 26174 } 26175 return arr; 26176 } 26177 26178 /** 26179 * @param {CgpShader} [shader] 26180 */ 26181 getLayout(shader) 26182 { 26183 // console.log(this.getLayoutEntries(shader)); 26184 26185 /** @type {GPUBindGroupLayout} */ 26186 const bindGroupLayout = this.#cgp.device.createBindGroupLayout( 26187 { 26188 "label": "bindgrouplayout " + this.name, 26189 "entries": this.getLayoutEntries(shader), 26190 }); 26191 26192 return bindGroupLayout; 26193 } 26194 26195 /** 26196 * @param {number} inst 26197 */ 26198 create(inst) 26199 { 26200 26201 /** @type {GPUBindGroupDescriptor} */ 26202 const bg = { 26203 "label": " " + this.name + " i" + inst, 26204 "layout": this.getLayout(), 26205 "entries": this.getEntries(inst) 26206 }; 26207 26208 this.#cgp.profileData.count("bindgroup created", this.name); 26209 26210 // if (bindingGroupEntries.length != this.bindingGroupLayoutEntries.length) 26211 // { 26212 // this.#log.error("bindingGroupEntries.length!= this.bindingGroupLayoutEntries.length", bindingGroupEntries.length, this.bindingGroupLayoutEntries.length); 26213 // this.#rebuildNumBindingGroups = true; 26214 // this.#isValid = false;
26215 // return; 26216 // } 26217 26218 try 26219 { 26220 this.#gpuBindGroups[inst] = this.#cgp.device.createBindGroup(bg); 26221 this.needsRebuildBindgroup = true; 26222 26223 } 26224 catch (e) 26225 { 26226 console.log(bg); 26227 console.error(e); 26228 } 26229 26230 this.updateValues(inst); 26231 } 26232 26233 /** 26234 * @param {number} inst 26235 */ 26236 updateValues(inst) 26237 { 26238 for (let i = 0; i < this.#bindings.length; i++) 26239 { 26240 this.#bindings[i].updateValues(inst); 26241 } 26242 } 26243 26244 /** 26245 * @param {number} inst 26246 * @param {GPURenderPassEncoder|GPUComputePassEncoder} passEnc 26247 */ 26248 bind(inst = 0, passEnc = null, idx = 0) 26249 { 26250 for (let i = 0; i < this.#bindings.length; i++) 26251 if (this.#bindings[i].needsRebuildBindgroup) 26252 { 26253 // console.log("rebuild bg"); 26254 this.create(inst); 26255 this.#bindings[i].needsRebuildBindgroup = false; 26256 this.#gpuBindGroups = []; 26257 // todo: dispose 26258 } 26259 26260 if (!this.#gpuBindGroups[inst]) this.create(inst); 26261 (passEnc || this.#cgp.passEncoder).setBindGroup(idx, this.#gpuBindGroups[inst]); 26262 } 26263 26264 /** 26265 * @param {CgpShader} shader 26266 * @param {number} idx 26267 */ 26268 getShaderHeaderCode(shader, idx) 26269 { 26270 const srcs = { "vertex": "", "fragment": "", "compute": "" }; 26271 26272 this.#cgp.profileData.count("bindgroup shadercode", this.name); 26273 for (let i = 0; i < this.#bindings.length; i++) 26274 { 26275 const bind = this.#bindings[i]; 26276 let src = ""; 26277 src += bind.getShaderHeaderCode(shader, idx); 26278 if (bind.stage & GPUShaderStage.VERTEX)srcs.vertex += src; 26279 else if (bind.stage === GPUShaderStage.FRAGMENT)srcs.fragment += src; 26280 else if (bind.stage & GPUShaderStage.COMPUTE)srcs.compute += src; 26281 } 26282 26283 return srcs; 26284 } 26285 26286 /** 26287 * @param {CgpShader} shader 26288 */ 26289 copy(shader) 26290 { 26291 const newBg = new BindGroup(this.#cgp, this.name); 26292 for (let i = 0; i < this.#bindings.length; i++) 26293 { 26294 newBg.addBinding(this.#bindings[i].copy(shader)); 26295 } 26296 return newBg; 26297 } 26298 26299 setBindingNums() 26300 { 26301 26302 for (let i = 0; i < this.#bindings.length; i++) 26303 { 26304 this.#bindings[i].setBindNum(i); 26305 } 26306 } 26307 26308 getInfo() 26309 { 26310 const o = { "name": this.name, "bindings": [] }; 26311 for (let i = 0; i < this.#bindings.length; i++) 26312 { 26313 o.bindings.push(this.#bindings[i].getInfo()); 26314 } 26315 return o; 26316 } 26317} 26318 26319// EXTERNAL MODULE: ./src/core/utils.js + 1 modules 26320var utils = __webpack_require__("./src/core/utils.js"); 26321// EXTERNAL MODULE: ./src/corelibs/cgl/constants.js 26322var constants = __webpack_require__("./src/corelibs/cgl/constants.js"); 26323;// CONCATENATED MODULE: ./src/corelibs/cgp/binding/binding.js 26324 26325 26326 26327 26328 26329 26330class Binding 26331{ 26332 id = utils.simpleId(); 26333 name = ""; 26334 bindNum = 0; 26335 stage = GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT; 26336 define = ""; 26337 log = new logger["default"]("binding"); 26338 needsRebuildBindgroup = false; 26339 26340 /** @type {CgpContext} */ 26341 cgp = null; 26342 26343 /** 26344 * Description 26345 * @param {CgpContext} cgp 26346 * @param {string} name 26347 * @param {object} options 26348 */ 26349 constructor(cgp, name, options) 26350 { 26351 this.cgp = cgp; 26352 this.name = name; 26353 if (!name) this.log.error("no binding name given"); 26354 this.options = options || {}; 26355 if (options.hasOwnProperty("stage")) this.stage = options.stage; 26356 } 26357 26358 /** 26359 * @param {number} _inst 26360 */ 26361 getResource(_inst) 26362 { 26363 // overwrite 26364 return null; 26365 } 26366 26367 /** 26368 * @param {number} i 26369 */ 26370 setBindNum(i) 26371 { 26372 if (this.bindNum != i) this.needsRebuildBindgroup = true; 26373 this.bindNum = i; 26374 } 26375 26376 /** 26377 * @returns {GPUBindGroupLayoutEntry} 26378 * @param {CgpShader} _shader 26379 */ 26380 getLayoutEntry(_shader) 26381 { 26382 this.log.warn("unknown binding type?", this); 26383 return null; 26384 } 26385 26386 /** 26387 * @returns {GPUBindGroupEntry} 26388 * @param {number} inst 26389 */ 26390 getBindgroupEntry(inst) 26391 { 26392 let label = "layout " + this.name + " [" + this.constructor.name; 26393 label += "]"; 26394 26395 return { 26396 "binding": this.bindNum, 26397 "resource": this.getResource(inst) 26398 }; 26399 } 26400 26401 /** @param {CgpShader} _shader */ 26402 isActiveByDefine(_shader) 26403 { 26404 if (!this.define) return true; 26405 // if (this.define && !shader.hasDefine(this.define)) return false;
26406 return true; 26407 } 26408 26409 /** @param {number} _inst */ 26410 updateValues(_inst) 26411 { 26412 // overwrite 26413 } 26414 26415 /** 26416 * @param {CgpShader} _shader 26417 * @param {number} _bindGroupNum 26418 * @returns {String} 26419 */ 26420 getShaderHeaderCode(_shader, _bindGroupNum) 26421 { 26422 return "//getShaderHeaderCode function not emplemented " + constants.nl; 26423 } 26424 26425 /** 26426 * @param {CgpShader} _shader 26427 * @returns {Binding} 26428 */ 26429 copy(_shader) 26430 { 26431 // implenented in inheriting classes 26432 return null; 26433 } 26434 26435 getInfo() 26436 { 26437 const o = { "name": this.name, "id": this.id, "class": this.constructor.name }; 26438 return o; 26439 } 26440} 26441 26442// EXTERNAL MODULE: ../shared/client/src/eventtarget.js + 2 modules 26443var eventtarget = __webpack_require__("../shared/client/src/eventtarget.js"); 26444;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_gpubuffer.js 26445 26446 26447 26448 26449/** @typedef GPUBufferOptions 26450 * @property {number} [length] 26451 * @property {GPUBufferDescriptor} [buffCfg] 26452*/ 26453 26454class CgpGguBuffer extends eventtarget["default"] 26455{ 26456 #name = "unknown"; 26457 26458 /** @type {CgpContext} */ 26459 #cgp = null; 26460 26461 /** @type {GPUBuffer} */ 26462 #gpuBuffer = null; 26463 26464 /** @type {GPUBufferDescriptor} */ 26465 buffCfg = null; 26466 26467 #length = 0; 26468 id = utils.shortId(); 26469 floatArr = null; 26470 needsUpdate = true; 26471 #log; 26472 26473 // static BINDINGTYPE_STORAGE = "storage"; 26474 // static BINDINGTYPE_UNIFORM = "uniform"; 26475 // static BINDINGTYPE_READONLY_STORAGE = "read-only-storage"; 26476 26477 /** 26478 * Description 26479 * @param {CgpContext} cgp 26480 * @param {String} name 26481 * @param {Array} data=null 26482 * @param {GPUBufferOptions} options={} 26483 */ 26484 constructor(cgp, name, data = null, options = {}) 26485 { 26486 super(); 26487 this.#log = new logger["default"]("cgpGpubuffer"); 26488 if (!cgp.supported) return; 26489 26490 this.#name = name; 26491 // this.setData([0, 0, 0, 0]); 26492 26493 this.buffCfg = options.buffCfg || {}; 26494 if (data) this.setData(data); 26495 if (options.length) this.setLength(options.length); 26496 26497 this.buffCfg.usage = this.buffCfg.usage || (GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC); 26498 this.updateGpuBuffer(cgp); 26499 } 26500 26501 /** 26502 * @param {Array} arr 26503 */ 26504 setData(arr) 26505 { 26506 this.floatArr = new Float32Array(arr); 26507 this.setLength(this.floatArr.length); 26508 26509 this.needsUpdate = true; 26510 } 26511 26512 /** 26513 * @param {number} s 26514 */ 26515 setLength(s) 26516 { 26517 this.#length = s; 26518 if (!this.floatArr || s != this.floatArr.length) 26519 { 26520 this.floatArr = new Float32Array(this.#length); 26521 this.needsUpdate = true; 26522 } 26523 } 26524 26525 /** 26526 * @param {number} flag 26527 */ 26528 hasUsage(flag) 26529 { 26530 return (this.buffCfg.usage & flag) === flag; 26531 } 26532 26533 /** @param {CgpContext} cgp */ 26534 updateGpuBuffer(cgp = null) 26535 { 26536 if (cgp) this.#cgp = cgp; 26537 if (!this.#cgp || !this.#cgp.device) 26538 { 26539 this.#log.warn("no cgp...", this.#name, this.#cgp); 26540 return; 26541 } 26542 26543 this.#cgp.pushErrorScope("updateGpuBuffer"); 26544 if (!this.#gpuBuffer || this.buffCfg.mappedAtCreation) 26545 { 26546 this.buffCfg = /** @type {GPUBufferDescriptor} */(this.buffCfg || {}); 26547 this.buffCfg.label = "gpuBuffer-" + this.#name; 26548 if (!this.buffCfg.hasOwnProperty("size") && this.floatArr) this.buffCfg.size = this.floatArr.length * 4; 26549 26550 this.#gpuBuffer = this.#cgp.device.createBuffer(this.buffCfg); 26551 } 26552 26553 if (this.floatArr) 26554 { 26555 if (this.buffCfg.mappedAtCreation) 26556 { 26557 new Float32Array(this.#gpuBuffer.getMappedRange()).set(this.floatArr); 26558 this.#gpuBuffer.unmap(); 26559 26560 } 26561 else 26562 26563 this.#cgp.device.queue.writeBuffer( 26564 this.#gpuBuffer, 26565 0, 26566 this.floatArr.buffer, 26567 this.floatArr.byteOffset, 26568 this.floatArr.byteLength 26569 ); 26570 } 26571 26572 this.#cgp.popErrorScope(); 26573 26574 this.needsUpdate = false;
26575 } 26576 26577 get name() 26578 { 26579 return this.#name; 26580 } 26581 26582 /** @returns {GPUBuffer} */ 26583 get gpuBuffer() 26584 { 26585 if (!this.#gpuBuffer || this.needsUpdate) this.updateGpuBuffer(); 26586 26587 return this.#gpuBuffer; 26588 } 26589 26590 get length() 26591 { 26592 return this.#length; 26593 } 26594 26595 getSizeBytes() 26596 { 26597 return this.floatArr.length * 4; 26598 } 26599 26600 dispose() 26601 { 26602 // setTimeout(() => 26603 // { 26604 // if (this._gpuBuffer) this._gpuBuffer.destroy(); 26605 // }, 100); 26606 } 26607} 26608 26609;// CONCATENATED MODULE: ./src/corelibs/cgp/binding/binding_uniform.js 26610 26611 26612 26613 26614 26615 26616/** @extends Binding */ 26617class BindingUniform extends Binding 26618{ 26619 26620 /** @type {Array<CgpUniform>} */ 26621 #uniforms = []; 26622 26623 /** @type {Array<CgpGguBuffer>} */ 26624 cgpBuffer = []; 26625 26626 /** 26627 * Description 26628 * @param {CgpContext} cgp 26629 * @param {string} name 26630 * @param {object} options 26631 */ 26632 constructor(cgp, name, options) 26633 { 26634 super(cgp, name, options); 26635 26636 console.log("new binding uniform", this.id); 26637 } 26638 26639 /** 26640 * @param {CgpShader} shader 26641 * @returns {Binding} 26642 */ 26643 copy(shader) 26644 { 26645 const b = new BindingUniform(this.cgp, this.name, this.options); 26646 console.log("copybinuni", this.id, b.id); 26647 b.stage = this.stage; 26648 26649 for (let i = 0; i < this.#uniforms.length; i++) 26650 { 26651 let foundWorldUni = false; 26652 for (let j = 0; j < shader.worldUniforms.length; j++) 26653 { 26654 if (shader.worldUniforms[j].getName() == this.#uniforms[i].getName()) 26655 { 26656 b.addUniform(shader.worldUniforms[j]); 26657 foundWorldUni = true; 26658 } 26659 } 26660 if (!foundWorldUni) b.addUniform(this.#uniforms[i]); 26661 } 26662 26663 return b; 26664 } 26665 26666 /** 26667 * @param {CgpUniform} u 26668 */ 26669 addUniform(u) 26670 { 26671 this.#uniforms.push(u); 26672 this.needsRebuildBindgroup = true; 26673 console.log(this.#uniforms, this); 26674 return u; 26675 } 26676 26677 /** 26678 * @returns {GPUBindingResource} 26679 * @param {number} inst 26680 */ 26681 getResource(inst) 26682 { 26683 this.updateBuffer(inst); 26684 return { 26685 "buffer": this.cgpBuffer[inst].gpuBuffer, 26686 }; 26687 } 26688 26689 getSizeBytes() 26690 { 26691 let size = 0; 26692 for (let i = 0; i < this.#uniforms.length; i++) 26693 size += this.#uniforms[i].getSizeBytes(); 26694 26695 return size; 26696 } 26697 26698 /** 26699 * @param {string} name 26700 */ 26701 getUniform(name) 26702 { 26703 for (let i = 0; i < this.#uniforms.length; i++) 26704 { 26705 if (this.#uniforms[i].name == name) return this.#uniforms[i]; 26706 } 26707 return null; 26708 } 26709 26710 /** 26711 * @param {string} name 26712 */ 26713 removeUniformByName(name) 26714 { 26715 for (let i = 0; i < this.#uniforms.length; i++) 26716 if (this.#uniforms[i].name == name) 26717 { 26718 this.needsRebuildBindgroup = true; 26719 return this.#uniforms.splice(i, 1); 26720 } 26721 } 26722 26723 /** 26724 * @param {number} inst 26725 */ 26726 createBuffer(inst) 26727 { 26728 let buffCfg = { 26729 "label": this.name, 26730 "size": this.getSizeBytes(), 26731 "usage": GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM 26732 }; 26733 26734 this.cgpBuffer[inst] = new CgpGguBuffer(this.cgp, this.name + " buff", null, { "buffCfg": buffCfg }); 26735 } 26736 26737 pipelineUpdated() 26738 { 26739 this.needsRebuildBindgroup = false; 26740 } 26741 26742 needsPipeUpdate() 26743 { 26744 return this.needsRebuildBindgroup; 26745 } 26746 26747 /** 26748 * @param {number} inst 26749 */ 26750 updateBuffer(inst) 26751 { 26752 let info = { "name": this.#uniforms.length + " uniforms", "stage ": CgpShader.getStageString(this.stage), "uniforms": [] }; 26753 26754 let s = this.getSizeBytes() / 4; 26755 info.s = this.getSizeBytes(); 26756 if (s == 16)s = 16; 26757 if (!this.cgpBuffer[inst]) 26758 { 26759 this.createBuffer(inst); 26760 // console.log("no cpubuff? ", s, this.#uniforms); 26761 // return; 26762 } 26763 this.cgpBuffer[inst].setLength(s); 26764 26765 let off = 0; 26766 for (let i = 0; i < this.#uniforms.length; i++) 26767 { 26768 this.#uniforms[i].copyToBuffer(this.cgpBuffer[inst].floatArr, off); 26769 26770 if (this.#uniforms[i].gpuBufferChanged) 26771 console.log("un changed", this.cgpBuffer[inst].floatArr); 26772 26773 info.uniforms.push(this.#uniforms[i].getInfo()); 26774 26775 off += this.#uniforms[i].getSizeBytes() / 4; 26776 } 26777 if (this.cgp.branchProfiler) this.cgp.branchProfiler.push("binding update buff", CgpShader.getStageString(this.stage), { "info": info }); 26778 26779 this.cgpBuffer[inst].updateGpuBuffer(); 26780 26781 if (this.cgp.branchProfiler) this.cgp.branchProfiler.pop(); 26782 } 26783 26784 /** 26785 * @param {CgpShader} shader 26786 * @param {number} bindGroupNum 26787 */ 26788 getShaderHeaderCode(shader, bindGroupNum) 26789 { 26790 this.cgp.profileData.count("shadercode uni", this.name); 26791 let str = ""; 26792 let typeStr = ""; 26793 let name = this.name; 26794 26795 str += "// [binding_uniform] - \"" + this.name + "\" " + this.id + " uniforms:" + this.#uniforms.length + "\n"; 26796 26797 if (!this.isActiveByDefine(shader)) 26798 { 26799 str += "// " + typeStr + " " + this.name + ": excluded because define " + this.define + "\n"; 26800 return str; 26801 } 26802 26803 if (this.#uniforms.length > 1) 26804 { 26805 typeStr = "strct_" + name; 26806 26807 str += "struct " + typeStr + "\n"; 26808 str += "{\n"; 26809 // if (this.#uniforms.length == 0) str += "placehoder:1."; 26810 // else 26811 for (let i = 0; i < this.#uniforms.length; i++) 26812 { 26813 str += " " + this.#uniforms[i].name + ": " + this.#uniforms[i].getWgslTypeStr(); 26814 if (i != this.#uniforms.length - 1)str += ","; 26815 str += "\n"; 26816 } 26817 str += "};\n"; 26818 26819 } 26820 else if (this.#uniforms.length == 1) 26821 { 26822 typeStr = this.#uniforms[0].getWgslTypeStr(); 26823 name = this.#uniforms[0].name; 26824 } 26825 else if (this.#uniforms.length == 0) 26826 { 26827 return str; 26828 // typeStr = "float"; 26829 // name = "placeholder"; 26830 } 26831 26832 // console.log("shadercode uniforms", this.#uniforms[0].name); 26833 str += "@group(" + bindGroupNum + ") "; 26834 str += "@binding(" + this.bindNum + ") "; 26835 26836 str += "var<uniform> "; 26837 str += name + ": " + typeStr + ";\n"; 26838 26839 // console.log(str); 26840 return str + "\n"; 26841 } 26842 26843 /** @returns {GPUBindGroupLayoutEntry} */ 26844 getLayoutEntry() 26845 { 26846 return { 26847 "visibility": this.stage, 26848 "binding": this.bindNum,
26849 "minBindingSize": this.getSizeBytes(), 26850 "hasDynamicOffset": 0, 26851 "buffer": {} 26852 }; 26853 } 26854 26855 /** 26856 * @param {number} inst 26857 */ 26858 updateValues(inst) 26859 { 26860 for (let i = 0; i < this.#uniforms.length; i++) 26861 { 26862 // if (this.#uniforms[i].needsUpdate) 26863 } 26864 return this.updateBuffer(inst); 26865 26866 } 26867 26868 getInfo() 26869 { 26870 const o = { "name": this.name, "id": this.id, "stage": this.stage, "class": this.constructor.name, "uniforms": [] }; 26871 26872 for (let i = 0; i < this.#uniforms.length; i++) 26873 { 26874 o.uniforms.push(this.#uniforms[i].getInfo()); 26875 } 26876 return o; 26877 } 26878} 26879 26880;// CONCATENATED MODULE: ./src/corelibs/cgp/binding/binding_sampler.js 26881 26882 26883 26884/** @extends Binding */ 26885class BindingSampler extends Binding 26886{ 26887 26888 /** @type {GPUSamplerDescriptor} */ 26889 smplDesc = { 26890 "addressModeU": "mirror-repeat", 26891 "addressModeV": "mirror-repeat", 26892 "magFilter": "linear", 26893 "minFilter": "linear", 26894 "mipmapFilter": "linear", 26895 }; 26896 26897 /** @type {GPUSampler} */ 26898 sampler = null; 26899 26900 constructor(cgp, name, options) 26901 { 26902 super(cgp, name, options); 26903 this.sampler = this.cgp.device.createSampler(this.smplDesc); 26904 26905 } 26906 26907 copy() 26908 { 26909 const b = new BindingSampler(this.cgp, this.name, this.options); 26910 return b; 26911 } 26912 26913 getResource() 26914 { 26915 return this.sampler; 26916 } 26917 26918 /** @returns {GPUBindGroupLayoutEntry} */ 26919 getLayoutEntry() 26920 { 26921 return { 26922 "visibility": this.stage, 26923 "binding": this.bindNum, 26924 "sampler": {} 26925 }; 26926 } 26927 26928 /** 26929 * @param {CgpShader} shader 26930 * @param {number} bindGroupNum 26931 */ 26932 getShaderHeaderCode(shader, bindGroupNum) 26933 { 26934 let str = "@group(" + bindGroupNum + ") @binding(" + this.bindNum + ") "; 26935 str += "var " + this.name + ": sampler;".endl(); 26936 return str; 26937 } 26938} 26939 26940;// CONCATENATED MODULE: ./src/corelibs/cgp/binding/binding_texture.js 26941 26942 26943 26944 26945 26946/** @extends {Binding} */ 26947class BindingTexture extends Binding 26948{ 26949 26950 /** @type {GPUSampler} */ 26951 sampler = null; 26952 uniform = null; 26953 26954 /** 26955 * @param {CgpContext} cgp 26956 * @param {string} name 26957 * @param {object} options 26958 */ 26959 constructor(cgp, name, options) 26960 { 26961 super(cgp, name, options); 26962 26963 /** @type {CgpUniform} */ 26964 this.uniform = options.uniform; 26965 26966 if (this.uniform.port) 26967 { 26968 this.uniform.port.on("change", () => 26969 { 26970 this.needsRebuildBindgroup = true; 26971 }); 26972 } 26973 26974 console.log(this.uniform); 26975 } 26976 26977 copy() 26978 { 26979 const b = new BindingTexture(this.cgp, this.name, this.options); 26980 return b; 26981 } 26982 26983 getResource() 26984 { 26985 if (this.uniform.getValue() && this.uniform.getValue().gpuTexture) return this.uniform.getValue().gpuTexture.createView(); 26986 else return this.cgp.getDefaultTexture().createView(); 26987 } 26988 26989 /** @returns {GPUBindGroupLayoutEntry} */ 26990 getLayoutEntry() 26991 { 26992 return { 26993 "visibility": this.stage, 26994 "binding": this.bindNum, 26995 "texture": {} 26996 }; 26997 } 26998 26999 /** 27000 * @param {CgpShader} _shader 27001 * @param {number} bindGroupNum 27002 */ 27003 getShaderHeaderCode(_shader, bindGroupNum) 27004 { 27005 let str = "@group(" + bindGroupNum + ") @binding(" + this.bindNum + ") "; 27006 str += "var " + this.name + ": " + this.uniform.getWgslTypeStr() + ";\n"; 27007 return str; 27008 } 27009} 27010 27011;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_shader.js 27012 27013 27014 27015 27016 27017 27018 27019 27020 27021 27022 27023 27024 27025/** @typedef CgpShaderOptions 27026 * @property {Boolean} [compute] 27027 * @property {String} [entryPoint] 27028 */ 27029 27030class CgpShader extends cg_shader.CgShader 27031{ 27032 27033 #lastCompileReason = "first"; 27034 27035 /** @type {CgpUniform} */ 27036 uniModelMatrix; 27037 27038 /** @type {CgpUniform} */ 27039 uniViewMatrix; 27040 27041 /** @type {CgpUniform} */ 27042 uniProjMatrix; 27043 27044 /** 27045 * @type {GPUCompilationInfo} 27046 */ 27047 compilationInfo; 27048 27049 /** 27050 * @param {CgpContext} _cgp 27051 * @param {String} _name 27052 * @param {CgpShaderOptions} options={} 27053 */ 27054 constructor(_cgp, _name, options = {}) 27055 { 27056 super(); 27057 if (!_cgp) throw new Error("shader constructed without cgp " + _name); 27058 this._log = new logger["default"]("cgp_shader"); 27059 this._cgp = _cgp; 27060 this._name = _name; 27061 this.options = options; 27062 this.options.compute = this.options.compute || false; 27063 27064 if (!_name) this._log.stack("no shader name given"); 27065 this._name = _name || "unknown"; 27066 this.gpuShaderModule = null; 27067 this.frameUsageCounter = 0; 27068 this.lastFrameUsageCounter = -2; 27069 this.frameUsageFrame = -1; 27070 27071 this._bindingIndexCount = 0; 27072 this.compileCount = 0; 27073 this.worldUniforms = []; 27074 27075 this.defaultBindGroup = new BindGroup(_cgp, this._name); 27076 this.modsBindGroup = new BindGroup(_cgp, this._name); 27077 27078 /** @type {Array<BindGroup>} */ 27079 this.bindGroups = [this.defaultBindGroup, this.modsBindGroup]; 27080 27081 if (!this.options.compute) 27082 { 27083 // this.bindingWorld = new BindingUniform(_cgp, "world", { "stage": GPUShaderStage.VERTEX }); 27084 // this.defaultBindGroup.addBinding(this.bindingWorld); 27085 27086 this.defaultUniBindingVert = new BindingUniform(_cgp, "uniVert", { "stage": GPUShaderStage.VERTEX }); 27087 this.defaultBindGroup.addBinding(this.defaultUniBindingVert); 27088 27089 this.defaultUniBindingFrag = new BindingUniform(_cgp, "uniFrag", { "stage": GPUShaderStage.FRAGMENT }); 27090 this.defaultBindGroup.addBinding(this.defaultUniBindingFrag); 27091 } 27092 else 27093 { 27094 this.defaultUniBindingCompute = new BindingUniform(_cgp, "uniCompute", { "stage": GPUShaderStage.COMPUTE }); 27095 this.defaultBindGroup.addBinding(this.defaultUniBindingCompute); 27096 } 27097 27098 if (!this.options.compute) 27099 { 27100 this.uniModelMatrix = this.addUniform(new CgpUniform(this, "m4", "modelMatrix"), GPUShaderStage.VERTEX); 27101 this.uniViewMatrix = this.addUniform(new CgpUniform(this, "m4", "viewMatrix"), GPUShaderStage.VERTEX); 27102 this.uniProjMatrix = this.addUniform(new CgpUniform(this, "m4", "projMatrix"), GPUShaderStage.VERTEX); 27103 this.uniNormalMatrix = this.addUniform(new CgpUniform(this, "m4", "normalMatrix"), GPUShaderStage.VERTEX); 27104 this.uniModelViewMatrix = this.addUniform(new CgpUniform(this, "m4", "modelViewMatrix"), GPUShaderStage.VERTEX); 27105 this._tempNormalMatrix = mat4.create(); 27106 this._tempModelViewMatrix = mat4.create(); 27107 this.worldUniforms.push(this.uniModelMatrix, this.uniViewMatrix, this.uniProjMatrix, this.uniNormalMatrix, this.uniModelViewMatrix); 27108 } 27109 27110 this._src = ""; 27111 27112 this._cgp.on("deviceChange", () => 27113 { 27114 this.gpuShaderModule = null; 27115 this.setWhyCompile("device changed"); 27116 }); 27117 } 27118 27119 reInit() 27120 { 27121 27122 } 27123 27124 /** @returns {boolean} */ 27125 isValid() 27126 { 27127 return this._isValid; 27128 } 27129 27130 getName() 27131 { 27132 return this._name; 27133 } 27134 27135 incFrameUsageCount() 27136 { 27137 if (this.frameUsageFrame != this._cgp.frame) 27138 { 27139 this.lastFrameUsageCounter = this.frameUsageCounter; 27140 this.frameUsageCounter = 0; 27141 } 27142 else this.frameUsageCounter++; 27143 this.frameUsageFrame = this._cgp.frame; 27144 27145 return this.frameUsageCounter; 27146 } 27147 27148 getNewBindingGroupIndex() 27149 { 27150 return ++this._bindingIndexCount; 27151 } 27152 27153 /** 27154 * @param {String} src 27155 */ 27156 setSource(src) 27157 { 27158 this._src = src; 27159 this.setWhyCompile("Source changed"); 27160 } 27161 27162 /** 27163 * @param {import("../cg/cg_shader.js").ShaderModule} mod 27164 * @param {string} src 27165 */ 27166 _replaceModPrefixes(mod, src) 27167 { 27168 return src.replace(/MOD_/g, mod.prefix); 27169 } 27170 27171 /** 27172 * @param {String} vs 27173 * @param {{}}
27173 defs 27174 */ 27175 _replaceMods(vs, defs) 27176 { 27177 let srcHeadVert = ""; 27178 for (let i = 0; i < this._moduleNames.length; i++) 27179 { 27180 let srcVert = ""; 27181 27182 for (let j = 0; j < this._modules.length; j++) 27183 { 27184 const mod = this._modules[j]; 27185 if (mod.name == this._moduleNames[i]) 27186 { 27187 srcHeadVert += constants.nl + constants.nl + "//---- MOD: group:" + mod.group + ": idx:" + j + " - prfx:" + mod.prefix + " - " + mod.title + " ------" + constants.nl; 27188 27189 srcVert += constants.nl + constants.nl + "//---- MOD: " + mod.title + " / " + mod.priority + " ------" + constants.nl; 27190 27191 if (mod.attributes) 27192 for (let k = 0; k < mod.attributes.length; k++) 27193 { 27194 const r = this._getAttrSrc(mod.attributes[k], false); 27195 if (r.srcHeadVert)srcHeadVert += r.srcHeadVert; 27196 if (r.srcVert)srcVert += r.srcVert; 27197 } 27198 27199 srcHeadVert += mod.srcHead || ""; 27200 srcVert += mod.srcBody || ""; 27201 27202 srcHeadVert += constants.nl + "//---- end mod ------" + constants.nl; 27203 27204 srcVert += constants.nl + "//---- end mod ------" + constants.nl; 27205 27206 srcVert = this._replaceModPrefixes(mod, srcVert); 27207 srcHeadVert = this._replaceModPrefixes(mod, srcHeadVert); 27208 27209 } 27210 } 27211 27212 srcVert = preproc(srcVert, defs); 27213 vs = vs.replace("{{" + this._moduleNames[i] + "}}", srcVert); 27214 } 27215 27216 srcHeadVert = preproc(srcHeadVert, defs); 27217 vs = vs.replace("{{MODULES_HEAD}}", srcHeadVert); 27218 return vs; 27219 } 27220 27221 /** 27222 * @param {string} src 27223 */ 27224 _replaceVertexOutputs(src = "") 27225 { 27226 const strVertOut = "{{VERTEX_OUTPUT"; 27227 const posVertOut = src.indexOf(strVertOut); 27228 if (posVertOut > -1) 27229 { 27230 try 27231 { 27232 let str = src.substring(posVertOut + strVertOut.length, posVertOut + 100); 27233 let endPos = str.indexOf("}}"); 27234 let startNum = parseInt(str.substring(0, endPos)); 27235 27236 for (let j = 0; j < this._modules.length; j++) 27237 { 27238 if (!this._modules[j].outputs) continue; 27239 let outs = this._modules[j].outputs; 27240 let l = 0; 27241 while (outs.indexOf("@location(" + l + ")") > -1) 27242 { 27243 outs = outs.replaceAll("@location(" + l + ")", "@location(" + (l + startNum) + ")"); 27244 } 27245 outs = this._replaceModPrefixes(this._modules[j], outs); 27246 src = src.replaceAll(strVertOut + " " + startNum + "}}", outs); 27247 } 27248 27249 } 27250 catch (e) 27251 { 27252 console.log(e); 27253 } 27254 } 27255 return src; 27256 } 27257 27258 getDefines() 27259 { 27260 return this._defines; 27261 } 27262 27263 getProcessedSource() 27264 { 27265 const defs = {}; 27266 for (let i = 0; i < this._defines.length; i++) 27267 defs[this._defines[i][0]] = this._defines[i][1] || true; 27268 27269 let src = ""; 27270 src += preproc(this._src, defs); 27271 27272 let strDefs = ""; 27273 for (let i = 0; i < this._defines.length; i++) 27274 strDefs += "// #define " + this._defines[i] + "\n"; 27275 27276 let bindingsHeadVert = ""; 27277 let bindingsHeadFrag = ""; 27278 let bindingsHeadCompute = ""; 27279 27280 for (let i = 0; i < this.bindGroups.length; i++) 27281 { 27282 const src = this.bindGroups[i].getShaderHeaderCode(this, i); 27283 bindingsHeadFrag += src.fragment || ""; 27284 bindingsHeadVert += src.vertex || ""; 27285 bindingsHeadCompute += src.compute || ""; 27286 } 27287 27288 if (this.options.compute) 27289 src = bindingsHeadCompute + "\n\n////////////////\n\n" + src; 27290 else 27291 src = bindingsHeadFrag + "\n\n////////////////\n\n" + bindingsHeadVert + "\n\n////////////////\n\n" + src; 27292 27293 src = this._replaceMods(src, defs); 27294 27295 src = this._replaceVertexOutputs(src); 27296 27297 const strVertOut = "{{VERTEX_OUTPUT"; 27298 const posVertOut = src.indexOf(strVertOut); 27299 if (posVertOut > -1) 27300 { 27301 try 27302 { 27303 let str = src.substring(posVertOut + strVertOut.length, posVertOut + 100); 27304 let endPos = str.indexOf("}}"); 27305 let startNum = parseInt(str.substring(0, endPos)); 27306 let locCode = "@location(" + (startNum) + ") pos:vec4f, // generated"; 27307 27308 src = src.replaceAll(strVertOut + " " + startNum + "}}", locCode); 27309 } 27310 catch (e) 27311 { 27312 console.log(e); 27313 } 27314 } 27315 src = strDefs + "\n" + src; 27316 27317 let srcHead = "//" + constants.nl + "// "; 27318 if (this.options.compute)srcHead += "Compute "; 27319 else srcHead += "Render "; 27320 27321 srcHead += "Shader: " + this._name + " - " + this.id + constants.nl; 27322 srcHead += "//" + constants.nl; 27323 27324 return srcHead + src; 27325 } 27326 27327 compile() 27328 { 27329 this._isValid = true; 27330 this._cgp.pushErrorScope("cgp_shader " + this._name); 27331 27332 if (this._cgp.branchProfiler) this._cgp.branchProfiler.push("shadercompile", this._name, { "info": this.getInfo() }); 27333 27334 this._cgp.profileData.count("shader compile", this._name); 27335 this.gpuShaderModule = this._cgp.device.createShaderModule({ "code": this.getProcessedSource(), "label": this._name }); 27336 27337 this.gpuShaderModule.getCompilationInfo().then((compInfo) => 27338 { 27339 this.compilationInfo = compInfo; 27340 if (compInfo.messages.length > 0) 27341 { 27342 let hasErrors = false;
27343 for (const msg of compInfo.messages) 27344 { 27345 switch (msg.type) 27346 { 27347 case "error": 27348 console.error("Shader " + msg.type + " at line " + msg.lineNum + ":" + msg.linePos + " :" + msg.message); 27349 hasErrors = true; 27350 case "warning": 27351 console.warn("Shader " + msg.type + " at line " + msg.lineNum + ":" + msg.linePos + " :" + msg.message); 27352 break; 27353 case "info": 27354 console.info("Shader " + msg.type + " at line " + msg.lineNum + ":" + msg.linePos + " :" + msg.message); 27355 break; 27356 } 27357 } 27358 if (hasErrors) 27359 { 27360 console.log("has errrrrrrrrrr"); 27361 CABLES.UI.showShaderErrorCgp(this, compInfo, this.getProcessedSource()); 27362 } 27363 27364 } 27365 }); 27366 27367 this._cgp.popErrorScope(this.error.bind(this)); 27368 27369 this.#lastCompileReason = this._compileReason; 27370 27371 this.lastCompile = (0,timer.now)(); 27372 // console.log("#lastCompileReason", this.#lastCompileReason); 27373 27374 this.emitEvent("compiled", this._compileReason); 27375 this._needsRecompile = false; 27376 this._compileReason = "none"; 27377 this.compileCount++; 27378 27379 if (this._cgp.branchProfiler) this._cgp.branchProfiler.pop(); 27380 } 27381 27382 error(e) 27383 { 27384 this._isValid = false; 27385 } 27386 27387 bind(passEnc = null) 27388 { 27389 27390 this.incFrameUsageCount(); 27391 if (!this.options.compute) 27392 { 27393 this.uniModelMatrix.setValue(this._cgp.mMatrix); 27394 this.uniViewMatrix.setValue(this._cgp.vMatrix); 27395 this.uniProjMatrix.setValue(this._cgp.pMatrix); 27396 27397 // mat4.invert(this._tempNormalMatrix, this._cgp.mMatrix); 27398 // mat4.transpose(this._tempNormalMatrix, this._tempNormalMatrix); 27399 mat4.mul(this._tempModelViewMatrix, this._cgp.vMatrix, this._cgp.mMatrix); 27400 this.uniModelViewMatrix.setValue(this._tempModelViewMatrix); 27401 27402 mat4.copy(this._tempNormalMatrix, this._cgp.mMatrix); 27403 mat4.invert(this._tempNormalMatrix, this._tempNormalMatrix); 27404 mat4.transpose(this._tempNormalMatrix, this._tempNormalMatrix); 27405 27406 // cpu billboarding? 27407 // this._tempModelViewMatrix[0 * 4 + 0] = 1.0; 27408 // this._tempModelViewMatrix[0 * 4 + 1] = 0.0; 27409 // this._tempModelViewMatrix[0 * 4 + 2] = 0.0; 27410 27411 // // #ifndef BILLBOARDING_CYLINDRIC 27412 // this._tempModelViewMatrix[1 * 4 + 0] = 0.0; 27413 // this._tempModelViewMatrix[1 * 4 + 1] = 1.0; 27414 // this._tempModelViewMatrix[1 * 4 + 2] = 0.0; 27415 // // #endif 27416 27417 // this._tempModelViewMatrix[2 * 4 + 0] = 0.0; 27418 // this._tempModelViewMatrix[2 * 4 + 1] = 0.0; 27419 // this._tempModelViewMatrix[2 * 4 + 2] = 1.0; 27420 27421 this.uniNormalMatrix.setValue(this._tempNormalMatrix); 27422 } 27423 27424 for (let i = 0; i < this.bindGroups.length; i++) 27425 { 27426 this.bindGroups[i].updateValues(this.frameUsageCounter); 27427 this.bindGroups[i].bind(this.frameUsageCounter, passEnc, i); 27428 } 27429 if (this._needsRecompile) this.compile(); 27430 } 27431 27432 /** 27433 * @param {number} stage 27434 * @returns {BindingUniform} 27435 */ 27436 getDefaultUniBinding(stage) 27437 { 27438 let binding = this.defaultUniBindingFrag; 27439 if (stage == GPUShaderStage.VERTEX) binding = this.defaultUniBindingVert; 27440 if (this.options.compute && stage == GPUShaderStage.COMPUTE) binding = this.defaultUniBindingCompute; 27441 return binding; 27442 } 27443 27444 pipelineUpdated() 27445 { 27446 27447 if (this.defaultUniBindingFrag) this.defaultUniBindingFrag.pipelineUpdated(); 27448 if (this.defaultUniBindingVert) this.defaultUniBindingVert.pipelineUpdated(); 27449 if (this.defaultUniBindingCompute) this.defaultUniBindingCompute.pipelineUpdated(); 27450 } 27451 27452 bindingsNeedPipeUpdate() 27453 { 27454 return ( 27455 (this.defaultUniBindingFrag && this.defaultUniBindingFrag.needsPipeUpd
27455ate()) || 27456 (this.defaultUniBindingVert && this.defaultUniBindingVert.needsPipeUpdate()) || 27457 (this.defaultUniBindingCompute && this.defaultUniBindingCompute.needsPipeUpdate()) 27458 ); 27459 } 27460 27461 /** 27462 * @param {String} name 27463 * @param {number} stage 27464 */ 27465 hasUniformInStage(name, stage) 27466 { 27467 let binding = this.getDefaultUniBinding(stage); 27468 27469 // console.log("bindingget uni", stage, binding, CgpShader.getStageString(stage)); 27470 if (!binding) return false; 27471 return !!binding.getUniform(name); 27472 } 27473 27474 /** 27475 * @param {String} name 27476 */ 27477 hasUniform(name) 27478 { 27479 return this.hasUniformInStage(name, GPUShaderStage.FRAGMENT) || this.hasUniformInStage(name, GPUShaderStage.VERTEX) || this.hasUniformInStage(name, GPUShaderStage.COMPUTE); 27480 } 27481 27482 /** 27483 * @param {CgpUniform} u 27484 * @param {number} stage 27485 * @returns {CgpUniform} 27486 */ 27487 addUniform(u, stage) 27488 { 27489 const binding = this.getDefaultUniBinding(stage); 27490 if (u.type == "t") this.defaultBindGroup.addBinding(new BindingTexture(this._cgp, u.name, { "uniform": u })); 27491 else if (u.type == "sampler") this.defaultBindGroup.addBinding(new BindingSampler(this._cgp, u.name, { "uniform": u })); 27492 else 27493 { 27494 binding.addUniform(u); 27495 } 27496 27497 this.needsPipelineUpdate = "add uniform"; 27498 console.log("adduni2", this._name, u.name, this.id, binding, CgpShader.getStageString(stage)); 27499 console.log("code", binding.getShaderHeaderCode(this, 0)); 27500 27501 // if (!this.defaultBindGroup.hasBinding(binding)) this.defaultBindGroup.addBinding(binding); 27502 return u; 27503 } 27504 27505 removeUniformByName(name) 27506 { 27507 const binding = this.getDefaultUniBinding(stage); 27508 binding.removeUniformByName(name); 27509 27510 } 27511 27512 /** 27513 * copy current shader 27514 * @returns newShader 27515 */ 27516 copy() 27517 { 27518 this.bind(); 27519 const shader = new CgpShader(this._cgp, this._name + " copy", this.options); 27520 console.log("copyyyyyy", this.id, shader.id); 27521 shader.setSource(this._src); 27522 27523 shader._modules = JSON.parse(JSON.stringify(this._modules)); 27524 shader._defines = JSON.parse(JSON.stringify(this._defines)); 27525 27526 shader._moduleNames = this._moduleNames; 27527 27528 shader.bindGroups = []; 27529 for (let i = 0; i < this.bindGroups.length; i++) 27530 { 27531 const bg = this.bindGroups[i].copy(shader); 27532 shader.bindGroups.push(bg); 27533 27534 if (this.bindGroups[i] == this.defaultBindGroup) shader.defaultBindGroup = bg; 27535 // if (this.bindGroups[i] == this.modsBindGroup) shader.modsBindGroup = bg; 27536 bg.setBindingNums(); 27537 } 27538 27539 shader.setWhyCompile("copy"); 27540 shader.compile(); 27541 return shader; 27542 } 27543 27544 dispose() 27545 { 27546 27547 } 27548 27549 /** 27550 * @param {number} stage 27551 */ 27552 static getStageString(stage) 27553 { 27554 if (stage == GPUShaderStage.FRAGMENT) return "frag"; 27555 if (stage == GPUShaderStage.VERTEX) return "vertex"; 27556 if (stage == (GPUShaderStage.FRAGMENT | GPUShaderStage.VERTEX)) return "frag+vertex"; 27557 if (stage == (GPUShaderStage.FRAGMENT | GPUShaderStage.VERTEX | GPUShaderStage.COMPUTE)) return "frag+vertex+comp"; 27558 if (stage == GPUShaderStage.COMPUTE) return "compute"; 27559 27560 return "unknown" + stage; 27561 } 27562 27563 getInfo() 27564 { 27565 const o = { 27566 "class": this.constructor.name, 27567 "id": this.id, 27568 "name": this._name, 27569 "needsPipelineUpdate": this.needsPipelineUpdate, 27570 "frameUsageCounter": this.lastFrameUsageCounter, 27571 "lastCompileReason": this.#lastCompileReason, 27572 "compileCount": this.compileCount, 27573 "defines": this._defines, 27574 "isCompute": this.options.compute, 27575 "modules": [], 27576 "bindgroups": [] 27577 }; 27578 27579 for (let i = 0; i < this.bindGroups.length; i++) 27580 { 27581 o.bindgroups.push(this.bindGroups[i].getInfo()); 27582 } 27583 27584 for (let i = 0; i < this._modules.length; i++) 27585 { 27586 o.modules.push(this._modules[i].title + " " + this._modules[i].name + " " + this._modules[i].group); 27587 // console.log(this._modules[i]); 27588 } 27589 27590 return o; 27591 } 27592 27593 copyUniformValues(orig) 27594 { 27595 27596 } 27597} 27598 27599;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_texture.js 27600 27601 27602 27603 27604class Texture extends cg_texture.CgTexture 27605{ 27606 #log = new logger["default"]("cgp_texture"); 27607 27608 /** @type {CgpContext} */ 27609 #cgp = null; 27610 27611 /** @type {GPUTexture} */ 27612 gpuTexture = null; 27613 27614 /** @type {GPUTextureDescriptor} */ 27615 gpuTextureDescriptor = null; 27616 name = "unknown"; 27617 width = 8; 27618 height = 8; 27619 textureType = "???"; 27620 27621 samplerDesc = {}; 27622 27623 /** 27624 * @param {CgpContext} _cgp 27625 * @param {Object} options={} 27626 */ 27627 constructor(_cgp, options = {}) 27628 { 27629 super(options); 27630 options = options || {}; 27631 27632 this.#cgp = _cgp; 27633 if (!this.#cgp) throw new Error("no cgp"); 27634 27635 if (options.name) this.name = options.name; 27636 if (options.height && options.width) this.setSize(options.width, options.height); 27637 27638 this.#cgp.on("deviceChange", () => 27639 { 27640 }); 27641 this.samplerDesc = { 27642 "addressModeU": options.wrap || options.addressModeU || "clamp-to-edge", 27643 "addressModeV": options.wrap || options.addressModeV || "clamp-to-edge", 27644 "magFilter": options.magFilter || options.filter || "linear", 27645 "minFilter": options.minFilter || options.filter || "linear", 27646 }; 27647 27648 } 27649 27650 /** 27651 * @param {Number} w 27652 * @param {Number} h 27653 */ 27654 setSize(w, h) 27655 { 27656 this.width = w; 27657 this.height = h; 27658 } 27659 27660 /** 27661 * set texture data from an image/canvas object 27662 * @function initTexture 27663 * @memberof Texture 27664 * @instance 27665 * @param {Object} img image 27666 * @param {Number} filter 27667 */ 27668 initTexture(img, filter) 27669 { 27670 this.width = img.width;
27671 this.height = img.height; 27672 27673 const textureType = "rgba8unorm"; 27674 27675 this.#cgp.pushErrorScope("inittexture", { "logger": this.#log }); 27676 27677 this.gpuTextureDescriptor = { 27678 27679 "size": { "width": img.width, "height": img.height }, 27680 "format": textureType, 27681 // "sampleCount": 4, 27682 "usage": GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT 27683 }; 27684 27685 this.gpuTexture = this.#cgp.device.createTexture(this.gpuTextureDescriptor); 27686 this.#cgp.device.queue.copyExternalImageToTexture({ "source": img }, { "texture": this.gpuTexture }, this.gpuTextureDescriptor.size); 27687 27688 this.#cgp.popErrorScope(); 27689 27690 return this.gpuTexture; 27691 } 27692 27693 dispose() 27694 { 27695 console.log("todo dispose"); 27696 } 27697 27698 getInfo() 27699 { 27700 const obj = {}; 27701 27702 obj.name = this.name || "???"; 27703 obj.size = this.width + " x " + this.height; 27704 27705 obj.textureType = this.textureType; 27706 27707 return obj; 27708 } 27709 27710 createView() 27711 { 27712 if (!this.gpuTexture) 27713 { 27714 console.log("no gputexture..."); 27715 return null; 27716 } 27717 return this.gpuTexture.createView(); 27718 } 27719 27720 getSampler() 27721 { 27722 // "clamp-to-edge" 27723 // "repeat" 27724 // "mirror-repeat" 27725 27726 return this.samplerDesc; 27727 } 27728 27729 /** 27730 * @function initFromData 27731 * @memberof Texture 27732 * @instance 27733 * @description create texturem from rgb data 27734 * @param {ArrayBuffer} data rgb color array [r,g,b,a,r,g,b,a,...] 27735 * @param {Number} w width 27736 * @param {Number} h height 27737 * @param {Number} filter 27738 * @param {Number} wrap 27739 */ 27740 initFromData(data, w, h, filter, wrap) 27741 { 27742 if (!w || !h) this.#log.error("texture size is 0"); 27743 this.width = w; 27744 this.height = h; 27745 this.gpuTexture = this.#cgp.device.createTexture( 27746 { 27747 "size": [w, h], 27748 "format": "rgba8unorm", 27749 "usage": GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT, 27750 }); 27751 27752 this.#cgp.device.queue.writeTexture( 27753 { "texture": this.gpuTexture }, 27754 data, 27755 { "bytesPerRow": w * 4 }, 27756 { "width": w, "height": h }); 27757 } 27758 27759 /** 27760 * @param {any} v 27761 */ 27762 setWrap(v) 27763 { 27764 this.samplerDesc.addressModeU = this.samplerDesc.addressModeV = v; 27765 } 27766 27767 /** 27768 * @param {any} v 27769 */ 27770 setFilter(v) 27771 { 27772 this.samplerDesc.minFilter = this.samplerDesc.magFilter = v; 27773 } 27774} 27775 27776/** 27777 * @function load 27778 * @static 27779 * @memberof Texture 27780 * @description load an image from an url 27781 * @param {CgpContext} cgp 27782 * @param {String} url 27783 * @param {Function} onFinished 27784 * @param {Object} settings 27785 */ 27786Texture.load = function (cgp, url, onFinished, settings) 27787{ 27788 fetch(url).then((response) => 27789 { 27790 const texture = new Texture(cgp, { "name": url }); 27791 27792 response.blob().then((blob) => 27793 { 27794 createImageBitmap(blob).then((imgBitmap) => 27795 { 27796 texture.initTexture(imgBitmap); 27797 if (onFinished)onFinished(texture); 27798 else console.log("Texture.load no onFinished callback"); 27799 }).catch((err) => 27800 { 27801 if (onFinished)onFinished(cgp.getErrorTexture()); 27802 }); 27803 }); 27804 }); 27805}; 27806 27807;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_pipeline.js 27808/// <reference types="@webgpu/types" /> 27809 27810 27811 27812 27813class Pipeline 27814{ 27815 static TYPE_RENDER = 0; 27816 static TYPE_COMPUTE = 1; 27817 27818 #log = new logger["default"]("pipeline"); 27819 name = ""; 27820 27821 /** @type {CgpContext} */ 27822 #cgp = null; 27823 #isValid = true; 27824 27825 /** @type {string} */ 27826 presentationFormat = null; 27827 27828 /** @type {GPURenderPipelineDescriptor} */ 27829 #pipeCfg = null; 27830 27831 /** @type {GPUBindGroupLayout} */ 27832 bindGroupLayout = null; 27833 27834 /** @type {Array<string>} */ 27835 #shaderListeners = []; 27836 #type = -1; 27837 lastRebuildReason = "first"; 27838 rebuildCount = 0; 27839 profile = false; 27840 27841 /** @type {Array<GPUBindGroupLayoutEntry>} */ 27842 bindingGroupLayoutEntries = []; 27843 27844 /** 27845 * Description 27846 * @param {CgpContext} _cgp 27847 * @param {String} name 27848 * @param {Number} type 27849 */ 27850 constructor(_cgp, name, type = 0) 27851 { 27852 if (!_cgp) throw new Error("Pipeline constructed without cgp " + name); 27853 this.name = name; 27854 this.#cgp = _cgp; 27855 this.#type = type; 27856 27857 // this.#cgp.on("deviceChange", () => 27858 // { 27859 // this.#renderPipeline = null; 27860 // }); 27861 } 27862 27863 get passEncoder() 27864 { 27865 return this.#cgp.passEncoder; 27866 } 27867
27868 get log() 27869 { 27870 return this.#log; 27871 } 27872 27873 get cgp() 27874 { 27875 return this.#cgp; 27876 } 27877 27878 get isValid() { return this.#isValid; } 27879 27880 /** 27881 * @param {String} name 27882 */ 27883 setName(name) 27884 { 27885 this.name = name; 27886 } 27887 27888 // setShaderListener(oldShader, newShader) 27889 // { 27890 // for (let i = 0; i < this.#shaderListeners.length; i++) oldShader.off(this.#shaderListeners[i]); 27891 // this.#shaderListeners = []; 27892 // this.#shaderListeners.push( 27893 // newShader.on("compiled", (/** @type {string} */ reason) => 27894 // { 27895 // this.needsRebuildReason = "shader compiled: " + reason || "???"; 27896 // })); 27897 // } 27898 27899 getInfo() 27900 { 27901 const info = { 27902 "class": this.constructor.name, 27903 "name": this.name, 27904 "rebuildReason": this.lastRebuildReason, 27905 "rebuildCount": this.rebuildCount, 27906 // "numBindgroups": this.#bindingInstances.length, 27907 "bindingGroupLayoutEntries": this.bindingGroupLayoutEntries, 27908 }; 27909 27910 if (this.#type == Pipeline.TYPE_COMPUTE)info.type = "COMPUTE"; 27911 if (this.#type == Pipeline.TYPE_RENDER)info.type = "RENDER"; 27912 27913 return info; 27914 } 27915 27916 pushDebug() 27917 { 27918 this.#cgp.currentPipeDebug = 27919 { 27920 "name": this.name, 27921 "rebuildreason": this.lastRebuildReason, 27922 "rebuildCount": this.rebuildCount, 27923 "cfg": this.#pipeCfg, 27924 "bindingGroupLayoutEntries": this.bindingGroupLayoutEntries 27925 }; 27926 } 27927 27928 /** 27929 * @param {CgpShader} shader 27930 */ 27931 _bindUniforms(shader) 27932 { 27933 shader.bind(); 27934 } 27935 27936 dispose() 27937 { 27938 // todo... 27939 } 27940 27941} 27942 27943;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_renderpipeline.js 27944/// <reference types="@webgpu/types" /> 27945 27946 27947 27948 27949 27950class RenderPipeline extends Pipeline 27951{ 27952 static DEPTH_COMPARE_FUNCS_STRINGS = ["never", "less", "equal", "lessequal", "greater", "notequal", "greaterequal", "always"]; 27953 27954 #isValid = true; 27955 27956 /** @type {string} */ 27957 presentationFormat = null; 27958 27959 /** @type {GPURenderPipelineDescriptor} */ 27960 #pipeCfg = null; 27961 27962 /** @type {GPURenderPipeline} */ 27963 #renderPipeline = null; 27964 27965 /** @type {GPUBindGroupLayout} */ 27966 bindGroupLayout = null; 27967 27968 /** @type {GPURenderPassEncoder} */ 27969 #passEncoder; 27970 27971 // #shaderListeners = []; 27972 #old = {}; 27973 #type = RenderPipeline.TYPE_RENDER; 27974 lastRebuildReason = "first"; 27975 #rebuildNumBindingGroups = false; 27976 #compileCount = -1; 27977 27978 /** 27979 * Description 27980 * @param {CgpContext} _cgp 27981 * @param {String} name 27982 */ 27983 constructor(_cgp, name) 27984 { 27985 super(_cgp, name, Pipeline.TYPE_RENDER); 27986 } 27987 27988 /** 27989 * @param {CgpShader} shader 27990 * @param {CgpMesh} mesh 27991 */ 27992 setPipeline(shader, mesh = null) 27993 { 27994 if (this.#type == RenderPipeline.TYPE_RENDER) 27995 { 27996 if (!mesh) 27997 { 27998 this.log.log("pipeline unknown mesh"); 27999 return; 28000 } 28001 } 28002 if (!shader) 28003 { 28004 this.log.log("pipeline unknown shader"); 28005 return; 28006 } 28007 28008 if (this.cgp.branchProfiler) this.cgp.branchProfiler.push("setPipeline", this.name, { "info": this.getInfo(), "shader": shader.getInfo() }); 28009 28010 let needsRebuildReason = ""; 28011 if (!this.#renderPipeline) needsRebuildReason = "no renderpipeline"; 28012 if (!this.#pipeCfg)needsRebuildReason = "no pipecfg"; 28013 if (this.#old.mesh != mesh)needsRebuildReason = "no mesh"; 28014 if (this.#old.shader != shader) 28015 { 28016 // this.setShaderListener(this.#old.shader, shader); 28017 needsRebuildReason = "shader changed"; 28018 } 28019 28020 if (shader.needsPipelineUpdate) 28021 { 28022 needsRebuildReason = "shader needs update: " + shader.needsPipelineUpdate; 28023 shader.needsPipelineUpdate = ""; 28024 } 28025 28026 if (this.#type == RenderPipeline.TYPE_RENDER && mesh.needsPipelineUpdate) 28027 { 28028 needsRebuildReason = "mesh needs update"; 28029 mesh.needsPipelineUpdate = false;
28030 } 28031 28032 if (this.bindingGroupLayoutEntries.length != shader.defaultBindGroup.getLayoutEntries(shader).length) 28033 { 28034 needsRebuildReason = "num bindgroup layouts wrong..."; 28035 } 28036 28037 if (shader.bindingsNeedPipeUpdate()) 28038 { 28039 console.log("binding needs uptate"); 28040 needsRebuildReason = "bindings needs update"; 28041 this.needsRebuildBindgroup = true; 28042 } 28043 28044 // if (this.#rebuildNumBindingGroups) 28045 // { 28046 // needsRebuildReason = "num bindgroups wrong..."; 28047 // } 28048 28049 if (this.#pipeCfg) 28050 { 28051 this.#pipeCfg =/** @type {GPURenderPipelineDescriptor} */ (this.#pipeCfg || {}); 28052 if (this.#pipeCfg.depthStencil.depthWriteEnabled != this.cgp.stateDepthWrite()) 28053 needsRebuildReason = "depth changed"; 28054 28055 if (this.#pipeCfg.fragment.targets[0].blend != this.cgp.stateBlend()) 28056 { 28057 needsRebuildReason = "blend changed"; 28058 this.#pipeCfg.fragment.targets[0].blend = this.cgp.stateBlend(); 28059 } 28060 28061 if (this.#pipeCfg.depthStencil.depthCompare != this.cgp.getDepthCompare()) 28062 needsRebuildReason = "depth compare changed"; 28063 28064 if (this.#pipeCfg.primitive.cullMode != this.cgp.stateCullFaceFacing()) 28065 needsRebuildReason = "cullmode change"; 28066 28067 if (this.#pipeCfg.multisample.count != this.cgp.stateMultisampling()) 28068 needsRebuildReason = "multisample change"; 28069 28070 } 28071 if (this.#compileCount != shader.compileCount) 28072 { 28073 needsRebuildReason = "shader compiled " + shader.compileCount; 28074 } 28075 28076 this.pushDebug(); 28077 28078 if (needsRebuildReason != "") 28079 { 28080 this.cgp.profileData.addHeavyEvent("pipeline created", this.name, needsRebuildReason); 28081 this.lastRebuildReason = needsRebuildReason; 28082 this.rebuildCount++; 28083 this.cgp.pushErrorScope("createPipeline", { "logger": this.log }); 28084 28085 this.#rebuildNumBindingGroups = false; 28086 28087 this.#pipeCfg = this.getPipelineObject(shader); 28088 28089 this.#old.device = this.cgp.device; 28090 this.#old.shader = shader; 28091 this.#old.mesh = mesh; 28092 this.#isValid = true; 28093 this.#compileCount = shader.compileCount; 28094 shader.pipelineUpdated(); 28095 28096 try 28097 { 28098 28099 this.#renderPipeline = this.cgp.device.createRenderPipeline(this.#pipeCfg); 28100 28101 } 28102 catch (e) 28103 { 28104 28105 console.error("pipe error catch...", e.message, this.#pipeCfg); 28106 this.#isValid = false; 28107 } 28108 28109 this.cgp.popErrorScope( 28110 () => 28111 { 28112 console.log("this.#pipeCfg", this.#pipeCfg); 28113 }); 28114 } 28115 28116 if (this.#renderPipeline && this.#isValid) 28117 { 28118 this.cgp.pushErrorScope("setpipeline", { "logger": this.log }); 28119 28120 let passEnc = this.cgp.passEncoder; 28121 28122 // if (this.#type != RenderPipeline.TYPE_RENDER) passEnc = this.#passEncoder; 28123 28124 if (this.cgp.branchProfiler) this.cgp.branchProfiler.push("pipe updateUniforms", this.name, { "shader": shader.getInfo() }); 28125 28126 /// /////////////////// 28127 28128 shader.bind(); 28129 passEnc.setPipeline(this.#renderPipeline); 28130 28131 if (this.cgp.branchProfiler) this.cgp.branchProfiler.pop(); 28132 28133 this.cgp.popErrorScope(); 28134 } 28135 if (this.cgp.branchProfiler) this.cgp.branchProfiler.pop(); 28136 28137 } 28138 28139 /** 28140 * @param {CgpShader} shader 28141 * @returns {GPURenderPipelineDescriptor} 28142 */ 28143 getPipelineObject(shader) 28144 { 28145 28146 this.bindingGroupLayoutEntries = []; 28147 this.bindingGroupLayoutEntries = shader.defaultBindGroup.getLayoutEntries(shader); 28148 28149 const bindGroupLayouts = [shader.defaultBindGroup.getLayout(shader)]; 28150 28151 /** @type {GPUPipelineLayout} */ 28152 const pipelineLayout = this.cgp.device.createPipelineLayout({ 28153 "label": "pipe layout " + this.name, 28154 "bindGroupLayouts": bindGroupLayouts 28155 }); 28156 28157 /** @type {Array<GPUVertexBufferLayout>} */ 28158 let buffers = [ 28159 // position 28160 {
28161 "arrayStride": 3 * 4, // 3 floats, 4 bytes each 28162 "attributes": [ 28163 { "shaderLocation": 0, "offset": 0, "format": "float32x3" }, 28164 ], 28165 }, 28166 // texcoords 28167 { 28168 "arrayStride": 2 * 4, // 2 floats, 4 bytes each 28169 "attributes": [ 28170 { "shaderLocation": 2, "offset": 0, "format": "float32x2", }, 28171 ], 28172 }, 28173 // normals 28174 { 28175 "arrayStride": 3 * 4, // 3 floats, 4 bytes each 28176 "attributes": [ 28177 { "shaderLocation": 1, "offset": 0, "format": "float32x3" }, 28178 ], 28179 }]; 28180 28181 /** @type {GPURenderPipelineDescriptor} */ 28182 let pipeCfg = { 28183 "label": this.name, 28184 "layout": pipelineLayout, 28185 28186 "primitive": { 28187 "topology": "triangle-list", 28188 "cullMode": this.cgp.stateCullFaceFacing(), // back/none/front 28189 // "point-list", 28190 // "line-list", 28191 // "line-strip", 28192 // "triangle-list", 28193 // "triangle-strip" 28194 }, 28195 "multisample": { 28196 "count": this.cgp.stateMultisampling(), 28197 "alphaToCoverageEnabled": false // Enable if using alpha testing 28198 }, 28199 "depthStencil": { 28200 "depthWriteEnabled": this.cgp.stateDepthWrite(), 28201 "depthCompare": this.cgp.getDepthCompare(), 28202 "format": "depth24plus", 28203 28204 }, 28205 "vertex": 28206 { 28207 "module": shader.gpuShaderModule, 28208 "entryPoint": "myVSMain", 28209 "buffers": buffers 28210 }, 28211 "fragment": 28212 { 28213 "module": shader.gpuShaderModule, 28214 "entryPoint": "myFSMain", 28215 "targets": [ 28216 { 28217 "format": this.cgp.presentationFormat, 28218 "blend": this.cgp.stateBlend() 28219 }, 28220 ], 28221 } 28222 }; 28223 return pipeCfg; 28224 } 28225 28226 dispose() 28227 { 28228 // todo... 28229 } 28230 28231} 28232 28233// EXTERNAL MODULE: ./src/corelibs/cg/cg_mesh.js 28234var cg_mesh = __webpack_require__("./src/corelibs/cg/cg_mesh.js"); 28235;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_mesh.js 28236 28237 28238 28239 28240 28241class CgpMesh extends cg_mesh.CgMesh 28242{ 28243 #log = new logger["default"]("cgl_mesh"); 28244 needsPipelineUpdate = false; 28245 28246 /** 28247 * @param {any} _cgp 28248 * @param {any} __geom 28249 */ 28250 constructor(_cgp, __geom) 28251 { 28252 super(); 28253 28254 this.cgp = _cgp; 28255 this._geom = null; 28256 this.numIndex = 0; 28257 this.instances = 1; 28258 28259 this._pipe = new RenderPipeline(this.cgp, "pipe mesh " + __geom.name); 28260 this._numNonIndexed = 0; 28261 this._positionBuffer = null; 28262 28263 this._attributes = []; 28264 28265 if (__geom) this.setGeom(__geom); 28266 } 28267 28268 /** 28269 * @param {GPUDevice} device 28270 * @param {any} data 28271 * @param {any} usage 28272 */ 28273 _createBuffer(device, data, usage) 28274 { 28275 let bo = { 28276 "size": data.byteLength, 28277 "usage": usage, 28278 "mappedAtCreation": true, 28279 }; 28280 const buffer = device.createBuffer(bo); 28281 const dst = new data.constructor(buffer.getMappedRange()); 28282 dst.set(data); 28283 buffer.unmap(); 28284 return buffer; 28285 } 28286 28287 /** 28288 * @function setGeom 28289 * @memberof Mesh 28290 * @instance 28291 * @description set geometry for mesh 28292 * @param {Geometry} geom geometry 28293 */ 28294 setGeom(geom) 28295 { 28296 this.needsPipelineUpdate = true; 28297 this._geom = geom; 28298 this._disposeAttributes(); 28299 28300 this._positionBuffer = this._createBuffer(this.cgp.device, new Float32Array(geom.vertices), GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST); 28301 28302 let vi = geom.verticesIndices; 28303 if (!geom.isIndexed()) vi = Array.from(Array(geom.vertices.length / 3).keys()); 28304 this._numIndices = vi.length; 28305 this._indicesBuffer = this._createBuffer(this.cgp.device, new Uint32Array(vi), GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST); 28306 28307 if (geom.texCoords && geom.texCoords.length) this.setAttribute("texCoords", geom.texCoords, 2); 28308 if (geom.vertexNormals && geom.vertexNormals.length) this.setAttribute("normals", geom.vertexNormals, 3); 28309 28310 this.setAttribute("normals", geom.vertexNormals, 3); 28311 } 28312 28313 _disposeAttributes() 28314 { 28315 this.needsPipelineUpdate = true; 28316 for (let i = 0; i < this._attributes.length; i++) this._attributes[i].buffer.destroy(); 28317 this._attributes.length = 0; 28318 } 28319 28320 dispose() 28321 { 28322 this._disposeAttributes(); 28323 } 28324 28325 /** 28326 * @function setAttribute
28327 * @description update attribute 28328 * @memberof Mesh 28329 * @instance 28330 * @param {String} name attribute name 28331 * @param {Array} array data 28332 * @param {Number} itemSize 28333 * @param {Object} options 28334 */ 28335 setAttribute(name, array, itemSize, options = {}) 28336 { 28337 if (!array) 28338 { 28339 this.#log.error("mesh addAttribute - no array given! " + name); 28340 throw new Error(); 28341 } 28342 28343 let instanced = false; 28344 if (options.instanced) instanced = options.instanced; 28345 28346 const buffer = this._createBuffer(this.cgp.device, new Float32Array(array), GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST); 28347 28348 const attr = { 28349 "buffer": buffer, 28350 "name": name, 28351 "instanced": instanced, 28352 }; 28353 this._attributes.push(attr); 28354 28355 return attr; 28356 } 28357 28358 /** 28359 * @param {CgpShader} shader 28360 */ 28361 render(shader) 28362 { 28363 if (!this._positionBuffer) return; 28364 if (this.instances <= 0) return; 28365 28366 if (this.cgp.branchProfiler) this.cgp.branchProfiler.push("mesh.render()", "geom " + this._geom.name); 28367 28368 shader = shader || this.cgp.getShader(); 28369 if (shader)shader.bind(); 28370 28371 if (!shader || !shader.isValid) 28372 { 28373 // this.status = "shader invalid"; 28374 return; 28375 } 28376 28377 this._pipe.setName("mesh.render " + this._geom.name + " " + shader.getName() + " " + shader.id); 28378 this._pipe.setPipeline(shader, this); 28379 28380 if (this._pipe.isValid) 28381 { 28382 if (this.cgp.branchProfiler) this.cgp.branchProfiler.push("mesh.render().draw", "geom " + this._geom.name, { 28383 "geom": this._geom.getInfo(), 28384 "shader": shader.getInfo(), 28385 "numAttributes": this._attributes.length 28386 }); 28387 28388 this.cgp.passEncoder.setVertexBuffer(0, this._positionBuffer); 28389 for (let i = 0; i < this._attributes.length; i++) 28390 this.cgp.passEncoder.setVertexBuffer(i + 1, this._attributes[i].buffer); 28391 28392 this.cgp.passEncoder.setIndexBuffer(this._indicesBuffer, "uint32"); 28393 28394 this.cgp.profileData.count("draw mesh", this._name); 28395 if (this._numNonIndexed) 28396 this.cgp.passEncoder.draw(this._numIndices, this.instances); 28397 else 28398 this.cgp.passEncoder.drawIndexed(this._numIndices, this.instances); 28399 28400 if (this.cgp.branchProfiler) this.cgp.branchProfiler.pop(); 28401 } 28402 else 28403 { 28404 if (this.cgp.branchProfiler) 28405 { 28406 this.cgp.branchProfiler.push("mesh invalid pipeline ", "geom " + this._geom.name); 28407 this.cgp.branchProfiler.pop(); 28408 } 28409 } 28410 28411 if (this.cgp.branchProfiler) this.cgp.branchProfiler.pop(); 28412 28413 // if (shader)shader.unbind(); 28414 } 28415} 28416 28417;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_state.js 28418 28419 28420 28421 28422 28423 28424 28425 28426 28427// https://github.com/greggman/webgpu-utils 28428// https://developer.chrome.com/blog/from-webgl-to-webgpu/ 28429// https://gpuweb.github.io/gpuweb/explainer/ 28430 28431// eslint-disable-next-line no-restricted-syntax 28432const defaultShaderSrcVert = ` 28433struct MyVSInput 28434{ 28435 @location(0) position: vec3<f32>, 28436 @location(1) normal: vec3<f32>, 28437 @location(2) texcoord: vec2<f32>, 28438}; 28439 28440struct MyVSOutput 28441{ 28442 @builtin(position) position: vec4<f32>, 28443 @location(0) normal: vec3<f32>, 28444 @location(1) texcoord: vec2<f32>, 28445}; 28446 28447@vertex 28448fn myVSMain(v: MyVSInput) -> MyVSOutput 28449{ 28450 var vsOut: MyVSOutput; 28451 var pos =vec4<f32>(v.position, 1.0); 28452 28453 var mvMatrix=uniVert.viewMatrix * uniVert.modelMatrix; 28454 vsOut.position = uniVert.projMatrix * mvMatrix * pos; 28455 28456 vsOut.normal = v.normal; 28457 vsOut.texcoord = v.texcoord; 28458 return vsOut; 28459} 28460 28461@fragment 28462fn myFSMain(v: MyVSOutput) -> @location(0) vec4<f32> 28463{ 28464 return vec4<f32>(.5,.5,.5,1.0); 28465} 28466`; 28467 28468/** 28469 * cables webgpu context/state manager 28470 * @class 28471 * @namespace external:CGP 28472 * @hideconstructor 28473 */ 28474class CgpContext extends cg_context.CgContext 28475{ 28476 28477 branchProfiler = null; 28478 28479 /** 28480 * @param {Patch} _patch 28481 */ 28482 constructor(_patch) 28483 { 28484 super(_patch); 28485 this.patch = _patch; 28486 28487 this.lastErrorMsg = ""; 28488 28489 this._log = new logger["default"]("WebGpuContext"); 28490 this.gApi = cg_context.CgContext.API_WEBGPU; 28491 this._viewport = [0, 0, 256, 256]; 28492 this._shaderStack = []; 28493 this._simpleShader = null; 28494 this.frame = 0; 28495 this.catchErrors = true; 28496 28497 this._stackCullFaceFacing = []; 28498 this._stackDepthTest = []; 28499 this._stackCullFace = []; 28500 this._stackDepthFunc = []; 28501 this._stackDepthWrite = []; 28502 this._stackErrorScope = []; 28503 this._stackBlend = []; 28504 this._stackErrorScopeLogs = []; 28505 this._stackMultisampling = []; 28506 28507 this.currentPipeDebug = null; 28508 this.canvasAttachments = []; 28509 28510 /** @type {GPUDevice} */ 28511 this.device = null; 28512 28513 /** @type {GPURenderPassEncoder} */ 28514 this.passEncoder = null; 28515 28516 this._defaultBlend = { 28517 "color": { 28518 "operation": "add", 28519 "srcFactor": "one", 28520 "dstFactor": "zero", 28521 }, 28522 "alpha": { 28523 "operation": "add", 28524 "srcFactor": "one", 28525 "dstFactor": "zero", 28526 }, 28527 }; 28528 28529 this.DEPTH_FUNCS = [ 28530 "never", 28531 "always", 28532 "less", 28533 "less-equal", 28534 "greater", 28535 "greater-equal", 28536 "equal", 28537 "not-equal" 28538 ]; 28539 28540 this.CULL_MODES = [ 28541 "none", 28542 "back", 28543 "front", 28544 "none" // both does not exist in webgpu 28545 ]; 28546 28547 /** @type {GPUTextureFormat} */ 28548 this.presentationFormat = "bgra8unorm"; 28549 } 28550 28551 get supported() 28552 { 28553 return !!navigator.gpu; 28554 } 28555 28556 /// //////////////////// 28557 28558 /** 28559 * Description 28560 * @param {any} cgp 28561 * @param {any} identTranslate 28562 * @param {any} identTranslateView 28563 * @returns {any} 28564 */ 28565 renderStart(cgp, identTranslate, identTranslateView) 28566 { 28567 28568 this.frame++; 28569 this.pushErrorScope("cgpstate internal", { "scope": "internal" }); 28570 this.pushErrorScope("cgpstate out-of-memory", { "scope": "out-of-memory" }); 28571 28572 if (!this._simpleShader) 28573 { 28574 this._simpleShader = new CgpShader(this, "simple default shader"); 28575 this._simpleShader.setSource(defaultShaderSrcVert); 28576 28577 this._simpleShader.addUniform(new CgpUniform(this._simpleShader, "4f", "color", [1, 1, 0, 1]), GPUShaderStage.FRAGMENT); 28578 } 28579 28580 this.fpsCounter.startFrame(); 28581 28582 this._startMatrixStacks(identTranslate, identTranslateView); 28583 this.setViewPort(0, 0, this.canvasWidth, this.canvasHeight); 28584 28585 this.pushShader(this._simpleShader); 28586 this.pushDepthTest(true); 28587 this.pushDepthWrite(true); 28588 this.pushDepthFunc("less-equal"); 28589
28590 this.pushBlend(this._defaultBlend); 28591 28592 this._execOneTimeCallbacks(); 28593 28594 this.emitEvent("beginFrame"); 28595 } 28596 28597 renderEnd() 28598 { 28599 this._endMatrixStacks(); 28600 28601 this.popShader(); 28602 this.popDepthFunc(); 28603 this.popDepthWrite(); 28604 this.popDepthTest(); 28605 28606 this.popErrorScope(); 28607 this.popErrorScope(); 28608 28609 if (this._stackErrorScope.length > 0)console.log("error scope stack length invalid..."); 28610 this._stackErrorScope.length = 0; 28611 28612 this.emitEvent("endFrame"); 28613 this.fpsCounter.endFrame(); 28614 } 28615 28616 /** 28617 * @param {number} x 28618 * @param {number} [y] 28619 * @param {undefined} [w] 28620 * @param {undefined} [h] 28621 */ 28622 setViewPort(x, y, w, h) 28623 { 28624 this._viewport = [x, y, w, h]; 28625 } 28626 28627 /** 28628 * @function getViewPort 28629 * @memberof Context 28630 * @instance 28631 * @description get current gl viewport 28632 * @returns {Array} array [x,y,w,h] 28633 */ 28634 getViewPort() 28635 { 28636 return this._viewPort; 28637 } 28638 28639 /** 28640 * @param {Geometry} geom 28641 * @param {any} glPrimitive 28642 * @returns {CgpMesh} 28643 */ 28644 createMesh(geom, glPrimitive) 28645 { 28646 return new CgpMesh(this, geom); 28647 } 28648 28649 /** 28650 * @function popViewPort 28651 * @memberof Context 28652 * @instance 28653 * @description pop viewPort stack 28654 */ 28655 popViewPort() 28656 { 28657 this._viewPortStack.pop(); 28658 28659 if (this._viewPortStack.length == 0) 28660 this._viewPort = [0, 0, this.canvasWidth, this.canvasHeight]; 28661 else 28662 this.setViewPort(this._viewPortStack[this._viewPort.length - 1]); 28663 } 28664 28665 /** 28666 * @function pushViewPort 28667 * @memberof Context 28668 * @instance 28669 * @description push a new viewport onto stack 28670 * @param {Number} x 28671 * @param {Number} y 28672 * @param {Number} w 28673 * @param {Number} h 28674 */ 28675 28676 pushViewPort(x, y, w, h) 28677 { 28678 this._viewPortStack.push([x, y, w, h]); 28679 this._viewPort = [x, y, w, h]; 28680 } 28681 28682 /** 28683 * push a shader to the shader stack 28684 * @function pushShader 28685 * @memberof Context 28686 * @instance 28687 * @param {Object} shader 28688 * @function 28689 */ 28690 pushShader(shader) 28691 { 28692 this._shaderStack.push(shader); 28693 // currentShader = shader; 28694 } 28695 28696 /** 28697 * pop current used shader from shader stack 28698 * @function popShader 28699 * @memberof Context 28700 * @instance 28701 * @function 28702 */ 28703 popShader() 28704 { 28705 if (this._shaderStack.length === 0) throw new Error("Invalid shader stack pop!"); 28706 this._shaderStack.pop(); 28707 // currentShader = this._shaderStack[this._shaderStack.length - 1]; 28708 } 28709 28710 getShader() 28711 { 28712 return this._shaderStack[this._shaderStack.length - 1]; 28713 } 28714 28715 /** 28716 * @param {GPUDevice} device 28717 */ 28718 setDevice(device) 28719 { 28720 this.device = device; 28721 28722 if (this._emptyTexture) this._emptyTexture = this._emptyTexture.dispose(); 28723 if (this._defaultTexture) this._defaultTexture = this._defaultTexture.dispose(); 28724 if (this._errorTexture) this._errorTexture = this._errorTexture.dispose(); 28725 28726 this.emitEvent("deviceChange"); 28727 } 28728 28729 /** 28730 * @typedef ErrorScopeOptions 28731 * @property {Logger} [logger] 28732 * @property {GPUErrorFilter} [scope] 28733 */ 28734 28735 /** 28736 * @param {String} name 28737 * @param {ErrorScopeOptions} options 28738 */ 28739 pushErrorScope(name, options = { }) 28740 { 28741 if (this.catchErrors) 28742 { 28743 this._stackErrorScope.push(name); 28744 this._stackErrorScopeLogs.push(options.logger || null); 28745 this.device.pushErrorScope(options.scope || "validation"); 28746 } 28747 } 28748 28749 /** 28750 * @param {Function} [cb] 28751 */ 28752 popErrorScope(cb) 28753 { 28754 if (this.catchErrors) 28755 { 28756 const name = this._stackErrorScope.pop(); 28757 const logger = this._stackErrorScopeLogs.pop(); 28758 this.device.popErrorScope().then((error) => 28759 { 28760 if (error) 28761 { 28762 if (this.lastErrorMsg == error.message) 28763 { 28764 // this._log.warn("last error once more..."); 28765 } 28766 else 28767 { 28768 (logger || this._log).error(error.constructor.name, "in ERROR SCOPE:", name); 28769 (logger || this._log).error(error.message); 28770 } 28771 this.lastErrorMsg = error.message; 28772 28773 if (cb)cb(error); 28774 } 28775 }); 28776 } 28777 } 28778 28779 /** 28780 * push depth testing enabled state 28781 * @function pushDepthTest 28782 * @param {Boolean} b enabled 28783 * @memberof Context 28784 * @instance 28785 */ 28786 pushDepthTest(b) 28787 { 28788 this._stackDepthTest.push(b); 28789 } 28790 28791 getDepthCompare() 28792 { 28793 let depthComp = this.stateDepthFunc(); 28794 if (!this.stateDepthTest())depthComp = "always"; 28795 return depthComp; 28796 } 28797 28798 /** 28799 * current state of depth testing 28800 * @function stateDepthTest 28801 * @returns {Boolean} enabled 28802 * @memberof Context 28803 * @instance 28804 */ 28805 stateDepthTest() 28806 { 28807 return this._stackDepthTest[this._stackDepthTest.length - 1]; 28808 } 28809 28810 /** 28811 * pop depth testing state 28812 * @function popDepthTest 28813 * @memberof Context 28814 * @instance 28815 */ 28816 popDepthTest() 28817 { 28818 this._stackDepthTest.pop(); 28819 } 28820 28821 // -------------------------------------- 28822 // state depthwrite 28823 28824 /** 28825 * push depth write enabled state 28826 * @function pushDepthWrite 28827 * @param {Boolean} b enabled 28828 * @memberof Context 28829 * @instance 28830 */ 28831 pushDepthWrite(b) 28832 { 28833 b = b || false; 28834 this._stackDepthWrite.push(b); 28835 } 28836 28837 /** 28838 * current state of depth writing 28839 * @returns {Boolean} enabled 28840 * @memberof Context 28841 * @instance 28842 */ 28843 stateDepthWrite() 28844 { 28845 return this._stackDepthWrite[this._stackDepthWrite.length - 1]; 28846 } 28847 28848 /** 28849 * pop depth writing state 28850 * @memberof Context 28851 * @instance 28852 */ 28853 popDepthWrite() 28854 { 28855 this._stackDepthWrite.pop(); 28856 } 28857 28858 // -------------------------------------- 28859 // state depthfunc 28860 28861 /** 28862 * @function pushDepthFunc 28863 * @memberof Context 28864 * @instance 28865 * @param {GPUCompareFunction} depthFunc depth compare func 28866 */ 28867 pushDepthFunc(depthFunc) 28868 { 28869 this._stackDepthFunc.push(depthFunc); 28870 } 28871 28872 /** 28873 * @function stateDepthFunc 28874 * @memberof Context 28875 * @instance 28876 * @returns {GPUCompareFunction} 28877 */ 28878 stateDepthFunc() 28879 { 28880 if (this._stackDepthFunc.length > 0) return this._stackDepthFunc[this._stackDepthFunc.length - 1]; 28881 return "less"; 28882 } 28883 28884 /** 28885 * pop depth compare func 28886 * @function popDepthFunc 28887 * @memberof Context 28888 * @instance 28889 */ 28890 popDepthFunc() 28891 { 28892 this._stackDepthFunc.pop(); 28893 } 28894 28895 // -------------------------------------- 28896 // state CullFace 28897 28898 /** 28899 * push face culling face enabled state 28900 * @function pushCullFace 28901 * @param {Boolean} b enabled 28902 * @memberof Context 28903 * @instance 28904 */ 28905 pushCullFace(b) 28906 { 28907 this._stackCullFace.push(b); 28908 } 28909 28910 // -------------------------------------- 28911 // state multisambling 28912 /** 28913 * @returns {number} 28914 */ 28915 stateMultisampling() 28916 { 28917 return this._stackMultisampling[this._stackMultisampling.length - 1]; 28918 } 28919 28920 /** 28921 * @param {number} samples 28922 */ 28923 pushMultisampling(samples) 28924 { 28925 this._stackMultisampling.push(samples); 28926 } 28927 28928 popMultisampling() 28929 { 28930 this._stackMultisampling.pop(); 28931 } 28932 28933 // -------------------------------------- 28934 // state CullFace Facing 28935 28936 /** 28937 * push face culling face side 28938 * @param {string} b 28939 * @instance 28940 */ 28941 pushCullFaceFacing(b) 28942 { 28943 this._stackCullFaceFacing.push(b); 28944 } 28945 28946 /** 28947 * current state of face culling side 28948 * @returns {string} 28949 */ 28950 stateCullFaceFacing() 28951 { 28952 return this._stackCullFaceFacing[this._stackCullFaceFacing.length - 1]; 28953 } 28954 28955 /** 28956 * pop face culling face side 28957 * @function popCullFaceFacing 28958 * @memberof Context 28959 * @instance 28960 */ 28961 popCullFaceFacing() 28962 { 28963 this._stackCullFaceFacing.pop(); 28964 } 28965 28966 pushBlend(b) 28967 { 28968 this._stackBlend.push(b); 28969 } 28970 28971 popBlend() 28972 { 28973 this._stackBlend.pop(); 28974 } 28975 28976 /** 28977 * @returns {GPUBlendComponent} 28978 */ 28979 stateBlend() 28980 { 28981 return this._stackBlend[this._stackBlend.length - 1]; 28982 } 28983 28984 getEmptyTexture() 28985 { 28986 if (this._emptyTexture) return this._emptyTexture; 28987 const size = 8; 28988 this._emptyTexture = new Texture(this, {}); 28989 this._emptyTexture.initFromData(cg_texture.CgTexture.getDefaultTextureData("empty", size), size, size); 28990 return this._emptyTexture; 28991 } 28992 28993 getErrorTexture() 28994 { 28995 // if (this._errorTexture) return this._errorTexture; 28996 const size = 256; 28997 this._errorTexture = new Texture(this, {}); 28998 this._errorTexture.initFromData(cg_texture.CgTexture.getDefaultTextureData("stripes", size, { "r": 1, "g": 0, "b": 0 }), size, size); 28999 return this._errorTexture; 29000 } 29001 29002 getDefaultTexture() 29003 { 29004 if (this._defaultTexture) return this._defaultTexture; 29005 const size = 256; 29006 this._defaultTexture = new Texture(this, {}); 29007 this._defaultTexture.initFromData(cg_texture.CgTexture.getDefaultTextureData("stripes", size), size, size); 29008 return this._defaultTexture; 29009 } 29010 29011 /** 29012 * @param {function} cb 29013 * @param {boolean} _doScreenshotClearAlpha 29014 * @param {string} mimeType 29015 * @param {number} quality 29016 */
29017 screenShot(cb, _doScreenshotClearAlpha, mimeType, quality) 29018 { 29019 if (this.canvas && this.canvas.toBlob) 29020 { 29021 this.canvas.toBlob((blob) => 29022 { 29023 if (cb) cb(blob); 29024 else this._log.log("no screenshot callback..."); 29025 }, mimeType, quality); 29026 } 29027 29028 } 29029 29030} 29031 29032// EXTERNAL MODULE: ./src/corelibs/cgl/cgl_simplerect.js 29033var cgl_simplerect = __webpack_require__("./src/corelibs/cgl/cgl_simplerect.js"); 29034;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_canvasattachment.js 29035 29036 29037class WebGpuCanvasAttachment 29038{ 29039 29040 /** @type {HTMLCanvasElement} */ 29041 #canvas = null; 29042 29043 /** @type {CgpContext} */ 29044 #cgp = null; 29045 29046 /** @type {GPUCanvasContext} */ 29047 #ctx = null; 29048 29049 /** 29050 * @param {CgpContext} cgp 29051 */ 29052 constructor(cgp) 29053 { 29054 this.#cgp = cgp; 29055 this.#canvas = document.createElement("canvas"); 29056 this.#canvas.id = "webgpucanvasOut"; 29057 this.#canvas.style.width = 128 + "px"; 29058 this.#canvas.style.height = 128 + "px"; 29059 } 29060 29061 get canvas() 29062 { 29063 return this.#canvas; 29064 } 29065 29066 /** 29067 * @param {function} cb 29068 */ 29069 render(cb) 29070 { 29071 29072 const canvas = this.#cgp.canvas; 29073 if (this.#canvas.width != canvas.width || this.#canvas.height != canvas.height) 29074 { 29075 this.#canvas.style.width = canvas.width + "px"; 29076 this.#canvas.style.height = canvas.height + "px"; 29077 this.#canvas.width = canvas.width; 29078 this.#canvas.height = canvas.height; 29079 } 29080 29081 if (!this.#ctx) 29082 { 29083 this.#ctx = this.#canvas.getContext("webgpu"); 29084 29085 if (!this.#ctx) 29086 return console.log("no context", this.#canvas, this.#ctx); 29087 this.#ctx.configure({ 29088 "device": this.#cgp.device, 29089 "format": this.#cgp.presentationFormat 29090 }); 29091 29092 } 29093 29094 // const cgp = this.#cgp; 29095 // cgp.canvasInfo.depthTextureView = this.#ctx.createView(); 29096 29097 this.#cgp.renderPassDescriptor = { 29098 "label": "preview renderpass", 29099 "colorAttachments": [ 29100 { 29101 "view": this.#ctx.getCurrentTexture().createView(), 29102 "loadOp": "clear", 29103 "storeOp": "store", 29104 }, 29105 29106 ], 29107 "depthStencilAttachment": { 29108 "view": this.#cgp.canvasInfo.depthTextureView, 29109 "depthClearValue": 1, 29110 "depthLoadOp": "clear", 29111 "depthStoreOp": "store", 29112 }, 29113 }; 29114 29115 // make a render pass encoder to encode render specific commands 29116 this.#cgp.passEncoder = this.#cgp.commandEncoder.beginRenderPass(this.#cgp.renderPassDescriptor); 29117 this.#cgp.textureView = this.#ctx.getCurrentTexture().createView(); 29118 this.#cgp.renderStart(); 29119 29120 cb(); 29121 29122 this.#cgp.tempPrevCanvas = this.#canvas; 29123 29124 this.#cgp.renderEnd(); 29125 this.#cgp.passEncoder.end(); 29126 29127 } 29128 29129} 29130 29131;// CONCATENATED MODULE: ./src/corelibs/cgp/binding/binding_storagebuffer.js 29132 29133 29134 29135 29136 29137/** @extends Binding */ 29138class BindingStorage extends Binding 29139{ 29140 29141 /** @type {CgpGguBuffer} */ 29142 cgpbuffer = null; 29143 bindingType = "read-only-storage"; 29144 29145 /** 29146 * Description 29147 * @param {CgpContext} cgp 29148 * @param {string} name 29149 * @param {object} options 29150 */ 29151 constructor(cgp, name, options) 29152 { 29153 super(cgp, name, options); 29154 this.cgpbuffer = options.cgpBuffer || new CgpGguBuffer(cgp, "temp", [0, 0, 0, 0]); 29155 } 29156 29157 copy() 29158 { 29159 const b = new BindingStorage(this.cgp, this.name, this.options); 29160 return b; 29161 } 29162 29163 /** 29164 * @returns {GPUBindingResource} 29165 * @param {number} _inst 29166 */ 29167 getResource(_inst) 29168 { 29169 return { 29170 "buffer": this.cgpbuffer.gpuBuffer, 29171 }; 29172 } 29173 29174 /** 29175 * @returns {GPUBindGroupLayoutEntry} 29176 * @param {CgpShader} [_shader] 29177 */ 29178 getLayoutEntry(_shader = null) 29179 { 29180 29181 /** @type {GPUBufferBindingType} */ 29182 let access = "read-only-storage"; 29183 29184 if (this.stage & GPUShaderStage.COMPUTE) 29185 if (this.cgpbuffer.hasUsage(GPUBufferUsage.COPY_SRC) && this.cgpbuffer.hasUsage(GPUBufferUsage.COPY_DST)) access = "storage"; 29186 // else if (this.cgpbuffer.hasUsage(GPUBufferUsage.COPY_DST)) access = "write-only-storage"; 29187 29188 return { 29189 "visibility": this.stage, 29190 "binding": this.bindNum,
29191 // "minBindingSize": this.getSizeBytes(), 29192 // "hasDynamicOffset": 0, 29193 "buffer": { 29194 "type": access 29195 } }; 29196 } 29197 29198 /** 29199 * @param {CgpShader} _shader 29200 * @param {number} bindGroupNum 29201 */ 29202 getShaderHeaderCode(_shader, bindGroupNum) 29203 { 29204 this.cgp.profileData.count("shadercode storage", this.name); 29205 let str = ""; 29206 29207 let access = "read"; 29208 29209 if (this.stage & GPUShaderStage.COMPUTE) 29210 if (this.cgpbuffer.hasUsage(GPUBufferUsage.COPY_SRC) && this.cgpbuffer.hasUsage(GPUBufferUsage.COPY_DST)) access = "read_write"; 29211 else if (this.cgpbuffer.hasUsage(GPUBufferUsage.COPY_DST)) access = "write"; 29212 29213 str += "@group(" + bindGroupNum + ") "; 29214 str += "@binding(" + this.bindNum + ") "; 29215 29216 str += "var<storage," + access + "> "; 29217 let typeStr = "array<f32>"; 29218 str += this.name + ": " + typeStr + ";\n"; 29219 29220 return str + "\n"; 29221 } 29222} 29223 29224;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_computepipeline.js 29225/// <reference types="@webgpu/types" /> 29226 29227 29228 29229 29230 29231class ComputePipeline extends Pipeline 29232{ 29233 29234 #isValid = true; 29235 29236 /** @type {string} */ 29237 presentationFormat = null; 29238 29239 /** @type {GPUComputePipelineDescriptor} */ 29240 #pipeCfg = null; 29241 29242 /** @type {GPUComputePipeline} */ 29243 #computePipeline = null; 29244 29245 /** @type {GPUBindGroupLayout} */ 29246 bindGroupLayout = null; 29247 29248 /** @type {GPUComputePassEncoder} */ 29249 #computePassEncoder; 29250 29251 #shaderListeners = []; 29252 #old = {}; 29253 #errorCount = 0; 29254 lastRebuildReason = "first"; 29255 rebuildCount = 0; 29256 profile = false; 29257 #rebuildNumBindingGroups = false; 29258 29259 /** 29260 * Description 29261 * @param {CgpContext} _cgp 29262 * @param {String} name 29263 */ 29264 constructor(_cgp, name) 29265 { 29266 super(_cgp, name, Pipeline.TYPE_COMPUTE); 29267 } 29268 29269 /** 29270 * @param {CgpShader} shader 29271 * @param {CgpMesh} mesh 29272 */ 29273 setPipeline(shader, mesh = null) 29274 { 29275 if (!shader) 29276 { 29277 this.log.log("pipeline unknown shader"); 29278 return; 29279 } 29280 29281 let needsRebuildReason = ""; 29282 if (!this.#pipeCfg)needsRebuildReason = "no pipecfg"; 29283 if (this.#old.mesh != mesh)needsRebuildReason = "no mesh"; 29284 if (this.#old.shader != shader) 29285 { 29286 needsRebuildReason = "shader changed"; 29287 } 29288 29289 if (shader.needsPipelineUpdate) 29290 { 29291 needsRebuildReason = "shader needs update: " + shader.needsPipelineUpdate; 29292 shader.needsPipelineUpdate = ""; 29293 } 29294 29295 if (this.#rebuildNumBindingGroups) 29296 { 29297 needsRebuildReason = "num bindgroups wrong..."; 29298 } 29299 29300 this.pushDebug(); 29301 29302 if (needsRebuildReason != "") 29303 { 29304 this.cgp.profileData.count("pipeline created", this.name); 29305 29306 this.lastRebuildReason = needsRebuildReason; 29307 this.rebuildCount++; 29308 // console.log("needsRebuildReason"); 29309 this.cgp.pushErrorScope("createPipeline", { "logger": this.log }); 29310 29311 this.#rebuildNumBindingGroups = false; 29312 29313 this.#pipeCfg = this.getPipelineObject(shader); 29314 console.log(this.#pipeCfg); 29315 29316 this.#old.device = this.cgp.device; 29317 this.#old.shader = shader; 29318 this.#old.mesh = mesh; 29319 this.#isValid = true; 29320 console.log(this.#pipeCfg); 29321 try 29322 { 29323 this.#computePipeline = this.cgp.device.createComputePipeline(this.#pipeCfg); 29324 } 29325 catch (e) 29326 { 29327 console.error("pipe error catch...", e.message, this.#pipeCfg); 29328 this.#isValid = false; 29329 } 29330 29331 this.cgp.popErrorScope( 29332 () => 29333 { 29334 console.log("this.#pipeCfg", this.#pipeCfg); 29335 }); 29336 } 29337 29338 if (this.cgp.branchProfiler) this.cgp.branchProfiler.pop(); 29339 29340 } 29341 29342 /** 29343 * @param {CgpShader} shader 29344 * @returns {GPUComputePipelineDescriptor} 29345 */ 29346 getPipelineObject(shader) 29347 { 29348 29349 /** @type {Array<GPUBindGroupLayoutEntry>} */ 29350 this.bindingGroupLayoutEntries = []; 29351 this.bindingGroupLayoutEntries = shader.defaultBindGroup.getLayoutEntries(shader); 29352 29353 const bindGroupLayouts = [shader.defaultBindGroup.getLayout(shader)]; 29354 29355 /** @type {GPUPipelineLayout} */ 29356 const pipelineLayout = this.cgp.device.createPipelineLayout({ 29357 "label": "pipe layout " + this.name, 29358 "bindGroupLayouts": bindGroupLayouts 29359 }); 29360 29361 /** @type {GPUComputePipelineDescriptor} */ 29362 let pipeCfg = { 29363 "label": this.name, 29364 "layout": pipelineLayout, 29365 "compute": 29366 { 29367 "module": shader.gpuShaderModule, 29368 "entryPoint": shader.options.entryPoint || "main" 29369 } 29370 }; 29371 console.log("pipecft", pipeCfg, bindGroupLayouts); 29372 29373 return pipeCfg; 29374 } 29375 29376 /** 29377 * @param {CgpShader} shader 29378 * @param {Array} workGroups 29379 */ 29380 compute(shader, workGroups = [8, 8]) 29381 { 29382 if (!shader.gpuShaderModule) shader.compile(); 29383 29384 /** @type {GPUCommandEncoder} */ 29385 const commandEncoder = this.cgp.device.createCommandEncoder(); 29386 29387 this.#computePassEncoder = commandEncoder.beginComputePass({ "label": "computepass " + shader.getName() }); 29388 29389 // if (!this.#computePipeline) 29390 this.setPipeline(shader); 29391 29392 if (!this.#computePipeline) 29393 { 29394 this.log.warn("no render pipe"); 29395 return; 29396 } 29397 29398 this.#computePassEncoder.setPipeline(this.#computePipeline); 29399 shader.bind(this.#computePassEncoder); 29400 29401 if (workGroups.length == 1) this.#computePassEncoder.dispatchWorkgroups(workGroups[0] || 8); 29402 else if (workGroups.length == 2) this.#computePassEncoder.dispatchWorkgroups(workGroups[0] || 8, workGroups[1] || 8); 29403 else if (workGroups.length == 3) this.#computePassEncoder.dispatchWorkgroups(workGroups[0] || 8, workGroups[1] || 8, workGroups[2] || 8);
29404 else console.log("workgroups length wrong,,,"); 29405 29406 this.#computePassEncoder.end(); 29407 29408 this.cgp.profileData.count("compute pipe", this.name); 29409 // console.log("llllllll", shader.defaultBindGroup.getLayout()); 29410 const gpuCommands = commandEncoder.finish(); 29411 this.cgp.device.queue.submit([gpuCommands]); 29412 this.pushDebug(); 29413 // const entry = shader.bindingsVert[i].getBindingGroupEntry(shader.bindingCounter); 29414 // this._passEncoder = commandEncoder.beginComputePass(); 29415 // this._passEncoder.setPipeline(computePipeline); 29416 // this.#passEncoder.setBindGroup(0, shader.defaultBindGroupshader.defaultBindGroup; 29417 // outBuff.setRef(gpuBuff); 29418 29419 } 29420 29421 dispose() 29422 { 29423 // todo... 29424 } 29425 29426} 29427 29428;// CONCATENATED MODULE: ./src/corelibs/cgp/cgp_shadermodifier.js 29429 29430 29431 29432 29433 29434/** 29435 * @typedef UniformDescrip 29436 * @property {string} name 29437 * @property {string} type 29438 * @property {number} stage 29439 * @property {any} v1 29440 * @property {any} v2 29441 * @property {any} v3 29442 * @property {any} v4 29443 */ 29444 29445class ShaderModifier 29446{ 29447 onBind = null; 29448 29449 /** 29450 * @param {CgpContext} cgl 29451 * @param {string} name 29452 * @param {object} options 29453 */ 29454 constructor(cgl, name, options) 29455 { 29456 29457 /** @type {CgpContext} */ 29458 this._cgl = cgl; 29459 this._name = name; 29460 this._origShaders = {}; 29461 29462 /** @type {Array<UniformDescrip>} */ 29463 this._uniforms = []; 29464 this._structUniforms = []; 29465 this._definesToggled = {}; 29466 this._defines = {}; 29467 this._mods = []; 29468 this._textures = []; 29469 29470 /** @type {object} */ 29471 this._boundShader = null; 29472 this._changedDefines = true; 29473 this._changedUniforms = true; 29474 this._modulesChanged = false; 29475 this.needsTexturePush = false; 29476 29477 /** @type {CgpShader} */ 29478 this._lastShader = null; 29479 this._attributes = []; 29480 if (options && options.opId) this.opId = options.opId; 29481 29482 } 29483 29484 /** 29485 * @param {CgpShader} curShader 29486 * @param {boolean} pushShader 29487 */ 29488 bind(curShader, pushShader = true) 29489 { 29490 const shader = curShader || this._cgl.getShader(); 29491 if (!shader) return; 29492 29493 this._boundShader = this._origShaders[shader.id]; 29494 let missingMod = false; 29495 29496 if (this._boundShader && this._lastShader != this._boundShader.shader) // shader changed since last bind 29497 { 29498 if (!this._boundShader.shader.hasModule(this._mods[0].id)) missingMod = true; 29499 } 29500 29501 if (missingMod) console.warn("copy because (missingMod)"); 29502 if (!this._boundShader) console.warn("copy because (!this._boundShader)"); 29503 else if (shader.lastCompile != this._boundShader.lastCompile) console.warn("copy because shader.lastCompile"); 29504 if (this._modulesChanged) console.warn("copy because this._modulesChanged"); 29505 if (shader._needsRecompile) console.warn("copy because shader._needsRecompile ", shader._compileReason); 29506 29507 if (missingMod || !this._boundShader || shader.lastCompile != this._boundShader.lastCompile || this._modulesChanged || shader._needsRecompile) 29508 { 29509 if (this._boundShader) this._boundShader.shader.dispose(); 29510 if (shader._needsRecompile) shader.compile(); 29511 this.needsTexturePush = true; 29512 29513 this._boundShader = this._origShaders[shader.id] = 29514 { 29515 "lastCompile": shader.lastCompile, 29516 "orig": shader, 29517 "shader": shader.copy() 29518 }; 29519 29520 console.log("mod shaderrrrrrrrrrr", shader.getName(), this._boundShader.shader.getName()); 29521 29522 this._addModulesToShader(this._boundShader.shader); 29523 this._updateDefinesShader(this._boundShader.shader); 29524 this._updateUniformsShader(this._boundShader.shader); 29525 } 29526 29527 this._boundShader.wireframe = shader.wireframe; 29528 if (this._changedDefines) this._updateDefines(); 29529 if (this._changedUniforms) this._updateUniforms(); 29530 29531 if (pushShader) 29532 { 29533 this._cgl.pushShader(this._boundShader.shader); 29534 // console.log(this._boundShader.shader.id); 29535 } 29536 29537 // this._boundShader.shader.copyUniformValues(this._boundShader.orig); 29538 29539 if (this.needsTexturePush) 29540 { 29541 for (let j = 0; j < this._textures.length; j++) 29542 { 29543 const uniformName = this._textures[j][0]; 29544 const tex = this._textures[j][1]; 29545 const texType = this._textures[j][2]; 29546 29547 if (this._getUniform(uniformName)) 29548 { 29549 const name = this.getPrefixedName(uniformName); 29550 const uni = this._boundShader.shader.getUniform(name); 29551 29552 if (uni) this._boundShader.shader.pushTexture(uni, tex, texType); 29553 } 29554 } 29555 29556 this.needsTexturePush = false;
29557 this._textures.length = 0; 29558 } 29559 29560 this._modulesChanged = false; 29561 29562 this._boundShader.shader.fromMod = this; 29563 29564 if (this.onBind) this.onBind(this._boundShader.shader); 29565 29566 return this._boundShader.shader; 29567 } 29568 29569 /** 29570 * @param {boolean} popShader 29571 */ 29572 unbind(popShader = true) 29573 { 29574 if (this._boundShader) 29575 if (popShader) this._cgl.popShader(); 29576 29577 this._boundShader = null; 29578 } 29579 29580 /** 29581 * @param {CgpShader} shader 29582 */ 29583 _addModulesToShader(shader) 29584 { 29585 let firstMod; 29586 29587 if (this._mods.length > 1) firstMod = this._mods[0]; 29588 29589 for (let i = 0; i < this._mods.length; i++) shader.addModule(this._mods[i], firstMod); 29590 } 29591 29592 /** 29593 * @param {import("../cg/cg_shader.js").ShaderModule} mod 29594 */ 29595 _removeModulesFromShader(mod) 29596 { 29597 for (const j in this._origShaders) this._origShaders[j].shader.removeModule(mod); 29598 } 29599 29600 /** 29601 * @param {import("../cg/cg_shader.js").ShaderModule} mod 29602 */ 29603 addModule(mod) 29604 { 29605 this._mods.push(mod); 29606 this._modulesChanged = true; 29607 } 29608 29609 /** 29610 * @param {string} title 29611 */ 29612 removeModule(title) 29613 { 29614 const indicesToRemove = []; 29615 29616 let found = false; 29617 for (let i = 0; i < this._mods.length; i++) 29618 { 29619 if (this._mods[i].title == title) 29620 { 29621 found = true; 29622 this._removeModulesFromShader(this._mods[i]); 29623 indicesToRemove.push(i); 29624 } 29625 } 29626 29627 // * go in reverse order so the indices of the mods stay the same 29628 for (let j = indicesToRemove.length - 1; j >= 0; j -= 1) 29629 this._mods.splice(indicesToRemove[j], 1); 29630 29631 this._modulesChanged = true; 29632 } 29633 29634 /** 29635 * @param {CgpShader} shader 29636 */ 29637 _updateUniformsShader(shader) 29638 { 29639 for (let i = 0; i < this._uniforms.length; i++) 29640 { 29641 const uni = this._uniforms[i]; 29642 const name = this.getPrefixedName(uni.name); 29643 29644 if (!shader.hasUniform(name)) 29645 { 29646 console.log("shadermod uni ", name, shader.id, uni.stage); 29647 const u = new CgpUniform(shader, uni.type, name, uni.v1, uni.v2, uni.v3, uni.v4); 29648 29649 console.log(uni); 29650 shader.addUniform(u, uni.stage); 29651 } 29652 } 29653 } 29654 29655 _updateUniforms() 29656 { 29657 for (const j in this._origShaders) 29658 this._updateUniformsShader(this._origShaders[j].shader); 29659 29660 this._changedUniforms = false; 29661 } 29662 29663 /** 29664 * @param {CgShader} shader 29665 * @param {string} uniformName 29666 * @param {number} value 29667 */ 29668 _setUniformValue(shader, uniformName, value) 29669 { 29670 const uniform = shader.getUniform(uniformName); 29671 29672 if (uniform) uniform.setValue(value); 29673 } 29674 29675 /** 29676 * @param {string} name 29677 * @param {number} value 29678 */ 29679 setUniformValue(name, value) 29680 { 29681 const uni = this._getUniform(name); 29682 if (!uni) return; 29683 29684 const defineName = this.getPrefixedName(name); 29685 29686 for (const j in this._origShaders) 29687 { 29688 this._setUniformValue(this._origShaders[j].shader, defineName, value); 29689 } 29690 } 29691 29692 /** 29693 * @param {string} name 29694 */ 29695 hasUniform(name) 29696 { 29697 return !!this._getUniform(name); 29698 } 29699 29700 /** 29701 * @param {string} name 29702 */ 29703 _getUniform(name) 29704 { 29705 for (let i = 0; i < this._uniforms.length; i++) 29706 { 29707 if (this._uniforms[i].name == name) return this._uniforms[i]; 29708 } 29709 return null; 29710 } 29711 29712 /** 29713 * @param {number} stage 29714 * @param {string} name 29715 * @param {string} type 29716 * @param {any} valOrPort 29717 * @param {any} v2 29718 * @param {any} v3 29719 * @param {any} v4 29720 */ 29721 addUniform(stage, type, name, valOrPort, v2, v3, v4) 29722 { 29723 if (!this._getUniform(name)) 29724 { 29725 this._uniforms.push( 29726 { 29727 "name": name, 29728 "stage": stage, 29729 "type": type, 29730 "v1": valOrPort, 29731 "v2": v2, 29732 "v3": v3, 29733 "v4": v4, 29734 }); 29735 this._changedUniforms = true; 29736 } 29737 } 29738 29739 // addUniformFrag(type, name, valOrPort, v2, v3, v4) 29740 // { 29741 // this.addUniform(type, name, valOrPort, v2, v3, v4, null, null, null, "frag"); 29742 // this._changedUniforms = true; 29743 // } 29744 29745 // addUniformVert(type, name, valOrPort, v2, v3, v4) 29746 // { 29747 // this.addUniform(type, name, valOrPort, v2, v3, v4, null, null, null, "vert"); 29748 // this._changedUniforms = true; 29749 // } 29750 29751 // addUniformBoth(type, name, valOrPort, v2, v3, v4) 29752 // { 29753 // this.addUniform(type, name, valOrPort, v2, v3, v4, null, null, null, "both"); 29754 // this._changedUniforms = true; 29755 // } 29756 29757 // addUniformStruct(structName, uniformName, members, shaderType) 29758 // { 29759 // for (let i = 0; i < members.length; i += 1) 29760 // { 29761 // const member = members[i]; 29762 // if ((member.type === "2i" || member.type === "i" || member.type === "3i") && shaderType === "both") 29763 // console.error("Adding an integer struct member to both shaders can potentially error. Please use different structs for each shader. Error occured in struct:", structName, " with member:", member.name, " of type:", member.type, "."); 29764 29765 // if (!this._getUniform(uniformName + "." + member.name)) 29766 // { 29767 // this.addUniform( 29768 // member.type, 29769 // uniformName + "." + member.name, 29770 // member.v1, 29771 // member.v2, 29772 // member.v3, 29773 // member.v4, 29774 // uniformName, 29775 // structName, 29776 // member.name, 29777 // shaderType 29778 // ); 29779 // } 29780 // } 29781 // if (!this._getStructUniform(uniformName)) 29782 // { 29783 // this._structUniforms.push({ 29784 // "structName": structName, 29785 // "uniformName": uniformName, 29786 // "members": members, 29787 // "shaderType": shaderType, 29788 // }); 29789 // } 29790 // } 29791 29792 // addUniformStructVert(structName, uniformName, members) 29793 // { 29794 // this.addUniformStruct(structName, uniformName, members, "vert"); 29795 // } 29796 29797 // addUniformStructFrag(structName, uniformName, members) 29798 // { 29799 // this.addUniformStruct(structName, uniformName, members, "frag"); 29800 // } 29801 29802 // addUniformStructBoth(structName, uniformName, members) 29803 // { 29804 // this.addUniformStruct(structName, uniformName, members, "both"); 29805 // } 29806 29807 addAttribute(attr) 29808 { 29809 for (let i = 0; i < this._attributes.length; i++) 29810 { 29811 if (this._attributes[i].name == attr.name && this._attributes[i].nameFrag == attr.nameFrag) return; 29812 } 29813 this._attributes.push(attr); 29814 } 29815 29816 pushTexture(uniformName, tex, texType) 29817 { 29818 if (!tex) throw (new Error("no texture given to texturestack")); 29819 29820 this._textures.push([uniformName, tex, texType]); 29821 this.needsTexturePush = true; 29822 } 29823 29824 /** 29825 * @param {string} name 29826 * @param {CgShader} shader 29827 */ 29828 _removeUniformFromShader(name, shader) 29829 { 29830 if (shader.hasUniform(name)) shader.removeUniform(name); 29831 } 29832 29833 /** 29834 * @param {string} name 29835 */ 29836 removeUniform(name) 29837 { 29838 if (this._getUniform(name)) 29839 { 29840 for (let j = this._uniforms.length - 1; j >= 0; j -= 1) 29841 { 29842 const nameToRemove = name; 29843 29844 if (this._uniforms[j].name == name) 29845 { 29846 for (const k in this._origShaders) 29847 { 29848 this._removeUniformFromShader( 29849 this.getPrefixedName(nameToRemove), 29850 this._origShaders[k].shader 29851 ); 29852 } 29853 29854 this._uniforms.splice(j, 1); 29855 } 29856 } 29857 this._changedUniforms = true; 29858 } 29859 } 29860 29861 /** 29862 * @param {string} name 29863 */ 29864 getPrefixedName(name) 29865 { 29866 const prefix = this._mods[0].group; 29867 if (prefix === undefined) 29868 { 29869 return; 29870 } 29871 if (name.startsWith("MOD_")) 29872 { 29873 name = name.substr("MOD_".length); 29874 name = "mod" + prefix + "_" + name; 29875 } 29876 return name; 29877 } 29878 29879 /** 29880 * @param {CgpShader} shader 29881 */ 29882 _updateDefinesShader(shader) 29883 { 29884 for (const i in this._defines) 29885 { 29886 const name = this.getPrefixedName(i); 29887 if (this._defines[i] !== null && this._defines[i] !== undefined) shader.define(name, this._defines[i]); 29888 else shader.removeDefine(name); 29889 } 29890 29891 for (const i in this._definesToggled) 29892 { 29893 const name = this.getPrefixedName(i); 29894 shader.toggleDefine(name, this._definesToggled[i]); 29895 } 29896 } 29897 29898 _updateDefines() 29899 { 29900 for (const j in this._origShaders) this._updateDefinesShader(this._origShaders[j].shader); 29901 29902 this._changedDefines = false;
29903 } 29904 29905 /** 29906 * @param {string | number} what 29907 * @param {boolean} value 29908 */ 29909 define(what, value) 29910 { 29911 if (value === undefined)value = true; 29912 this._defines[what] = value; 29913 this._changedDefines = true; 29914 } 29915 29916 /** 29917 * @param {string} name 29918 */ 29919 removeDefine(name) 29920 { 29921 this._defines[name] = null; 29922 this._changedDefines = true; 29923 } 29924 29925 /** 29926 * @param {string} name 29927 */ 29928 hasDefine(name) 29929 { 29930 if (this._defines[name] !== null && this._defines[name] !== undefined) return true; 29931 return false; 29932 } 29933 29934 /** 29935 * @param {string} name 29936 * @param {any} b 29937 */ 29938 toggleDefine(name, b) 29939 { 29940 this._changedDefines = true; 29941 this._definesToggled[name] = b; 29942 } 29943 29944 currentShader() 29945 { 29946 if (!this._boundShader) return null; 29947 return this._boundShader.shader; 29948 } 29949 29950 dispose() 29951 { 29952 29953 } 29954} 29955 29956 29957 29958;// CONCATENATED MODULE: ./src/corelibs/cgp/index.js 29959 29960 29961 29962 29963 29964 29965 29966 29967 29968 29969 29970 29971 29972 29973 29974 29975const CGP = { 29976 "Context": CgpContext, 29977 "Shader": CgpShader, 29978 "Mesh": CgpMesh, 29979 "Texture": Texture, 29980 "Uniform": CgpUniform, 29981 "MESHES": cgl_simplerect.MESHES, 29982 "GPUBuffer": CgpGguBuffer 29983}; 29984 29985window.CABLES = window.CABLES || {}; 29986window.CABLES.CGP = window.CABLES.CGP || CGP; 29987window.CGP = window.CGP || CGP; 29988 29989window.CGP.WebGpuCanvasAttachment = WebGpuCanvasAttachment; 29990window.CGP.RenderPipeline = RenderPipeline; 29991window.CGP.ComputePipeline = ComputePipeline; 29992window.CGP.ShaderModifier = ShaderModifier; 29993 29994window.CGP.BindingStorage = BindingStorage; 29995window.CGP.BindingUniform = BindingUniform; 29996window.CGP.BindingTexture = BindingTexture; 29997window.CGP.BindingSampler = BindingSampler; 29998 29999 30000 30001 30002/***/ }), 30003
30004/***/ "./src/corelibs/webaudio/webaudio.js": 30005/*!*******************************************!*\ 30006 !*** ./src/corelibs/webaudio/webaudio.js ***! 30007 \*******************************************/ 30008/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 30009 30010"use strict"; 30011/* unused harmony exports WebAudio, WEBAUDIO */ 30012/* harmony import */ var cables__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! cables */ "./src/core/constants.js"); 30013/** @namespace WEBAUDIO */ 30014 30015 30016 30017/** 30018 * Part of the Web Audio API, the AudioBuffer interface represents a short audio asset residing in memory. 30019 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioBuffer} 30020 */ 30021 30022/** 30023 * Part of the Web Audio API, the AudioNode interface is a generic interface for representing an audio processing module. 30024 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioNode} 30025 */ 30026 30027/** 30028 * The AudioContext interface represents an audio-processing graph built from audio modules linked together 30029 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioContext} 30030 */ 30031 30032class WebAudio 30033{ 30034 30035 constructor() 30036 { 30037 this.toneJsInitialized = false; 30038 } 30039 30040 /** 30041 * Checks if a global audio context has been created and creates 30042 * it if necessary. This audio context can be used for native Web Audio as well as Tone.js ops. 30043 * Associates the audio context with Tone.js if it is being used 30044 * @param {Op} op - The operator which needs the Audio Context 30045 */ 30046 createAudioContext(op) 30047 { 30048 window.AudioContext = window.AudioContext || window.webkitAudioContext; 30049 if (window.AudioContext) 30050 { 30051 if (!window.audioContext) 30052 { 30053 window.audioContext = new AudioContext(); 30054 } 30055 // check if tone.js lib is being used 30056 if (window.Tone && !this.toneJsInitialized) 30057 { 30058 // set current audio context in tone.js, and discard potentially audio context created by tone 30059 if (Tone.setContext) Tone.setContext(window.audioContext, true); 30060 this.toneJsInitialized = true; 30061 } 30062 } 30063 else 30064 { 30065 if (op.patch.config.onError)op.logError("NO_WEBAUDIO", "Web Audio is not supported in this browser."); 30066 return; 30067 } 30068 return window.audioContext; 30069 } 30070 30071 /** 30072 * Returns the audio context. 30073 * Before `createAudioContext` must have been called at least once. 30074 * It most cases you should use `createAudioContext`, which just returns the audio context 30075 * when it has been created already. 30076 */ 30077 _getAudioContext() 30078 { 30079 return window.audioContext; 30080 } 30081 30082 /** 30083 * Creates an audio in port for the op with name `portName` 30084 * When disconnected it will disconnect the previous connected audio n
30084ode 30085 * from the op's audio node. 30086 * @param {Op} op - The operator to create the audio port in 30087 * @param {string} portName - The name of the port 30088 * @param {AudioNode} audioNode - The audionode incoming connections should connect to 30089 * @param {number} [inputChannelIndex=0] - If the audio node has multiple inputs, this is the index of the input channel to connect to 30090 * @returns {Port|undefined} - The newly created audio in port or `undefined` if there was an error 30091 */ 30092 createAudioInPort(op, portName, audioNode, inputChannelIndex) 30093 { 30094 if (!op || !portName || !audioNode) 30095 { 30096 const msg = "ERROR: createAudioInPort needs three parameters, op, portName and audioNode"; 30097 op.log(msg); 30098 throw new Error(msg); 30099 // return; 30100 } 30101 if (!inputChannelIndex) 30102 { 30103 inputChannelIndex = 0; 30104 } 30105 op.webAudio = op.webAudio || {}; 30106 op.webAudio.audioInPorts = op.webAudio.audioInPorts || []; 30107 const port = op.inObject(portName); 30108 port.webAudio = {}; 30109 port.webAudio.previousAudioInNode = null; 30110 port.webAudio.audioNode = audioNode; 30111 30112 op.webAudio.audioInPorts[portName] = port; 30113 30114 port.onChange = function () 30115 { 30116 const audioInNode = port.get(); 30117 // when port disconnected, disconnect audio nodes 30118 if (!audioInNode) 30119 { 30120 if (port.webAudio.previousAudioInNode) 30121 { 30122 try 30123 { 30124 if (port.webAudio.previousAudioInNode.disconnect) port.webAudio.previousAudioInNode.disconnect(port.webAudio.audioNode, 0, inputChannelIndex); 30125 op.setUiError("audioCtx", null); 30126 } 30127 catch (e) 30128 { 30129 try 30130 { 30131 port.webAudio.previousAudioInNode.disconnect(port.webAudio.audioNode); 30132 } 30133 catch (er) 30134 { 30135 op.log( 30136 "Disconnecting audio node with in/out port index, as well as without in/out-port-index did not work ", 30137 e, 30138 ); 30139 if (e.printStackTrace) 30140 { 30141 e.printStackTrace(); 30142 } 30143 throw e; 30144 } 30145 } 30146 } 30147 } 30148 else 30149 { 30150 try 30151 { 30152 if (audioInNode.connect) 30153 { 30154 audioInNode.connect(port.webAudio.audioNode, 0, inputChannelIndex); 30155 op.setUiError("audioCtx", null); 30156 } 30157 else op.setUiError("audioCtx", "The passed input is not an audio context. Please make sure you connect an audio context to the input.", 2); 30158 } 30159 catch (e) 30160 { 30161 op.log("Error: Failed to connect web audio node!", e); 30162 op.log("port.webAudio.audioNode", port.webAudio.audioNode); 30163 op.log("audioInNode: ", audioInNode); 30164 op.log("inputChannelIndex:", inputChannelIndex); 30165 op.log("audioInNode.connect: ", audioInNode.connect); 30166 throw e; 30167 } 30168 } 30169 port.webAudio.previousAudioInNode = audioInNode; 30170 }; 30171 // TODO: Maybe add subtype to audio-node-object? 30172 return port; 30173 } 30174 30175 /** 30176 * Creates an audio out port which takes care of (dis-)connecting on itâs own 30177 * @param {Op} op - The op to create an audio out port for 30178 * @param {string} portName - The name of the port to be created 30179 * @param {AudioNode} audioNode - The audio node to link to the port 30180 * @returns {(CABLES.Port|undefined)} - The newly created audio out port or `undefined` if there was an error 30181 */ 30182 createAudioOutPort(op, portName, audioNode) 30183 { 30184 if (!op || !portName || !audioNode) 30185 { 30186 const msg = "ERROR: createAudioOutPort needs three parameters, op, portName and audioNode"; 30187 op.log(msg); 30188 throw new Error(msg); 30189 } 30190 30191 const port = op.outObject(portName); 30192 // TODO: Maybe add subtype to audio-node-object? 30193 port.set(audioNode); 30194 return port; 30195 } 30196 30197 /** 30198 * Creates an audio param in port for the op with name portName. 30199 * The port accepts other audio nodes as signals as well as values (numbers) 30200 * When the port is disconnected it will disconnect the previous connected audio n
30200ode 30201 * from the op's audio node and restore the number value set before. 30202 * 30203 * @deprecated 30204 * @param {Op} op - The operator to create an audio param input port for 30205 * @param {string} portName - The name of the port to create 30206 * @param audioNode 30207 * @param options 30208 * @param defaultValue 30209 * @returns {(CABLES.Port|undefined)} - The newly created port, which takes care of (dis-)connecting on its own, or `undefined` if there was an error 30210 */ 30211 createAudioParamInPort(op, portName, audioNode, options, defaultValue) 30212 { 30213 if (!op || !portName || !audioNode) 30214 { 30215 op.log("ERROR: createAudioParamInPort needs three parameters, op, portName and audioNode"); 30216 if (op && op.name) op.log("opname: ", op.name); 30217 op.log("portName", portName); 30218 op.log("audioNode: ", audioNode); 30219 return; 30220 } 30221 op.webAudio = op.webAudio || {}; 30222 op.webAudio.audioInPorts = op.webAudio.audioInPorts || []; 30223 // var port = op.inObject(portName); 30224 const port = op.inDynamic( 30225 portName, 30226 [cables__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.OP.OP_PORT_TYPE_VALUE, cables__WEBPACK_IMPORTED_MODULE_0__.CONSTANTS.OP.OP_PORT_TYPE_OBJECT], 30227 options, 30228 defaultValue, 30229 ); 30230 port.webAudio = {}; 30231 port.webAudio.previousAudioInNode = null; 30232 port.webAudio.audioNode = audioNode; 30233 30234 op.webAudio.audioInPorts[portName] = port; 30235 30236 port.onChange = () => 30237 { 30238 const audioInNode = port.get(); 30239 const node = port.webAudio.audioNode; 30240 const audioCtx = this._getAudioContext(); 30241 30242 if (audioInNode != undefined) 30243 { 30244 if (typeof audioInNode === "object" && audioInNode.connect) 30245 { 30246 try 30247 { 30248 audioInNode.connect(node); 30249 } 30250 catch (e) 30251 { 30252 op.log("Could not connect audio node: ", e); 30253 if (e.printStackTrace) 30254 { 30255 e.printStackTrace(); 30256 } 30257 throw e; 30258 } 30259 port.webAudio.previousAudioInNode = audioInNode; 30260 } 30261 else 30262 { 30263 // tone.js audio param 30264 if (node._param && node._param.minValue && node._param.maxValue) 30265 { 30266 if (audioInNode >= node._param.minValue && audioInNode <= node._param.maxValue) 30267 { 30268 try 30269 { 30270 if (node.setValueAtTime) 30271 { 30272 node.setValueAtTime(audioInNode, audioCtx.currentTime); 30273 } 30274 else 30275 { 30276 node.value = audioInNode; 30277 } 30278 } 30279 catch (e) 30280 { 30281 op.log("Possible AudioParam problem with tone.js op: ", e); 30282 if (e.printStackTrace) 30283 { 30284 e.printStackTrace(); 30285 } 30286 throw e; 30287 } 30288 } 30289 else 30290 { 30291 op.log("Warning: The value for an audio parameter is out of range!"); 30292 } 30293 } // native Web Audio param 30294 else if (node.minValue && node.maxValue) 30295 { 30296 if (audioInNode >= node.minValue && audioInNode <= node.maxValue) 30297 { 30298 try 30299 { 30300 if (node.setValueAtTime) 30301 { 30302 node.setValueAtTime(audioInNode, audioCtx.currentTime); 30303 } 30304 else 30305 { 30306 node.value = audioInNode; 30307 } 30308 } 30309 catch (e) 30310 { 30311 op.log( 30312 "AudioParam has minValue / maxValue defined, and value is in range, but setting the value failed! ", 30313 e, 30314 ); 30315 if (e.printStackTrace) 30316 { 30317 e.printStackTrace(); 30318 } 30319 throw e; 30320 } 30321 } 30322 else 30323 { 30324 op.log("Warning: The value for an audio parameter is out of range!"); 30325 } 30326 } // no min-max values, try anyway 30327 else 30328 { 30329 try 30330 { 30331 if (node.setValueAtTime) 30332 { 30333 node.setValueAtTime(audioInNode, audioCtx.currentTime); 30334 } 30335 else 30336 { 30337 node.value = audioInNode; 30338 } 30339 } 30340 catch (e) 30341 { 30342 op.log("Possible AudioParam problem (without minValue / maxValue): ", e); 30343 if (e.printStackTrace) 30344 { 30345 e.printStackTrace(); 30346 } 30347 throw e; 30348 } 30349 } 30350 30351 if (port.webAudio.previousAudioInNode && port.webAudio.previousAudioInNode.disconnect) 30352 { 30353 try 30354 { 30355 port.webAudio.previousAudioInNode.disconnect(node); 30356 } 30357 catch (e) 30358 { 30359 op.log("Could not disconnect previous audio n
30359ode: ", e); 30360 throw e; 30361 } 30362 port.webAudio.previousAudioInNode = undefined; 30363 } 30364 } 30365 } 30366 else 30367 { 30368 // disconnected 30369 if (port.webAudio.previousAudioInNode) 30370 { 30371 } 30372 } 30373 }; 30374 return port; 30375 } 30376 30377 /** 30378 * Loads an audio file and updates the loading indicators when cables is run in the editor. 30379 * @param {Patch} patch - The cables patch, when called from inside an op this is `op.patch` 30380 * @param {string} url - The url of the audio file to load 30381 * @param {function} onFinished - The callback to be called when the loading is finished, passes the AudioBuffer 30382 * @param {function} onError - The callback when there was an error loading the file, the rror message is passed 30383 * @param loadingTask 30384 * @see {@link https://developer.mozilla.org/de/docs/Web/API/AudioContext/decodeAudioData} 30385 */ 30386 loadAudioFile(patch, url, onFinished, onError, loadingTask) 30387 { 30388 const audioContext = this.createAudioContext(); 30389 30390 if (!audioContext) onError(new Error("No Audiocontext")); 30391 30392 let loadingId = null; 30393 if (loadingTask || loadingTask === undefined) 30394 { 30395 loadingId = patch.loading.start("audio", url); 30396 if (patch.isEditorMode()) gui.jobs().start({ "id": "loadaudio" + loadingId, "title": " loading audio (" + url + ")" }); 30397 } 30398 const request = new XMLHttpRequest(); 30399 30400 if (!url) return; 30401 30402 request.open("GET", url, true); 30403 request.responseType = "arraybuffer"; 30404 30405 request.onload = function () 30406 { 30407 patch.loading.finished(loadingId); 30408 if (patch.isEditorMode()) gui.jobs().finish("loadaudio" + loadingId); 30409 30410 audioContext.decodeAudioData(request.response, onFinished, onError).catch((e) => 30411 { 30412 onError(e); 30413 }); 30414 }; 30415 request.send(); 30416 } 30417 30418 /** 30419 * Checks if the passed time is a valid time to be used in any of the Tone.js ops. 30420 * @deprecated 30421 * @param {(string|number)} t - The time to check 30422 * @returns {boolean} - True if time is valid, false if not 30423 */ 30424 isValidToneTime(t) 30425 { 30426 try 30427 { 30428 const time = new Tone.Time(t); 30429 } 30430 catch (e) 30431 { 30432 return false; 30433 } 30434 return true; 30435 } 30436 30437 /** 30438 * Checks if the passed note is a valid note to be used with Tone.js 30439 * @deprecated 30440 * @param {string} note - The note to be checked, e.g. `"C4"` 30441 * @returns {boolean} - True if the note is a valid note, false otherwise 30442 */ 30443 isValidToneNote(note) 30444 { 30445 try 30446 { 30447 Tone.Frequency(note); 30448 } 30449 catch (e) 30450 { 30451 return false; 30452 } 30453 return true; 30454 } 30455} 30456 30457const WEBAUDIO = new WebAudio(); 30458 30459window.CABLES = window.CABLES || {}; 30460window.CABLES.WEBAUDIO = WEBAUDIO; 30461 30462 30463 30464 30465/***/ }), 30466
30467/***/ "../shared/client/src/eventtarget.js": 30468/*!*******************************************************!*\ 30469 !*** ../shared/client/src/eventtarget.js + 2 modules ***! 30470 \*******************************************************/ 30471/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 30472 30473"use strict"; 30474 30475// EXPORTS 30476__webpack_require__.d(__webpack_exports__, { 30477 "default": () => (/* binding */ Events) 30478}); 30479 30480;// CONCATENATED MODULE: ../shared/client/src/eventlistener.js 30481class EventListener 30482{ 30483 30484 /** 30485 * @param {Object} emitter 30486 * @param {string} id 30487 * @param {string} eventName 30488 * @param {Function} cb 30489 */ 30490 constructor(emitter, id, eventName, cb) 30491 { 30492 this.targetObj = emitter; 30493 this.id = id; 30494 this.eventName = eventName; 30495 this.cb = cb; 30496 } 30497 30498 remove() 30499 { 30500 this.targetObj.off(this.id); 30501 } 30502} 30503 30504;// CONCATENATED MODULE: ../shared/client/src/helper.js 30505/** 30506 * Shared helper methods for cables uis 30507 */ 30508class Helper 30509{ 30510 constructor() 30511 { 30512 this._simpleIdCounter = 0; 30513 } 30514 30515 /** 30516 * generate a random v4 uuid 30517 * 30518 * @return {string} 30519 */ 30520 uuid() 30521 { 30522 let d = new Date().getTime(); 30523 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => 30524 { 30525 const r = (d + Math.random() * 16) % 16 | 0; 30526 d = Math.floor(d / 16); 30527 return (c === "x" ? r : (r & 0x3) | 0x8).toString(16); 30528 }); 30529 } 30530 30531 /** 30532 * checks value for !isNan and isFinite 30533 * 30534 * @param {string} n 30535 * @return {boolean} 30536 */ 30537 isNumeric(n) 30538 { 30539 const nn = parseFloat(n); 30540 return !isNaN(nn) && isFinite(nn); 30541 } 30542 30543 /** 30544 * generate a simple ID using an internal counter 30545 * 30546 * @return {Number} new id 30547 * @static 30548 */ 30549 simpleId() 30550 { 30551 this._simpleIdCounter++; 30552 return this._simpleIdCounter; 30553 } 30554 30555 pathLookup(obj, path) 30556 { 30557 const parts = path.split("."); 30558 if (parts.length == 1) 30559 { 30560 return obj[parts[0]]; 30561 } 30562 return this.pathLookup(obj[parts[0]], parts.slice(1).join(".")); 30563 } 30564 30565} 30566/* harmony default export */ const helper = (new Helper()); 30567 30568// EXTERNAL MODULE: ../shared/client/src/logger.js 30569var logger = __webpack_require__("../shared/client/src/logger.js"); 30570;// CONCATENATED MODULE: ../shared/client/src/eventtarget.js 30571 30572 30573 30574 30575/** 30576 * add eventlistener functionality to classes 30577 */ 30578class Events 30579{ 30580 #eventLog = new logger["default"]("eventtarget"); 30581 30582 /** @type {Object<string,EventListener>} */ 30583 #listeners = {}; 30584 #logEvents = false; 30585 #logName = ""; 30586 #eventCallbacks = {}; 30587 #countErrorUnknowns = 0; 30588 eventsPaused = false; 30589 30590 constructor() 30591 { 30592 } 30593 30594 /** 30595 * @callback whatever 30596 * @param {...any} param 30597 */ 30598 30599 /** 30600 * add event listener 30601 * @param {string} eventName event name 30602 * @param {whatever} cb callback 30603 * @param {string} idPrefix prefix for id, default empty 30604 * @return {EventListener} eventlistener 30605 */ 30606 on(eventName, cb, idPrefix = "") 30607 { 30608 const newId = (idPrefix || "") + helper.simpleId(); 30609 30610 const event = new EventListener(this, newId, eventName, cb); 30611 30612 if (!this.#eventCallbacks[eventName]) this.#eventCallbacks[eventName] = [event]; 30613 else this.#eventCallbacks[eventName].push(event); 30614 30615 this.#listeners[event.id] = event; 30616 30617 return event; 30618 } 30619 30620 removeAllEventListeners() 30621 { 30622 for (const i in this.#listeners) 30623 { 30624 this.off(this.#listeners[i]); 30625 } 30626 } 30627 30628 /** 30629 * 30630 * @param {string} which 30631 * @param {whatever} cb 30632 */ 30633 addEventListener(which, cb, idPrefix = "") 30634 { 30635 return this.on(which, cb, idPrefix); 30636 } 30637 30638 /** 30639 * check event listener registration 30640 * @param {string|EventListener} id event id 30641 * @param {whatever} cb callback - deprecated 30642 * @return {boolean} 30643 */ 30644 hasEventListener(id, cb = null) 30645 { 30646 if (id && !cb) 30647 { 30648 if (typeof id == "string") // check by id 30649 return !!this.#listeners[id]; 30650 else 30651 return !!this.#listeners[id.id]; 30652 30653 } 30654 else 30655 { 30656 this.#eventLog.warn("old eventtarget function haseventlistener!"); 30657 if (id && cb) 30658 { 30659 if (this.#eventCallbacks[id]) 30660 { 30661 const idx = this.#eventCallbacks[id].indexOf(cb); 30662 return idx !== -1; 30663 } 30664 } 30665 } 30666 } 30667 30668 /** 30669 * check event listener by name 30670 * @param {string } eventName event name 30671 * @return {boolean} 30672 */ 30673 hasListenerForEventName(eventName) 30674 { 30675 return this.#eventCallbacks[eventName] && this.#eventCallbacks[eventName].length > 0; 30676 } 30677 30678 /** @deprecated */ 30679 removeEventListener(id) 30680 { 30681 return this.off(id); 30682 } 30683 30684 /** 30685 * remove event listener registration 30686 * @param {EventListener} listenerParam 30687 */ 30688 off(listenerParam) 30689 { 30690 if (listenerParam === null || listenerParam === undefined) 30691 { 30692 this.#eventLog.warn("removeEventListener id null", listenerParam); 30693 return; 30694 } 30695 30696 let id = listenerParam; // old off was using id strings directly, now uses eventlistener class 30697 // @ts-ignore 30698 if (listenerParam.eventName) id = listenerParam.id; 30699 30700 if (typeof id != "string") 30701 { 30702 console.log("old function signature: removeEventListener! use listener id"); 30703 return; 30704 } 30705 30706 const event = this.#listeners[id]; 30707 if (!event) 30708 { 30709 if (this.#countErrorUnknowns == 20) this.#eventLog.warn("stopped reporting unknown events"); 30710 if (this.#countErrorUnknowns < 20) this.#eventLog.warn("could not find event...", id); 30711 this.#countErrorUnknowns++; 30712 return; 30713 } 30714 30715 let removeCount = 0; 30716 30717 let found = true; 30718 while (found) 30719 { 30720 found = false;
30721 let index = -1; 30722 for (let i = 0; i < this.#eventCallbacks[event.eventName].length; i++) 30723 { 30724 if (this.#eventCallbacks[event.eventName][i].id.indexOf(id) === 0) // this._eventCallbacks[event.eventName][i].id == which || 30725 { 30726 found = true; 30727 index = i; 30728 } 30729 } 30730 30731 if (index !== -1) 30732 { 30733 this.#eventCallbacks[event.eventName].splice(index, 1); 30734 delete this.#listeners[id]; 30735 removeCount++; 30736 } 30737 } 30738 30739 if (removeCount == 0)console.log("no events removed", event.eventName, id); 30740 30741 return; 30742 } 30743 30744 /** 30745 * enable/disable logging of events for the class 30746 * 30747 * @param {boolean} enabled 30748 * @param {string} logName 30749 */ 30750 logEvents(enabled, logName) 30751 { 30752 this.#logEvents = enabled; 30753 this.#logName = logName; 30754 } 30755 30756 /** 30757 * emit event 30758 * 30759 * @param {string} which event name 30760 * @param {*} param1 30761 * @param {*} param2 30762 * @param {*} param3 30763 * @param {*} param4 30764 * @param {*} param5 30765 * @param {*} param6 30766 */ 30767 emitEvent(which, param1 = null, param2 = null, param3 = null, param4 = null, param5 = null, param6 = null, param7 = null, param8 = null) 30768 { 30769 if (this.eventsPaused) return; 30770 if (this.#logEvents) this.#eventLog.log("[event] ", this.#logName, which, this.#eventCallbacks); 30771 30772 if (this.#eventCallbacks[which]) 30773 { 30774 for (let i = 0; i < this.#eventCallbacks[which].length; i++) 30775 { 30776 if (this.#eventCallbacks[which][i]) 30777 { 30778 this.#eventCallbacks[which][i].cb(param1, param2, param3, param4, param5, param6, param7, param8); 30779 } 30780 } 30781 } 30782 else 30783 { 30784 if (this.#logEvents) this.#eventLog.log("[event] has no event callback", which, this.#eventCallbacks); 30785 } 30786 } 30787} 30788 30789 30790/***/ }), 30791
30792/***/ "../shared/client/src/logger.js": 30793/*!**************************************!*\ 30794 !*** ../shared/client/src/logger.js ***! 30795 \**************************************/ 30796/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { 30797 30798"use strict"; 30799/* harmony export */ __webpack_require__.d(__webpack_exports__, { 30800/* harmony export */ "default": () => (/* binding */ Logger) 30801/* harmony export */ }); 30802/* eslint-disable no-console */ 30803class Logger 30804{ 30805 30806 /** 30807 * @param {any} initiator 30808 * @param {Object} options 30809 */ 30810 constructor(initiator, options) 30811 { 30812 this.initiator = initiator; 30813 this._options = options; 30814 } 30815 30816 /** 30817 * @param {string} t 30818 */ 30819 stack(t) 30820 { 30821 console.info("[" + this.initiator + "] ", t); 30822 console.log((new Error()).stack); 30823 } 30824 30825 /** 30826 * @param {string} t 30827 */ 30828 groupCollapsed(t) 30829 { 30830 if ((CABLES.UI && CABLES.UI.logFilter.filterLog({ "initiator": this.initiator, "level": 0 }, ...arguments)) || !CABLES.logSilent) console.log("[" + this.initiator + "]", ...arguments); 30831 30832 console.groupCollapsed("[" + this.initiator + "] " + t); 30833 } 30834 30835 /** 30836 * @param {any[][]} t 30837 */ 30838 table(t) 30839 { 30840 console.table(t); 30841 } 30842 30843 groupEnd() 30844 { 30845 console.groupEnd(); 30846 } 30847 30848 error() 30849 { 30850 if ((CABLES.UI && CABLES.UI.logFilter.filterLog({ "initiator": this.initiator, "level": 2 }, ...arguments)) || !CABLES.UI) 30851 { 30852 console.error("[" + this.initiator + "]", ...arguments); 30853 } 30854 30855 if (this._options && this._options.onError) 30856 { 30857 this._options.onError(this.initiator, ...arguments); 30858 // console.log("emitevent onerror..."); 30859 // CABLES.patch.emitEvent("onError", this.initiator, ...arguments); 30860 // CABLES.logErrorConsole("[" + this.initiator + "]", ...arguments); 30861 } 30862 } 30863 30864 errorGui() 30865 { 30866 if (CABLES.UI) CABLES.UI.logFilter.filterLog({ "initiator": this.initiator, "level": 2 }, ...arguments); 30867 } 30868 30869 warn() 30870 { 30871 if ((CABLES.UI && CABLES.UI.logFilter.filterLog({ "initiator": this.initiator, "level": 1 }, ...arguments)) || !CABLES.logSilent) 30872 console.warn("[" + this.initiator + "]", ...arguments); 30873 } 30874 30875 verbose() 30876 { 30877 if ((CABLES.UI && CABLES.UI.logFilter.filterLog({ "initiator": this.initiator, "level": 0 }, ...arguments)) || !CABLES.logSilent) 30878 console.log("[" + this.initiator + "]", ...arguments); 30879 } 30880 30881 info() 30882 { 30883 if ((CABLES.UI && CABLES.UI.logFilter.filterLog({ "initiator": this.initiator, "level": 0 }, ...arguments)) || !CABLES.logSilent) 30884 console.info("[" + this.initiator + "]", ...arguments); 30885 } 30886 30887 log() 30888 { 30889 if ((CABLES.UI && CABLES.UI.logFilter.filterLog({ "initiator": this.initiator, "level": 0 }, ...arguments)) || !CABLES.logSilent) 30890 console.log("[" + this.initiator + "]", ...arguments); 30891 } 30892 30893 logGui() 30894 { 30895 if (CABLES.UI) CABLES.UI.logFilter.filterLog({ "initiator": this.initiator, "level": 0 }, ...arguments); 30896 } 30897 30898 userInteraction(text) 30899 { 30900 // this.log({ "initiator": "userinteraction", "text": text }); 30901 } 30902} 30903 30904 30905/***/ })
vendor: 2,964 bytes, lines 30905-30973
30905 30906 30907/******/ }); 30908/************************************************************************/ 30909/******/ // The module cache 30910/******/ var __webpack_module_cache__ = {}; 30911/******/ 30912/******/ // The require function 30913/******/ function __webpack_require__(moduleId) { 30914/******/ // Check if module is in cache 30915/******/ var cachedModule = __webpack_module_cache__[moduleId]; 30916/******/ if (cachedModule !== undefined) { 30917/******/ return cachedModule.exports; 30918/******/ } 30919/******/ // Create a new module (and put it into the cache) 30920/******/ var module = __webpack_module_cache__[moduleId] = { 30921/******/ // no module.id needed 30922/******/ // no module.loaded needed 30923/******/ exports: {} 30924/******/ }; 30925/******/ 30926/******/ // Execute the module function 30927/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); 30928/******/ 30929/******/ // Return the exports of the module 30930/******/ return module.exports; 30931/******/ } 30932/******/ 30933/************************************************************************/ 30934/******/ /* webpack/runtime/define property getters */ 30935/******/ (() => { 30936/******/ // define getter functions for harmony exports 30937/******/ __webpack_require__.d = (exports, definition) => { 30938/******/ for(var key in definition) { 30939/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { 30940/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); 30941/******/ } 30942/******/ } 30943/******/ }; 30944/******/ })(); 30945/******/ 30946/******/ /* webpack/runtime/hasOwnProperty shorthand */ 30947/******/ (() => { 30948/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) 30949/******/ })(); 30950/******/ 30951/******/ /* webpack/runtime/make namespace object */ 30952/******/ (() => { 30953/******/ // define __esModule on exports 30954/******/ __webpack_require__.r = (exports) => { 30955/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { 30956/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); 30957/******/ } 30958/******/ Object.defineProperty(exports, '__esModule', { value: true }); 30959/******/ }; 30960/******/ })(); 30961/******/ 30962/************************************************************************/ 30963/******/ 30964/******/ // startup 30965/******/ // Load entry module and return exports 30966/******/ __webpack_require__("./src/corelibs/cg/index.js"); 30967/******/ // This entry module is referenced by other modules so it can't be inlined 30968/******/ __webpack_require__("./src/corelibs/cgl/index.js"); 30969/******/ __webpack_require__("./src/corelibs/cgp/index.js"); 30970/******/ __webpack_require__("./src/corelibs/webaudio/webaudio.js"); 30971/******/ var __webpack_exports__ = __webpack_require__("./src/core/index.js"); 30972/******/ var __webpack_export_target__ = (CABLES = typeof CABLES === "undefined" ? {} : CABLES); 30973/******/ for(var i in __webpack_exports__) __webpack_export_target__[i] = __webpack_exports__[i];
30974/******/ if(__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true }); 30975/******/ 30976/******/ })() 30977; 30978 30979 30980var CABLES = CABLES || {}; CABLES.build = {"timestamp":1759820891913,"created":"2025-10-07T07:08:11.913Z","git":{"branch":"develop","commit":"39922376611f5f12d8d86cfde2d837a67c305f73","date":"1759820873","message":"cleartex"}}; 30981//# sourceMappingURL=cables.js.map 30982if(!CABLES.exportedPatches)CABLES.exportedPatches={};CABLES.exportedPatches["zwNKaV"]={_id:"68b05113dbbf1bb5ae6ea737",ops:[{id:"jpec9fzt3",uiAttribs:{},portsIn:[{name:"Max Pixel Density (DPR)",value:2},{name:"FPS Limit",value:30},{name:"Reduce FPS unfocussed",value:0},{name:"Transparent",value:0},{name:"Active",value:1},{name:"Focus canvas",value:1}],portsOut:[{name:"trigger",links:[{portIn:"exe",portOut:"trigger",objIn:"4cjxtytqv",objOut:"jpec9fzt3"}]},{name:"width",value:758},{name:"height",value:554},{name:"Pixel Density",value:1}],objName:"Ops.Gl.MainLoop_v2"},{id:"4cjxtytqv",uiAttribs:{},portsOut:[{name:"trigger 0",links:[{portIn:"exe",portOut:"trigger 0",objIn:"f5ez8gwci",objOut:"4cjxtytqv"}]},{name:"trigger 2",links:[{portIn:"Render",portOut:"trigger 2",objIn:"7goi1kd6x",objOut:"4cjxtytqv"}]},{name:"trigger 4",links:[{portIn:"Render",portOut:"trigger 4",objIn:"u3g29uxcu",objOut:"4cjxtytqv"}]},{name:"trigger 7",links:[{portIn:"exe",portOut:"trigger 7",objIn:"jxnl6c02w",objOut:"4cjxtytqv"}]}],objName:"Ops.Trigger.Sequence"},{id:"u3g29uxcu",uiAttribs:{},portsIn:[{name:"Size index",value:0},{name:"Size",value:"Auto"},{name:"Width",value:640},{name:"Height",value:480},{name:"Filter index",value:1},{name:"Filter",value:"linear"},{name:"Wrap index",value:1},{name:"Wrap",value:"repeat"},{name:"Anisotropic index",value:0},{name:"Anisotropic",value:"0"},{name:"Pixel Format index",value:4},{name:"Pixel Format",value:"RGBA 8bit ubyte"},{name:"Clear",value:1},{name:"R",value:0},{name:"G",value:0},{name:"B",value:0},{name:"A",value:0}],portsOut:[{name:"Next",links:[{portIn:"Update",portOut:"Next",objIn:"2f2fxiykf",objOut:"u3g29uxcu"}]},{name:"texture_out",links:[{portIn:"tex",portOut:"texture_out",objIn:"d6v0ujept",objOut:"u3g29uxcu"},{portIn:"Texture In",portOut:"texture_out",objIn:"s0scffwlv",objOut:"u3g29uxcu"}]},{name:"Aspect Ratio",value:1.3682310469314078},{name:"Texture Width",value:758},{name:"Texture Height",value:554}],objName:"Ops.Gl.ImageCompose.ImageCompose_v4"},{id:"l1kn6r4jz",uiAttribs:{},portsIn:[{name:"Scale index",value:1},{name:"Scale",value:"Fit"},{name:"Flip Y",value:0},{name:"Flip X",value:0}],portsOut:[{name:"trigger",links:[{portIn:"Render",portOut:"trigger",objIn:"9e055zmn9",objOut:"l1kn6r4jz"}]}],objName:"Ops.Gl.Meshes.FullscreenRectangle_v2"},{id:"7goi1kd6x",uiAttribs:{},portsIn:[{name:"Size index",value:2},{name:"Size",value:"Manual"},{name:"Width",value:256},{name:"Height",value:256},{name:"Filter index",value:1},{name:"Filter",value:"linear"},{name:"Wrap index",value:2},{name:"Wrap",value:"mirrored repeat"},{name:"Anisotropic index",value:0},{name:"Anisotropic",value:"0"},{name:"Pixel Format index",value:4},{name:"Pixel Format",value:"RGBA 8bit ubyte"},{name:"Clear",value:1},{name:"R",value:0},{name:"G",value:0},{name:"B",value:0},{name:"A",value:0}],portsOut:[{name:"Next",links:[{portIn:"render",portOut:"Next",objIn:"cr90y7xb5",objOut:"7goi1kd6x"}]},{name:"texture_out",links:[{portIn:"Image",portOut:"texture_out",objIn:"srddvd5ji",objOut:"7goi1kd6x"}]},{name:"Aspect Ratio",value:1},{name:"Texture Width",value:256},{name:"Texture Height",value:256}],objName:"Ops.Gl.ImageCompose.ImageCompose_v4"},{id:"svjcaubcw",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.5,"r":0,"g":0,"b":0},{"pos":0,"posy":0.5,"r":0,"g":0,"b":0},{"pos":1,"posy":0.5,"r":1,"g":1,"b":1},{"pos":1,"posy":0.5,"r":1,"g":1,"b":1}]}'},{name:"Direction index",value:5},{name:"Direction",value:"YX"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:256},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Image",portOut:"Texture",objIn:"cr90y7xb5",objOut:"svjcaubcw"}]}],objName:"Ops.Gl.GradientTexture"},{id:"cr90y7xb5",uiAttribs:{},portsIn:[{name:"blendMode index",value:0},{name:"blendMode",value:"normal"},{name:"amount",value:1},{name:"Premultiplied",value:0},{name:"Alpha Mask",value:0},{name:"removeAlphaSrc",value:0},{name:"Mask Src index",value:1},{name:"Mask Src",value:"luminance"},{name:"Invert alpha channel",value:0},{name:"Aspect Ratio",value:0},{name:"Stretch Axis index",value:0},{name:"Stretch Axis",value:"X"},{name:"Position",value:0},{name:"Crop",value:0},{name:"flip x",value:0},{name:"flip y",value:0},{name:"Transform",value:0},{name:"Scale X",value:1},{name:"Scale Y",value:1},{name:"Position X",value:0},{name:"Position Y",value:0},{name:"Rotation",value:0},{name:"Clip Repeat",value:0}],portsOut:[{name:"trigger",links:[{portIn:"render",portOut:"trigger",objIn:"qvl9i85vh",objOut:"cr90y7xb5"}]}],objName:"Ops.Gl.ImageCompose.DrawImage_v3"},{id:"srddvd5ji",uiAttribs:{},portsIn:[{name:"blendMode index",value:0},{name:"blendMode",value:"normal"},{name:"amount",value:1},{name:"Premultiplied",value:0},{name:"Alpha Mask",value:0},{name:"removeAlphaSrc",value:0},{name:"Mask Src index",value:1},{name:"Mask Src",value:"luminance"},{name:"Invert alpha channel",value:0},{name:"Aspect Ratio",value:0},{name:"Stretch Axis index",value:0},{name:"Stretch Axis",value:"X"},{name:"Position",value:0},{name:"Crop",value:0},{name:"flip x",value:0},{name:"flip y",value:0},{name:"Transform",value:1},{name:"Scale X",value:1},{name:"Scale Y",value:1},{name:"Position Y",value:0},{name:"Rotation",value:0},{name:"Clip Repeat",value:0}],objName:"Ops.Gl.ImageCompose.DrawImage_v3"},{id:"qvl9i85vh",uiAttribs:{},portsIn:[{name:"Blend Mode index",value:0},{name:"Blend Mode",value:"normal"},{name:"Amount",value:1},{name:"Crop",value:0},{name:"Clear",value:1}],portsOut:[{name:"trigger",links:[{portIn:"render",portOut:"trigger",objIn:"udkkitv80",objOut:"qvl9i85vh"}]}],objName:"Ops.Gl.ImageCompose.RotateTexture_v2"},{id:"uzeqy9xft",uiAttribs:{},portsIn:[{name:"Coordinates index",value:0},{name:"Coordinates",value:"-1 to 1"},{name:"Area index",value:2},{name:"Area",value:"Document"},{name:"flip y",value:1},{name:"right click prevent default",value:0},{name:"Events index",value:0},{name:"Events",value:"Pointer"},{name:"Passive Events",value:0},{name:"Active",value:1}],portsOut:[{name:"x",links:[{portIn:"Value",portOut:"x",objIn:"2f2fxiykf",objOut:"uzeqy9xft"}]},{name:"y",links:[{portIn:"number1",portOut:"y",objIn:"130m752p6",objOut:"uzeqy9xft"}]},{name:"Button is down",value:0},{name:"Mouse is hovering",value:1},{name:"Movement X",value:6},{name:"Movement Y",value:-7}],objName:"Ops.Devices.Mouse.Mouse_v4"},{id:"2f2fxiykf",uiAttribs:{},portsIn:[{name:"Separate inc/dec",value:0},{name:"Inc factor",value:15.18,title:"Inc/Dec factor"},{name:"Dec factor",value:4}],portsOut:[{name:"Next",links:[{portIn:"Update",portOut:"Next",objIn:"7id7azrnh",objOut:"2f2fxiykf"}]},{name:"Result",links:[{portIn:"Position X",portOut:"Result",objIn:"srddvd5ji",objOut:"2f2fxiykf"}]}],objName:"Ops.Anim.Smooth"},{id:"udkkitv80",uiAttribs:{},portsIn:[{name:"Blend Mode index",value:0},{name:"Blend Mode",value:"normal"},{name:"Amount",value:1},{name:"Intensity",value:-28.5}],portsOut:[{name:"Trigger",links:[{portIn:"render",portOut:"Trigger",objIn:"rafdqy6wp",objOut:"udkkitv80"}]}],objName:"Ops.Gl.ImageCompose.BarrelDistortion_v3"},{id:"130m752p6",uiAttribs:{},portsIn:[{name:"number2",value:.2}],portsOut:[{name:"result",links:[{portIn:"number1",portOut:"result",objIn:"zbtj5pb7v",objOut:"130m752p6"}]}],objName:"Ops.Math.Multiply"},{id:"7id7azrnh",uiAttribs:{},portsIn:[{name:"Separate inc/dec",value:0},{name:"Inc factor",value:15.18,title:"Inc/Dec factor"},{name:"Dec factor",value:4}],portsOut:[{name:"Next",links:[{portIn:"render",portOut:"Next",objIn:"srddvd5ji",objOut:"7id7azrnh"}]},{name:"Result",links:[{portIn:"Rotate",portOut:"Result",objIn:"qvl9i85vh",objOut:"7id7azrnh"}]}],objName:"Ops.Anim.Smooth"},{id:"zbtj5pb7v",uiAttribs:{},portsOut:[{name:"result",links:[{portIn:"Value",portOut:"result",objIn:"7id7azrnh",objOut:"zbtj5pb7v"}]}],objName:"Ops.Math.Sum"},{id:"fuw3ufv3v",uiAttribs:{},portsIn:[{name:"phase",value:0},{name:"frequency",value:1},{name:"amplitude",value:1},{name:"asine",value:0}],portsOut:[{name:"result",links:[{portIn:"number2",portOut:"result",objIn:"zbtj5pb7v",objOut:"fuw3ufv3v"}]}],objName:"Ops.Math.Sine"},{id:"54f91btuz",uiAttribs:{},portsIn:[{name:"Speed",value:.1},{name:"Play",value:1},{name:"Sync to timeline",value:0}],portsOut:[{name:"Time",links:[{portIn:"value",portOut:"Time",objIn:"fuw3ufv3v",objOut:"54f91btuz"}]}],objName:"Ops.Anim.Timer_v2"},{id:"rafdqy6wp",uiAttribs:{},portsIn:[{name:"Blend Mode index",value:0},{name:"Blend Mode",value:"normal"},{name:"Alpha Mask index",value:0},{name:"Alpha Mask",value:"Off"},{name:"Amount",value:.262},{name:"Color index",value:0},{name:"Color",value:"Mono"},{name:"Scale",value:1.5},{name:"Multiply",value:1},{name:"Value index",value:0}
30982,{name:"Value",value:"0-1"},{name:"Harmonics index",value:0},{name:"Harmonics",value:"1"},{name:"X",value:0},{name:"Y",value:0},{name:"Offset Multiply",value:1},{name:"Offset X index",value:0},{name:"Offset X",value:"None"},{name:"Offset Y index",value:0},{name:"Offset Y",value:"None"},{name:"Offset Z index",value:1},{name:"Offset Z",value:"R"}],objName:"Ops.Gl.ImageCompose.Noise.PerlinNoise_v2"},{id:"oby4rc0gy",uiAttribs:{},portsIn:[{name:"Speed",value:1},{name:"Play",value:1},{name:"Sync to timeline",value:0}],portsOut:[{name:"Time",links:[{portIn:"Z",portOut:"Time",objIn:"rafdqy6wp",objOut:"oby4rc0gy"}]}],objName:"Ops.Anim.Timer_v2"},{id:"k4iwedcj3",uiAttribs:{},portsIn:[{name:"Text",value:"Element"},{name:"Position index",value:0},{name:"Position",value:"Absolute"},{name:"Interactive index",value:0},{name:"Interactive",value:"True"},{name:"Set Size",value:1},{name:"Width",value:313.9},{name:"Height",value:577.28},{name:"Size Units index",value:0},{name:"Size Units",value:"px"},{name:"Overflow index",value:1},{name:"Overflow",value:"Hidden"},{name:"Inline Style",value:""},{name:"CSS Class",value:"bggradient"},{name:"Disable CSS Props",value:""},{name:"Display index",value:1},{name:"Display",value:"Block"},{name:"Tag Name",value:"canvas"},{name:"Opacity",value:1},{name:"Propagate Click-Events",value:1}],portsOut:[{name:"DOM Element",links:[{portIn:"Element",portOut:"DOM Element",objIn:"9u6fgcxyt",objOut:"k4iwedcj3"}]},{name:"Hovering",value:0}],objName:"Ops.Html.Elements.Element_v2"},{id:"0yg96xu13",uiAttribs:{},portsOut:[{name:"then",links:[{portIn:"render",portOut:"then",objIn:"d6v0ujept",objOut:"0yg96xu13"}]}],objName:"Ops.Boolean.IfTrueThen_v2"},{id:"w55a5wcw4",uiAttribs:{},portsIn:[{name:"Query",value:".bggradient"},{name:"Mode index",value:0},{name:"Mode",value:"document"},{name:"Type index",value:0},{name:"Type",value:"text/html"},{name:"Document",value:"xml"}],portsOut:[{name:"Elements",links:[{portIn:"array",portOut:"Elements",objIn:"k0tgkvnrd",objOut:"w55a5wcw4"}]}],objName:"Ops.Html.QuerySelectorAll_v2"},{id:"9u6fgcxyt",uiAttribs:{},portsIn:[{name:"Translate Active",value:1},{name:"Translate X",value:111.15},{name:"Translate Y",value:-29.89},{name:"Unit index",value:0},{name:"Unit",value:"px"},{name:"Scale Active",value:1},{name:"Scale",value:1},{name:"Rotate Active",value:1},{name:"Rot Z",value:0},{name:"Set Origin",value:1},{name:"Origin X index",value:1},{name:"Origin X",value:"center"},{name:"Origin Y index",value:1},{name:"Origin Y",value:"center"},{name:"Z Index Active",value:0},{name:"Z Index",value:100}],portsOut:[{name:"Passthrough",links:[{portIn:"Element",portOut:"Passthrough",objIn:"rtbgcu8ns",objOut:"9u6fgcxyt"}]}],objName:"Ops.Html.CSS.ElementCssTransform_v2"},{id:"v451ni5ju",uiAttribs:{},portsIn:[{name:"Text",value:"Element"},{name:"Position index",value:0},{name:"Position",value:"Absolute"},{name:"Interactive index",value:0},{name:"Interactive",value:"True"},{name:"Set Size",value:1},{name:"Width",value:265.9},{name:"Height",value:100},{name:"Size Units index",value:0},{name:"Size Units",value:"px"},{name:"Overflow index",value:1},{name:"Overflow",value:"Hidden"},{name:"Inline Style",value:""},{name:"CSS Class",value:"bggradient"},{name:"Disable CSS Props",value:""},{name:"Display index",value:1},{name:"Display",value:"Block"},{name:"Tag Name",value:"canvas"},{name:"Opacity",value:1},{name:"Propagate Click-Events",value:1}],portsOut:[{name:"DOM Element",links:[{portIn:"Element",portOut:"DOM Element",objIn:"gnpl62fdc",objOut:"v451ni5ju"}]},{name:"Hovering",value:0}],objName:"Ops.Html.Elements.Element_v2"},{id:"gnpl62fdc",uiAttribs:{},portsIn:[{name:"Translate Active",value:1},{name:"Translate X",value:348.18},{name:"Translate Y",value:164},{name:"Unit index",value:0},{name:"Unit",value:"px"},{name:"Scale Active",value:1},{name:"Scale",value:1},{name:"Rotate Active",value:1},{name:"Rot Z",value:0},{name:"Set Origin",value:1},{name:"Origin X index",value:1},{name:"Origin X",value:"center"},{name:"Origin Y index",value:1},{name:"Origin Y",value:"center"},{name:"Z Index Active",value:0},{name:"Z Index",value:100}],portsOut:[{name:"Passthrough",links:[{portIn:"Element",portOut:"Passthrough",objIn:"6n3c7fcfa",objOut:"gnpl62fdc"}]}],objName:"Ops.Html.CSS.ElementCssTransform_v2"},{id:"k0tgkvnrd",uiAttribs:{},portsOut:[{name:"trigger",links:[{portIn:"Update",portOut:"trigger",objIn:"x2kilcz6q",objOut:"k0tgkvnrd"}]},{name:"index",links:[{portIn:"Number",portOut:"index",objIn:"ea8xqnuo9",objOut:"k0tgkvnrd"}]},{name:"value",links:[{portIn:"Number 0",portOut:"value",objIn:"jv9912jq9",objOut:"k0tgkvnrd"}]}],objName:"Ops.Array.ArrayIteratorObjects"},{id:"fdsclzo6o",uiAttribs:{},portsOut:[{name:"UI",links:[{portIn:"Add to DOM",portOut:"UI",objIn:"k4iwedcj3",objOut:"fdsclzo6o"},{portIn:"Add to DOM",portOut:"UI",objIn:"v451ni5ju",objOut:"fdsclzo6o"}]},{name:"Overlay Mode",value:0},{name:"Remote Viewer",value:0},{name:"Is Standalone",value:0},{name:"Canvas Mode",value:0},{name:"Patch Field Visible",value:0}],objName:"Ops.Cables.UIMode"},{id:"jxnl6c02w",uiAttribs:{},portsOut:[{name:"trigger 0",links:[{portIn:"render",portOut:"trigger 0",objIn:"2296f4e6v",objOut:"jxnl6c02w"}]},{name:"trigger 1",links:[{portIn:"reset",portOut:"trigger 1",objIn:"kef43qbc6",objOut:"jxnl6c02w"}]},{name:"trigger 3",links:[{portIn:"Update",portOut:"trigger 3",objIn:"w55a5wcw4",objOut:"jxnl6c02w"}]},{name:"trigger 4",links:[{portIn:"exe",portOut:"trigger 4",objIn:"k0tgkvnrd",objOut:"jxnl6c02w"}]}],objName:"Ops.Trigger.Sequence"},{id:"0npn0ufui",uiAttribs:{},portsIn:[{name:"Scale Text",value:2.5},{name:"Scale",value:.75,title:"Line Scale"},{name:"Font",value:"Arial"},{name:"align index",value:1},{name:"align",value:"center"},{name:"vertical align index",value:1},{name:"vertical align",value:"Middle"},{name:"Line Height",value:1},{name:"Letter Spacing",value:0},{name:"filter index",value:2},{name:"filter",value:"mipmap"},{name:"Anisotropic index",value:0},{name:"Anisotropic",value:0},{name:"r",value:1},{name:"g",value:1},{name:"b",value:1},{name:"a",value:1}],portsOut:[{name:"Total Lines",value:1},{name:"Width",value:.5213274274553571},{name:"Font Available",value:0}],objName:"Ops.Gl.Meshes.TextMesh_v2"},{id:"mdd8frh1h",uiAttribs:{},portsOut:[{name:"FPS",value:31},{name:"MS",links:[{portIn:"Number",portOut:"MS",objIn:"z1a1ckv0p",objOut:"mdd8frh1h"}]}],objName:"Ops.Cables.FPS_v2"},{id:"z1a1ckv0p",uiAttribs:{},portsIn:[{name:"Decimal Places",value:4}],portsOut:[{name:"Result",links:[{portIn:"Text",portOut:"Result",objIn:"0npn0ufui",objOut:"z1a1ckv0p"}]}],objName:"Ops.String.NumberToString_v2"},{id:"2296f4e6v",uiAttribs:{},portsIn:[{name:"posX",value:1.13},{name:"posY",value:.38},{name:"posZ",value:0},{name:"scale",value:.74},{name:"rotX",value:0},{name:"rotY",value:0},{name:"rotZ",value:0}],portsOut:[{name:"trigger",links:[{portIn:"Render",portOut:"trigger",objIn:"0npn0ufui",objOut:"2296f4e6v"}]}],objName:"Ops.Graphics.Transform"},{id:"i0gwzksft",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.49,"r":0.6823529411764706,"g":0.9058823529411765,"b":0.9764705882352941},{"pos":0.201171875,"posy":0.49,"r":0.6823529411764706,"g":0.9058823529411765,"b":0.9764705882352941},{"pos":0.482421875,"posy":0.47,"r":0.9490196078431372,"g":0.8588235294117647,"b":0.9215686274509803},{"pos":0.83984375,"posy":0.49,"r":0.8,"g":0.8117647058823529,"b":0.92941176470
3098258824},{"pos":1,"posy":0.49,"r":0.8,"g":0.8117647058823529,"b":0.9294117647058824}]}'},{name:"Direction index",value:0},{name:"Direction",value:"X"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:512},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Texture 1",portOut:"Texture",objIn:"5xdaqppf3",objOut:"i0gwzksft"}]}],objName:"Ops.Gl.GradientTexture"},{id:"3q79e0gum",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.44,"r":0.7568627450980392,"g":0.8941176470588236,"b":0.8392156862745098},{"pos":0.189453125,"posy":0.44,"r":0.7568627450980392,"g":0.8941176470588236,"b":0.8392156862745098},{"pos":0.482421875,"posy":0.47,"r":0.9294117647058824,"g":0.8352941176470589,"b":0.7568627450980392},{"pos":0.82421875,"posy":0.42,"r":0.984313725490196,"g":0.8823529411764706,"b":0.7764705882352941},{"pos":1,"posy":0.42,"r":0.984313725490196,"g":0.8823529411764706,"b":0.7764705882352941}]}'},{name:"Direction index",value:0},{name:"Direction",value:"X"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:512},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Texture 2",portOut:"Texture",objIn:"5xdaqppf3",objOut:"3q79e0gum"}]}],objName:"Ops.Gl.GradientTexture"},{id:"d6v0ujept",uiAttribs:{},portsIn:[{name:"Fragment Code",value:"UNI sampler2D tex;\nUNI sampler2D texGradient;\nIN vec2 texCoord;\n{{MODULES_HEAD}}\nvoid main()\n{\n vec4 col=vec4(0.5,0.5,0.5,1.0);\n {{MODULE_COLOR}}\n \n col=texture(texGradient,texture(tex,texCoord).rr);\n outColor = col;\n}"},{name:"Vertex Code",value:"\n{{MODULES_HEAD}}\nIN vec3 vPosition; //!@\nIN vec2 attrTexCoord;\nIN vec3 attrVertNormal;\nIN vec3 attrTangent,attrBiTangent;\n\nIN float attrVertIndex;\n\nOUT vec2 texCoord;\nOUT vec3 norm;\nUNI mat4 projMatrix;\nUNI mat4 viewMatrix;\nUNI mat4 modelMatrix;\n\nvoid main()\n{\n texCoord=attrTexCoord;\n norm=attrVertNormal;\n vec4 pos=vec4(vPosition, 1.0);\n vec3 tangent=attrTangent;\n vec3 bitangent=attrBiTangent;\n mat4 mMatrix=modelMatrix;\n gl_PointSize=10.0;\n\n {{MODULE_VERTEX_POSITION}}\n\n mat4 modelViewMatrix=viewMatrix*mMatrix;\n {{MODULE_VERTEX_MODELVIEW}}\n\n gl_Position = projMatrix * modelViewMatrix * pos;\n}\n"},{name:"Use As Material",value:1}],portsOut:[{name:"trigger",links:[{portIn:"render",portOut:"trigger",objIn:"l1kn6r4jz",objOut:"d6v0ujept"}]},{name:"Has Errors",value:false}],objName:"Ops.Gl.Shader.CustomShader_v2"},{id:"5xdaqppf3",uiAttribs:{},portsOut:[{name:"Array",links:[{portIn:"array",portOut:"Array",objIn:"kwwso7f7t",objOut:"5xdaqppf3"}]},{name:"Count",value:11}],objName:"Ops.Gl.TextureArray"},{id:"kwwso7f7t",uiAttribs:{},portsOut:[{name:"value",links:[{portIn:"texGradient",portOut:"value",objIn:"d6v0ujept",objOut:"kwwso7f7t"}]}],objName:"Ops.Array.ArrayGetTexture"},{id:"6n3c7fcfa",uiAttribs:{},portsIn:[{name:"Attribute",value:"data-gradient"},{name:"Value",value:"5"},{name:"Active",value:1}],objName:"Ops.Html.Attributes.ElementSetAttribute"},{id:"gfzyagxbo",uiAttribs:{},portsOut:[{name:"Dataset",links:[{portIn:"Data",portOut:"Dataset",objIn:"ug5wi8tnq",objOut:"gfzyagxbo"}]}],objName:"Ops.Html.ElementDataSet"},{id:"ug5wi8tnq",uiAttribs:{},portsIn:[{name:"Key",value:"gradient"}],portsOut:[{name:"Result",links:[{portIn:"Number",portOut:"Result",objIn:"q92ipbq5s",objOut:"ug5wi8tnq"}]},{name:"Found",value:1}],objName:"Ops.Json.ObjectGetNumber_v2"},{id:"rtbgcu8ns",uiAttribs:{},portsIn:[{name:"Attribute",value:"data-gradient"},{name:"Value",value:"7"},{name:"Active",value:1}],objName:"Ops.Html.Attributes.ElementSetAttribute"},{id:"q92ipbq5s",uiAttribs:{},portsIn:[{name:"Number 2",value:1},{name:"Number 3",value:0},{name:"Number 4",value:0},{name:"Number 5",value:0},{name:"Number 6",value:0},{name:"Number 7",value:0},{name:"Number 8",value:0}],portsOut:[{name:"Result",links:[{portIn:"number1",portOut:"Result",objIn:"8gs8l0923",objOut:"q92ipbq5s"}]}],objName:"Ops.Boolean.OrNumber_v2"},{id:"dq43sb7fa",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.49,"r":1,"g":0.8588235294117647,"b":0.82352941176470
3098258},{"pos":0.201171875,"posy":0.49,"r":1,"g":0.8588235294117647,"b":0.8235294117647058},{"pos":0.482421875,"posy":0.47,"r":0.9647058823529412,"g":0.8666666666666667,"b":0.7686274509803922},{"pos":0.82421875,"posy":0.42,"r":0.9607843137254902,"g":0.7725490196078432,"b":0.796078431372549},{"pos":1,"posy":0.42,"r":0.9607843137254902,"g":0.7725490196078432,"b":0.796078431372549}]}'},{name:"Direction index",value:0},{name:"Direction",value:"X"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:512},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Texture 3",portOut:"Texture",objIn:"5xdaqppf3",objOut:"dq43sb7fa"}]}],objName:"Ops.Gl.GradientTexture"},{id:"ed03brr31",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.47,"r":0.8196078431372549,"g":0.9686274509803922,"b":0.9176470588235295},{"pos":0.201171875,"posy":0.47,"r":0.8196078431372549,"g":0.9686274509803922,"b":0.9176470588235295},{"pos":0.470703125,"posy":0.43,"r":0.8627450980392157,"g":0.8235294117647058,"b":0.9019607843137255},{"pos":0.82421875,"posy":0.42,"r":0.6078431372549019,"g":0.8431372549019608,"b":0.9764705882352941},{"pos":1,"posy":0.42,"r":0.6078431372549019,"g":0.8431372549019608,"b":0.9764705882352941}]}'},{name:"Direction index",value:0},{name:"Direction",value:"X"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:512},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Texture 5",portOut:"Texture",objIn:"5xdaqppf3",objOut:"ed03brr31"}]}],objName:"Ops.Gl.GradientTexture"},{id:"zguwq720i",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.49,"r":0.9647058823529412,"g":0.6823529411764706,"b":0.6745098039215687},{"pos":0.201171875,"posy":0.49,"r":0.9647058823529412,"g":0.6823529411764706,"b":0.6745098039215687},{"pos":0.482421875,"posy":0.47,"r":0.8901960784313725,"g":0.8235294117647058,"b":0.796078431372549},{"pos":0.8125,"posy":0.42,"r":0.8196078431372549,"g":0.9686274509803922,"b":0.9176470588235295},{"pos":1,"posy":0.42,"r":0.8196078431372549,"g":0.9686274509803922,"b":0.9176470588235295}]}'},{name:"Direction index",value:0},{name:"Direction",value:"X"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:512},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Texture 4",portOut:"Texture",objIn:"5xdaqppf3",objOut:"zguwq720i"}]}],objName:"Ops.Gl.GradientTexture"},{id:"jv9912jq9",uiAttribs:{},portsOut:[{name:"Output 1",links:[{portIn:"HTML Element",portOut:"Output 1",objIn:"gfzyagxbo",objOut:"jv9912jq9"}]},{name:"Output 4",links:[{portIn:"Element",portOut:"Output 4",objIn:"x2kilcz6q",objOut:"jv9912jq9"}]},{name:"Output 8",links:[{portIn:"Canvas",portOut:"Output 8",objIn:"9e055zmn9",objOut:"jv9912jq9"}]}],objName:"Ops.Json.SequenceObjects_v2"},{id:"ea8xqnuo9",uiAttribs:{},portsIn:[{name:"Decimal Places",value:4}],portsOut:[{name:"Result",value:"1"}],objName:"Ops.String.NumberToString_v2"},{id:"3n7daus8a",uiAttribs:{},portsIn:[{name:"r",value:1},{name:"g",value:0},{name:"b",value:.01343750119209286},{name:"a",value:.977942705154419}],portsOut:[{name:"texture_out",links:[{portIn:"Texture 0",portOut:"texture_out",objIn:"5xdaqppf3",objOut:"3n7daus8a"}]}],objName:"Ops.Gl.Textures.ColorTexture"},{id:"vy1rqk8m4",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.49,"r":0.796078431372549,"g":0.5137254901960784,"b":0.4000000000000001},{"pos":0.201171875,"posy":0.49,"r":0.796078431372549,"g":0.5137254901960784,"b":0.4000000000000001},{"pos":0.482421875,"posy":0.47,"r":0.796078431372549,"g":0.4000000000000001,"b":0.48235294117647065},{"pos":0.83984375,"posy":0.49,"r":0.5058823529411764,"g":0.23137254901960788,"b":0.380392156862745},{"pos":1,"posy":0.49,"r":0.5058823529411764,"g":0.23137254901960788,"b":0.380392156862745}]}'},{name:"Direction index",value:0},{name:"Direction",value:"X"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:512},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Texture 6",portOut:"Texture",objIn:"5xdaqppf3",objOut:"vy1rqk8m4"}]}],objName:"Ops.Gl.GradientTexture"}
30982,{id:"a5ps531gj",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.41,"r":0.796078431372549,"g":0.5137254901960784,"b":0.4000000000000001},{"pos":0.244140625,"posy":0.41,"r":0.796078431372549,"g":0.5137254901960784,"b":0.4000000000000001},{"pos":0.806640625,"posy":0.4,"r":0.24705882352941175,"g":0.2941176470588236,"b":0.7058823529411765},{"pos":1,"posy":0.4,"r":0.24705882352941175,"g":0.2941176470588236,"b":0.7058823529411765}]}'},{name:"Direction index",value:0},{name:"Direction",value:"X"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:512},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Texture 7",portOut:"Texture",objIn:"5xdaqppf3",objOut:"a5ps531gj"}]}],objName:"Ops.Gl.GradientTexture"},{id:"q1a025j90",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.49,"r":0.796078431372549,"g":0.5137254901960784,"b":0.4000000000000001},{"pos":0.201171875,"posy":0.49,"r":0.796078431372549,"g":0.5137254901960784,"b":0.4000000000000001},{"pos":0.482421875,"posy":0.47,"r":0.3176470588235294,"g":0.576470588235294,"b":0.7843137254901961},{"pos":0.82421875,"posy":0.42,"r":0.24705882352941178,"g":0.29411764705882365,"b":0.7098039215686275},{"pos":1,"posy":0.42,"r":0.24705882352941178,"g":0.29411764705882365,"b":0.7098039215686275}]}'},{name:"Direction index",value:0},{name:"Direction",value:"X"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:512},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Texture 8",portOut:"Texture",objIn:"5xdaqppf3",objOut:"q1a025j90"}]}],objName:"Ops.Gl.GradientTexture"},{id:"1h4budjny",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.44,"r":0.32941176470588235,"g":0.7098039215686274,"b":0.7254901960784313},{"pos":0.1953125,"posy":0.44,"r":0.32941176470588235,"g":0.7098039215686274,"b":0.7254901960784313},{"pos":0.755859375,"posy":0.44,"r":0.5921568627450979,"g":0.3764705882352941,"b":0.7450980392156863},{"pos":1,"posy":0.44,"r":0.5921568627450979,"g":0.3764705882352941,"b":0.7450980392156863}]}'},{name:"Direction index",value:0},{name:"Direction",value:"X"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:512},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Texture 10",portOut:"Texture",objIn:"5xdaqppf3",objOut:"1h4budjny"}]}],objName:"Ops.Gl.GradientTexture"},{id:"y74yu88h3",uiAttribs:{},portsIn:[{name:"Gradient",value:'{"keys":[{"pos":0,"posy":0.49,"r":0.796078431372549,"g":0.4000000000000001,"b":0.48235294117647065},{"pos":0.201171875,"posy":0.49,"r":0.796078431372549,"g":0.4000000000000001,"b":0.48235294117647065},{"pos":0.79296875,"posy":0.45,"r":0.24705882352941178,"g":0.29411764705882365,"b":0.7098039215686275},{"pos":1,"posy":0.45,"r":0.24705882352941178,"g":0.29411764705882365,"b":0.7098039215686275}]}'},{name:"Direction index",value:0},{name:"Direction",value:"X"},{name:"Smoothstep",value:0},{name:"Step",value:0},{name:"Flip",value:0},{name:"sRGB",value:0},{name:"Oklab",value:0},{name:"Size",value:512},{name:"filter index",value:1},{name:"filter",value:"linear"},{name:"wrap index",value:0},{name:"wrap",value:"clamp to edge"},{name:"Dither",value:0},{name:"Gradient Array",value:0}],portsOut:[{name:"Texture",links:[{portIn:"Texture 9",portOut:"Texture",objIn:"5xdaqppf3",objOut:"y74yu88h3"}]}],objName:"Ops.Gl.GradientTexture"},{id:"wx7oud6bb",uiAttribs:{},portsOut:[{name:"Body",links:[{portIn:"Element",portOut:"Body",objIn:"zeenzfdj7",objOut:"wx7oud6bb"}]}],objName:"Ops.Html.DocumentBody"},{id:"w500aqnlj",uiAttribs:{},portsIn:[{name:"Value 0",value:0},{name:"Value 1",value:5}],portsOut:[{name:"Out Value",links:[{portIn:"number2",portOut:"Out Value",objIn:"8gs8l0923",objOut:"w500aqnlj"}]}],objName:"Ops.Boolean.BoolToNumber_v2"},{id:"8gs8l0923",uiAttribs:{},portsOut:[{name:"result",links:[{portIn:"index",portOut:"result",objIn:"kwwso7f7t",objOut:"8gs8l0923"}]}],objName:"Ops.Math.Sum"},{id:"zeenzfdj7",uiAttribs:{},portsIn:[{name:"Classname",value:"dark"}],portsOut:[{name:"Has Class",links:[{portIn:"Use Value 1",portOut:"Has Class",objIn:"w500aqnlj",objOut:"zeenzfdj7"}]}],objName:"Ops.Html.ElementHasClass"},{id:"j8z3obse7",uiAttribs:{},portsIn:[{name:"interval",value:100},{name:"Active",value:1}],portsOut:[{name:"trigger",links:[{portIn:"Update",portOut:"trigger",objIn:"zeenzfdj7",objOut:"j8z3obse7"}]}],objName:"Ops.Trigger.Interval"},{id:"9e055zmn9",uiAttribs:{},portsIn:[{name:"Smooth",value:0}],portsOut:[{name:"Next",links:[{portIn:"exe",portOut:"Next",objIn:"kef43qbc6",objOut:"9e055zmn9"}]}],objName:"Ops.Dev.Html.GlCopyToCanvas"},{id:"kef43qbc6",uiAttribs:{},portsOut:[{name:"timesTriggered",value:2}],objName:"Ops.Trigger.TriggerCounter"},{id:"x2kilcz6q",uiAttribs:{},portsOut:[{name:"Next",links:[{portIn:"exe",portOut:"Next",objIn:"0yg96xu13",objOut:"x2kilcz6q"}]},{name:"Fully Visible",value:1},{name:"Partly Visible",links:[{portIn:"boolean",portOut:"Partly Visible",objIn:"0yg96xu13",objOut:"x2kilcz6q"}]}],objName:"Ops.Gl.ElementInBrowserViewport"},{id:"k0n9z9hw5",uiAttribs:{},portsIn:[{name:"Milliseconds",value:30}],portsOut:[{name:"Progress",value:.5566666682561239}],objName:"Ops.Trigger.TriggerLimiter"},{id:"s0scffwlv",uiAttribs:{},portsIn:[{name:"Show Info",value:0},{name:"Visualize outside 0-1 index",value:1},{name:"Visualize outside 0-1",value:"Anim"},{name:"Alpha index",value:0},{name:"Alpha",value:"A"},{name:"Show Color",value:0},{name:"X",value:.5},{name:"Y",value:.5}],portsOut:[{name:"Info",value:""}],objName:"Ops.Ui.VizTexture"},{id:"s57duwb38",uiAttribs:{},portsIn:[{name:"Event Name",value:"pointerenter"},{name:"Use Capture",value:0},{name:"Prevent Default",value:1},{name:"Stop Propagation",value:1}],portsOut:[{name:"Event Trigger",links:[{portIn:"True",portOut:"Event Trigger",objIn:"i327s2pmo",objOut:"s57duwb38"}]},{name:"Index",value:2},{name:"Event Element",links:[{portIn:"Object",portOut:"Event Element",objIn:"qqs94yk5y",objOut:"s57duwb38"}]}],objName:"Ops.Html.Event.ElementsArrayEventHandler"},{id:"lbhmmqcjd",uiAttribs:{},portsIn:[{name:"Query",value:".navEle"},{name:"Mode index",value:0},{name:"Mode",value:"document"},{name:"Type index",value:0},{name:"Type",value:"text/html"},{name:"Document",value:"xml"}],portsOut:[{name:"Elements",links:[{portIn:"Elements",portOut:"Elements",objIn:"s57duwb38",objOut:"lbhmmqcjd"},{portIn:"array",portOut:"Elements",objIn:"hsvdn4m92",objOut:"lbhmmqcjd"},{portIn:"Elements",portOut:"Elements",objIn:"vgg7zas9c",objOut:"lbhmmqcjd"}]}],objName:"Ops.Html.QuerySelectorAll_v2"},{id:"f5ez8gwci",uiAttribs:{},portsIn:[{name:"Play Timeline",value:1}],portsOut:[{name:"Finished Initial Loading",value:1},{name:"Loading",value:0},{name:"Progress",value:1},{name:"Trigger Loading Finished ",links:[{portIn:"Update",portOut:"Trigger Loading Finished ",objIn:"lbhmmqcjd",objOut:"f5ez8gwci"},{portIn:"false",portOut:"Trigger Loading Finished ",objIn:"i327s2pmo",objOut:"f5ez8gwci"},{portIn:"Update",portOut:"Trigger Loading Finished ",objIn:"dg3nmlrj4",objOut:"f5ez8gwci"}]}],objName:"Ops.Cables.LoadingStatus_v2"},{id:"lplmetyh0",uiAttribs:{},portsIn:[{name:"interval",value:20},{name:"Active",value:1}],portsOut:[{name:"trigger",links:[{portIn:"Update",portOut:"trigger",objIn:"7jycjpihs",objOut:"lplmetyh0"},{portIn:"Update",portOut:"trigger",objIn:"i7oph5tlh",objOut:"lplmetyh0"},{portIn:"exe",portOut:"trigger",objIn:"2shr81z2b",objOut:"lplmetyh0"},{portIn:"Update",portOut:"trigger",objIn:"dg3nmlrj4",objOut:"lplmetyh0"}]}],objName:"Ops.Trigger.Interval"},{id:"qqs94yk5y",uiAttribs:{},portsOut:[{name:"Changed",links:[{portIn:"True",portOut:"Changed",objIn:"4grtfyy72",objOut:"qqs94yk5y"},{portIn:"Update",portOut:"Changed",objIn:"hlz0vgjw0",objOut:"qqs94yk5y"}]},{name:"Result",links:[{portIn:"Element",portOut:"Result",objIn:"hlz0vgjw0",objOut:"qqs94yk5y"}]}],objName:"Ops.Trigger.TriggerOnChangeObject_v2"},{id:"125kds9x7",uiAttribs:{},portsIn:[{name:"Translate Active",value:1},{name:"Unit index",value:0},{name:"Unit",value:"px"},{name:"Scale Active",value:1},{name:"Scale",value:1},{name:"Rotate Active",value:1},{name:"Rot Z",value:0},{name:"Set Origin",value:1},{name:"Origin X index",value:1},{name:"Origin X",value:"center"},{name:"Origin Y index",value:1},{name:"Origin Y",value:"center"},{name:"Z Index Active",value:0},{name:"Z Index",value:100}],portsOut:[{name:"Passthrough",links:[{portIn:"Element",portOut:"Passthrough",objIn:"8kqwdb2te",objOut:"125kds9x7"}]}],objName:"Ops.Html.CSS.ElementCssTransform_v2"},{id:"6s257oe59",uiAttribs:{},portsIn:[{name:"Separate inc/dec",value:0},{name:"Inc factor",value:6,title:"Inc/Dec factor"}],portsOut:[{name:"Result",links:[{portIn:"Number",portOut:"Result",objIn:"cy1w71oad",objOut:"6s257oe59"}]}],objName:"Ops.Anim.Smooth"},{id:"8kqwdb2te",uiAttribs:{},portsIn:[{name:"Thickness",value:3},{name:"Radius",value:0},{name:"Color R",value:1},{name:"Color G",value:1},{name:"Color B",value:1},{name:"Top",value:0},{name:"Bottom",value:1},{name:"Left",value:0},{name:"Right",value:0}],objName:"Ops.Html.CSS.ElementCssBorder"},{id:"8lrzig6p9",uiAttribs:{},portsIn:[{name:"number2",value:30.54}],portsOut:[{name:"result",links:[{portIn:"Number",portOut:"result",objIn:"larvzjk20",objOut:"8lrzig6p9"}]}],objName:"Ops.Math.Sum"},{id:"7jycjpihs",uiAttribs:{},portsIn:[{name:"Separate inc/dec",value:0},{name:"Inc factor",value:12,title:"Inc/Dec factor"}],portsOut:[{name:"Next",links:[{portIn:"Update",portOut:"Next",objIn:"6s257oe59",objOut:"7jycjpihs"}]},{name:"Result",links:[{portIn:"Number",portOut:"Result",objIn:"ezv
309820rn7og",objOut:"7jycjpihs"}]}],objName:"Ops.Anim.Smooth"},{id:"hsvdn4m92",uiAttribs:{},portsIn:[{name:"index",value:0}],portsOut:[{name:"value",links:[{portIn:"Object",portOut:"value",objIn:"uwgg5z4xi",objOut:"hsvdn4m92"}]}],objName:"Ops.Array.ArrayGetObject"},{id:"uwgg5z4xi",uiAttribs:{},portsOut:[{name:"Result",links:[{portIn:"Element",portOut:"Result",objIn:"dg3nmlrj4",objOut:"uwgg5z4xi"}]}],objName:"Ops.Trigger.TriggerOnChangeObject_v2"},{id:"nstfby7ri",uiAttribs:{},portsOut:[{name:"result",links:[{portIn:"Value",portOut:"result",objIn:"6s257oe59",objOut:"nstfby7ri"}]}],objName:"Ops.Math.Subtract"},{id:"acm21460z",uiAttribs:{},portsIn:[{name:"value",value:12.15}],portsOut:[{name:"result",links:[{portIn:"number2",portOut:"result",objIn:"nstfby7ri",objOut:"acm21460z"},{portIn:"number1",portOut:"result",objIn:"pw73gwurf",objOut:"acm21460z"}]}],objName:"Ops.Number.Number"},{id:"56an9ch4y",uiAttribs:{},portsOut:[{name:"result",links:[{portIn:"number1",portOut:"result",objIn:"igt17n7hl",objOut:"56an9ch4y"}]}],objName:"Ops.Math.Sum"},{id:"pw73gwurf",uiAttribs:{},portsIn:[{name:"number2",value:2}],portsOut:[{name:"result",links:[{portIn:"number2",portOut:"result",objIn:"56an9ch4y",objOut:"pw73gwurf"}]}],objName:"Ops.Math.Multiply"},{id:"vd3wi4tnc",uiAttribs:{},portsIn:[{name:"Text",value:"Element"},{name:"Position index",value:3},{name:"Position",value:"Fixed"},{name:"Interactive index",value:2},{name:"Interactive",value:"No Pointer Events"},{name:"Set Size",value:1},{name:"Height",value:0},{name:"Size Units index",value:0},{name:"Size Units",value:"px"},{name:"Overflow index",value:1},{name:"Overflow",value:"Hidden"},{name:"Inline Style",value:""},{name:"CSS Class",value:"navEleUnderline"},{name:"Disable CSS Props",value:""},{name:"Display index",value:1},{name:"Display",value:"Block"},{name:"Tag Name",value:"div"},{name:"Opacity",value:1},{name:"Propagate Click-Events",value:1},{name:"Add to DOM",value:1}],portsOut:[{name:"DOM Element",links:[{portIn:"Element",portOut:"DOM Element",objIn:"125kds9x7",objOut:"vd3wi4tnc"}]},{name:"Hovering",value:0}],objName:"Ops.Html.Elements.Element_v2"},{id:"i7oph5tlh",uiAttribs:{},portsIn:[{name:"Var Name",value:"wp-admin--admin-bar--height"}],portsOut:[{name:"Result",links:[{portIn:"String",portOut:"Result",objIn:"fd567nfbv",objOut:"i7oph5tlh"}]}],objName:"Ops.Html.CSS.GetCssVariable"},{id:"fd567nfbv",uiAttribs:{},portsOut:[{name:"Number",value:0},{name:"Not a number",value:1}],objName:"Ops.String.StringToNumber"},{id:"vk4ir55py",uiAttribs:{},portsIn:[{name:"number1",value:0},{name:"number2",value:0}],portsOut:[{name:"result",value:0}],objName:"Ops.Math.Sum"},{id:"4grtfyy72",uiAttribs:{},portsOut:[{name:"Result",links:[{portIn:"number2",portOut:"Result",objIn:"igt17n7hl",objOut:"4grtfyy72"}]}],objName:"Ops.Boolean.BoolByTrigger"},{id:"igt17n7hl",uiAttribs:{},portsOut:[{name:"result",links:[{portIn:"Value",portOut:"result",objIn:"7jycjpihs",objOut:"igt17n7hl"}]}],objName:"Ops.Math.Multiply"},{id:"ezv0rn7og",uiAttribs:{},portsOut:[{name:"Result",links:[{portIn:"Width",portOut:"Result",objIn:"vd3wi4tnc",objOut:"ezv0rn7og"}]}],objName:"Ops.Math.Floor"},{id:"larvzjk20",uiAttribs:{},portsOut:[{name:"Result",links:[{portIn:"Translate Y",portOut:"Result",objIn:"125kds9x7",objOut:"larvzjk20"}]}],objName:"Ops.Math.Floor"},{id:"cy1w71oad",uiAttribs:{},portsOut:[{name:"Result",links:[{portIn:"Translate X",portOut:"Result",objIn:"125kds9x7",objOut:"cy1w71oad"}]}],objName:"Ops.Math.Floor"},{id:"f7v3z4ifb",uiAttribs:{},portsIn:[{name:"number1",value:12},{name:"number2",value:1}],portsOut:[{name:"result",links:[{portIn:"Dec factor",portOut:"result",objIn:"7jycjpihs",objOut:"f7v3z4ifb"}]}],objName:"Ops.Math.Multiply"},{id:"8dl0clmfb",uiAttribs:{},portsIn:[{name:"number1",value:4},{name:"number2",value:1}],portsOut:[{name:"result",links:[{portIn:"Dec factor",portOut:"result",objIn:"6s257oe59",objOut:"8dl0clmfb"}]}],objName:"Ops.Math.Multiply"},{id:"r8plq62xm",uiAttribs:{},portsOut:[{name:"time",links:[{portIn:"value",portOut:"time",objIn:"5d9zpphrg",objOut:"r8plq62xm"}]}],objName:"Ops.Trigger.TimeSinceTrigger"},{id:"vgg7zas9c",uiAttribs:{},portsIn:[{name:"Event Name",value:"pointerout"},{name:"Use Capture",value:0},{name:"Prevent Default",value:1},{name:"Stop Propagation",value:1}],portsOut:[{name:"Event Trigger",links:[{portIn:"trigger",portOut:"Event Trigger",objIn:"r8plq62xm",objOut:"vgg7zas9c"},{portIn:"false",portOut:"Event Trigger",objIn:"i327s2pmo",objOut:"vgg7zas9c"}]},{name:"Index",value:2}],objName:"Ops.Html.Event.ElementsArrayEventHandler"},{id:"5d9zpphrg",uiAttribs:{},portsIn:[{name:"old min",value:1},{name:"old max",value:2},{name:"new min",value:1},{name:"new max",value:0},{name:"Easing index",value:0},{name:"Easing",value:"Linear"},{name:"Clamp",value:1}],portsOut:[{name:"result",links:[{portIn:"Value 0",portOut:"result",objIn:"e4m9gdkpa",objOut:"5d9zpphrg"}]}],objName:"Ops.Math.MapRange"},{id:"i327s2pmo",uiAttribs:{},portsOut:[{name:"Result",links:[{portIn:"Index",portOut:"Result",objIn:"e4m9gdkpa",objOut:"i327s2pmo"}]}],objName:"Ops.Boolean.BoolByTrigger"},{id:"e4m9gdkpa",uiAttribs:{},portsIn:[{name:"Value 1",value:1},{name:"Value 2",value:0},{name:"Value 3",value:0},{name:"Value 4",value:0},{name:"Value 5",value:0},{name:"Value 6",value:0},{name:"Value 7",value:0},{name:"Value 8",value:0},{name:"Value 9",value:0},{name:"Value 10",value:0},{name:"Value 11",value:0},{name:"Value 12",value:0},{name:"Value 13",value:0},{name:"Value 14",value:0},{name:"Value 15",value:0}],portsOut:[{name:"Result",value:1}],objName:"Ops.Number.SwitchNumber"},{id:"cq101bpy0",uiAttribs:{},portsIn:[{name:"number2",value:140}],portsOut:[{name:"result",links:[{portIn:"Boolean",portOut:"result",objIn:"sm8ncv5hb",objOut:"cq101bpy0"}]}],objName:"Ops.Math.Compare.GreaterThan"},{id:"sm8ncv5hb",uiAttribs:{},portsOut:[{name:"Result",links:[{portIn:"bool",portOut:"Result",objIn:"2shr81z2b",objOut:"sm8ncv5hb"}]}],objName:"Ops.Boolean.Not"},{id:"2shr81z2b",uiAttribs:{},portsIn:[{name:"easing index",value:0},{name:"easing",value:"linear"},{name:"duration",value:.25},{name:"Direction index",value:0},{name:"Direction",value:"Both"},{name:"value false",value:0},{name:"value true",value:1}],portsOut:[{name:"value",links:[{portIn:"Color A",portOut:"value",objIn:"8kqwdb2te",objOut:"2shr81z2b"}]},{name:"finished",value:1}],objName:"Ops.Anim.BoolAnim"},{id:"ejp5aupd7",uiAttribs:{},portsIn:[{name:"Coordinates index",value:2},{name:"Coordinates",value:"Pixel"},{name:"Area index",value:2},{name:"Area",value:"Document"},{name:"flip y",value:0},{name:"right click prevent default",value:0},{name:"Events index",value:0},{name:"Events",value:"Pointer"},{name:"Passive Events",value:0},{name:"Active",value:1}],portsOut:[{name:"x",value:692.1875},{name:"y",links:[{portIn:"number1",portOut:"y",objIn:"cq101bpy0",objOut:"ejp5aupd7"}]},{name:"Button is down",value:0},{name:"Mouse is hovering",value:1},{name:"Movement X",value:6},{name:"Movement Y",value:-7}],objName:"Ops.Devices.Mouse.Mouse_v4"},{id:"7b5sy2k5n",uiAttribs:{},portsOut:[{name:"UI",links:[{portIn:"value",portOut:"UI",objIn:"c9r4edomb",objOut:"7b5sy2k5n"}]},{name:"Overlay Mode",value:0},{name:"Remote Viewer",value:0},{name:"Is Standalone",value:0},{name:"Canvas Mode",value:0},{name:"Patch Field Visible",value:0}],objName:"Ops.Cables.UIMode"},{id:"bsawys36s",uiAttribs:{},portsIn:[{name:"Text",value:"Elementsrttsrsrttsrsrtstrstr"},{name:"Position index",value:0},{name:"Position",value:"Absolute"},{name:"Interactive index",value:0},{name:"Interactive",value:"True"},{name:"Set Size",value:0},{name:"Width",value:100},{name:"Height",value:100},{name:"Size Units index",value:0},{name:"Size Units",value:"px"},{name:"Overflow index",value:1},{name:"Overflow",value:"Hidden"},{name:"Inline Style",value:""},{name:"CSS Class",value:"navEle"},{name:"Disable CSS Props",value:""},{name:"Display index",value:1},{name:"Display",value:"Block"},{name:"Tag Name",value:"div"},{name:"Opacity",value:1},{name:"Propagate Click-Events",value:1}],portsOut:[{name:"DOM Element",links:[{portIn:"Element",portOut:"DOM Element",objIn:"jtrogrndz",objOut:"bsawys36s"}]},{name:"Hovering",value:0}],objName:"Ops.Html.Elements.Element_v2"},{id:"gd8iz7r4u",uiAttribs:{},portsIn:[{name:"Text",value:"Elementf"},{name:"Position index",value:0},{name:"Position",value:"Absolute"},{name:"Interactive index",value:0},{name:"Interactive",value:"True"},{name:"Set Size",value:0},{name:"Width",value:100},{name:"Height",value:100},{name:"Size Units index",value:0},{name:"Size Units",value:"px"},{name:"Overflow index",value:1},{name:"Overflow",value:"Hidden"},{name:"Inline Style",value:""},{name:"CSS Class",value:"navEle"},{name:"Disable CSS Props",value:""},{name:"Display index",value:1},{name:"Display",value:"Block"},{name:"Tag Name",value:"div"},{name:"Opacity",value:1},{name:"Propagate Click-Events",value:1}],portsOut:[{name:"DOM Element",links:[{portIn:"Element",portOut:"DOM Element",objIn:"uclmwhn49",objOut:"gd8iz7r4u"}]},{name:"Hovering",value:0}],objName:"Ops.Html.Elements.Element_v2"},{id:"wq0hvpzj0",uiAttribs:{},portsIn:[{name:"Text",value:"aaa"},{name:"Position index",value:0},{name:"Position",value:"Absolute"},{name:"Interactive index",value:0},{name:"Interactive",value:"True"},{name:"Set Size",value:0},{name:"Width",value:100},{name:"Height",value:100},{name:"Size Units index",value:0},{name:"Size Units",value:"px"},{name:"Overflow index",value:1},{name:"Overflow",value:"Hidden"},{name:"Inline Style",value:""},{name:"CSS Class",value:"navEle"},{name:"Disable CSS Props",value:""},{name:"Display index",value:1},{name:"Display",value:"Block"},{name:"Tag Name",value:"div"},{name:"Opacity",value:1},{name:"Propagate Click-Events",value:1}],portsOut:[{name:"DOM Element",links:[{portIn:"Element",portOut:"DOM Element",objIn:"z5tn103ee",objOut:"wq0hvpzj0"}]},{name:"Hovering",value:0}],objName:"Ops.Html.Elements.Element_v2"},{id:"c9r4edomb",uiAttribs:{},portsOut:[{name:"result",links:[{portIn:"Add to DOM",portOut:"result",objIn:"bsawys36s",objOut:"c9r4edomb"},{portIn:"Add to DOM",portOut:"result",objIn:"gd8iz7r4u",objOut:"c9r4edomb"},{portIn:"Add to DOM",portOut:"result",objIn:"wq0hvpzj0",objOut:"c9r4edomb"}]}],objName:"Ops.Boolean.Boolean"},{id:"jtrogrndz",uiAttribs:{},portsIn:[{name:"Translate Active",value:1},{name:"Translate X",value:421.83},{name:"Translate Y",value:0},{name:"Unit index",value:0},{name:"Unit",value:"px"},{name:"Scale Active",value:1},{name:"Scale",value:1},{name:"Rotate Active",value:1},{name:"Rot Z",value:0},{name:"Set Origin",value:1},{name:"Origin X index",value:1},{name:"Origin X",value:"center"},{name:"Origin Y index",value:1},{name:"Origin Y",value:"center"},{name:"Z Index Active",value:0},{name:"Z Index",value:100}],objName:"Ops.Html.CSS.ElementCssTransform_v2"},{id:"uclmwhn49",uiAttribs:{},portsIn:[{name:"Translate Active",value:1},{name:"Translate X",value:300.08},{name:"Translate Y",value:403.46},{name:"Unit index",value:0},{name:"Unit",value:"px"},{name:"Scale Active",value:1},{name:"Scale",value:1},{name:"Rotate Active",value:1},{name:"Rot Z",value:0},{name:"Set Origin",value:1},{name:"Origin X index",value:1},{name:"Origin X",value:"center"},{name:"Origin Y index",value:1},{name:"Origin Y",value:"center"},{name:"Z Index Active",value:0},{name:"Z Index",value:100}],objName:"Ops.Html.CSS.ElementCssTransform_v2"},{id:"z5tn103ee",uiAttribs:{},portsIn:[{name:"Translate Active",value:1},{name:"Translate X",value:69.42},{name:"Translate Y",value:0},{name:"Unit index",value:0},{name:"Unit",value:"px"},{name:"Scale Active",value:1},{name:"Scale",value:1},{name:"Rotate Active",value:1},{name:"Rot Z",value:0},{name:"Set Origin",value:1},{name:"Origin X index",value:1},{name:"Origin X",value:"center"},{name:"Origin Y index",value:1},{name:"Origin Y",value:"center"},{name:"Z Index Active",value:0},{name:"Z Index",value:100}],objName:"Ops.Html.CSS.ElementCssTransform_v2"},{id:"hlz0vgjw0",uiAttribs:{},portsIn:[{name:"Pixel Units index",value:0},{name:"Pixel Units",value:"CSS Pixels"},{name:"Position index",value:0},{name:"Position",value:"In Canvas"}],portsOut:[{name:"X",links:[{portIn:"number1",portOut:"X",objIn:"nstfby7ri",objOut:"hlz0vgjw0"}]},{name:"Y",value:0},{name:"Width",links:[{portIn:"number1",portOut:"Width",objIn:"56an9ch4y",objOut:"hlz0vgjw0"}]},{name:"Height",value:0}],objName:"Ops.Html.ElementClientRect"},{id:"dg3nmlrj4",uiAttribs:{},portsIn:[{name:"Pixel Units index",value:0},{name:"Pixel Units",value:"CSS Pixels"},{name:"Position index",value:1},{name:"Position",value:"Absolute"}],portsOut:[{name:"X",links:[{portIn:"Value",portOut:"X",objIn:"6s257oe59",objOut:"dg3nmlrj4"}]},{name:"Y",links:[{portIn:"number1",portOut:"Y",objIn:"8lrzig6p9",objOut:"dg3nmlrj4"}]},{name:"Width",value:156.609375},{name:"Height",value:18}],objName:"Ops.Html.ElementClientRect"}],export:{time:"2025-10-07 10:27",service:"html",exportNumber:55}};if(!CABLES.exportedPatch){CABLES.exportedPatch=CABLES.exportedPatches["zwNKaV"]}"use strict";var CABLES=CABLES||{};CABLES.OPS=CABLES.OPS||{};var Ops=Ops||{};Ops.Gl=Ops.Gl||{};Ops.Ui=Ops.Ui||{};Ops.Dev=Ops.Dev||{};Ops.Anim=Ops.Anim||{};Ops.Html=Ops.Html||{};Ops.Json=Ops.Json||{};Ops.Math=Ops.Math||{};Ops.Array=Ops.Array||{};Ops.Cables=Ops.Cables||{};Ops.Number=Ops.Number||{};Ops.String=Ops.String||{};Ops.Boolean=Ops.Boolean||{};Ops.Devices=Ops.Devices||{};Ops.Trigger=Ops.Trigger||{};Ops.Dev.Html=Ops.Dev.Html||{};Ops.Graphics=Ops.Graphics||{};Ops.Html.CSS=Ops.Html.CSS||{};Ops.Gl.Meshes=Ops.Gl.Meshes||{};Ops.Gl.Shader=Ops.Gl.Shader||{};Ops.Html.Event=Ops.Html.Event||{};Ops.Gl.Textures=Ops.Gl.Textures||{};Ops.Math.Compare=Ops.Math.Compare||{};Ops.Devices.Mouse=Ops.Devices.Mouse||{};Ops.Html.Elements=Ops.Html.Elements||{};Ops.Gl.ImageCompose=Ops.Gl.ImageCompose||{};Ops.Html.Attributes=Ops.Html.Attributes||{};Ops.Gl.ImageCompose.Noise=Ops.Gl.ImageCompose.Noise||{};Ops.Gl.MainLoop_v2=class extends CABLES.Op{constructor(){super(...arguments);const i=this;const e=i.attachments={};const t=i.inFloat("Max Pixel Density (DPR)",2),n=i.inValue("FPS Limit",0),r=i.inValueBool("Reduce FPS unfocussed",false),s=i.inValueBool("Trans
30982parent",false),a=i.inValueBool("Active",1),o=i.inValueBool("Focus canvas",1),l=i.outTrigger("trigger"),u=i.outNumber("width"),h=i.outNumber("height"),c=i.outNumber("Pixel Density");i.onAnimFrame=C;t.onChange=A;const g=i.patch.cg=i.patch.cgl;let f=0;let d=0;let m=null;let p=false;if(!i.patch.cgl)i.uiAttr({error:"No webgl cgl context"});const _=vec3.create();vec3.set(_,0,0,0);const v=vec3.create();vec3.set(v,0,0,-2);let x=true;let b=null;let T=true;let E=true;window.addEventListener("blur",()=>{T=false});window.addEventListener("focus",()=>{T=true});document.addEventListener("visibilitychange",()=>{E=!document.hidden});R();i.patch.tempData.mainloopOp=this;function A(){O();if(CABLES.UI){if(t.get()<1)i.patch.cgl.canvas.style.imageRendering="pixelated"}i.patch.cgl.updateSize();if(CABLES.UI)gui.setLayout()}a.onChange=function(){i.patch.removeOnAnimFrame(i);if(a.get()){i.setUiAttrib({extendTitle:""});i.onAnimFrame=C;i.patch.addOnAnimFrame(i);i.log("adding again!")}else{i.setUiAttrib({extendTitle:"Inactive"})}};function S(){if(r.get()){if(!E)return 10;if(!T)return 30}return n.get()}i.onDelete=function(){g.gl.clearColor(0,0,0,0);g.gl.clear(g.gl.COLOR_BUFFER_BIT|g.gl.DEPTH_BUFFER_BIT)};function O(){if(t.get()!=0)i.patch.cgl.pixelDensity=Math.min(t.get(),window.devicePixelRatio);else i.patch.cgl.pixelDensity=window.devicePixelRatio}function C(e){if(!a.get())return;if(g.aborted||g.canvas.clientWidth===0||g.canvas.clientHeight===0)return;i.patch.cg=g;O();const t=performance.now();i.patch.config.fpsLimit=S();if(g.canvasWidth==-1){g.setCanvas(i.patch.config.glCanvasId);return}if(g.canvasWidth!=u.get()||g.canvasHeight!=h.get()){u.set(g.canvasWidth/1);h.set(g.canvasHeight/1)}if(CABLES.now()-d>1e3){CGL.fpsReport=CGL.fpsReport||[];if(i.patch.loading.getProgress()>=1&&d!==0)CGL.fpsReport.push(f);f=0;d=CABLES.now()}CGL.MESH.lastShader=null;CGL.MESH.lastMesh=null;g.renderStart(g,_,v);if(!s.get())g.gl.clearColor(0,0,0,1);else g.gl.clearColor(0,0,0,0);g.gl.clear(g.gl.COLOR_BUFFER_BIT|g.gl.DEPTH_BUFFER_BIT);l.trigger();if(CGL.MESH.lastMesh)CGL.MESH.lastMesh.unBind();if(CGL.Texture.previewTexture){if(!CGL.Texture.texturePreviewer)CGL.Texture.texturePreviewer=new CGL.Texture.texturePreview(g);CGL.Texture.texturePreviewer.render(CGL.Texture.previewTexture)}g.renderEnd(g);
30982i.patch.cg=null;if(!s.get()){g.gl.clearColor(1,1,1,1);g.gl.colorMask(false,false,false,true);g.gl.clear(g.gl.COLOR_BUFFER_BIT);g.gl.colorMask(true,true,true,true)}if(!g.tempData.phong)g.tempData.phong={};f++;if(x){if(o.get())g.canvas.focus();x=false}c.set(i.patch.cgl.pixelDensity);i.patch.cgl.profileData.profileMainloopMs=performance.now()-t}function R(){clearTimeout(m);m=setTimeout(()=>{if(i.patch.getOpsByObjName(i.name).length>1){i.setUiError("multimainloop","there should only be one mainloop op!");if(!p)p=i.patch.addEventListener("onOpDelete",R)}else i.setUiError("multimainloop",null,1)},500)}}};CABLES.OPS["f1029550-d877-42da-9b1e-63a5163a0350"]={f:Ops.Gl.MainLoop_v2,objName:"Ops.Gl.MainLoop_v2"};Ops.Trigger.Sequence=class extends CABLES.Op{constructor(){super(...arguments);const s=this;const e=s.attachments={};const t=s.inTrigger("exe"),i=s.inTriggerButton("Clean up connections");s.setUiAttrib({resizable:true,resizableY:false,stretchPorts:true});const n=[],a=[],r=16;let o=null,l=[];t.onTriggered=c;i.onTriggered=g;i.setUiAttribs({hideParam:true,hidePort:true});for(let t=0;t<r;t++){const f=s.outTrigger("trigger "+t);a.push(f);f.onLinkChanged=h;if(t<r-1){let e=s.inTrigger("exe "+t);e.onTriggered=c;n.push(e)}}u();function u(){l.length=0;for(let e=0;e<a.length;e++)if(a[e].links.length>0)l.push(a[e])}function h(){u();clearTimeout(o);o=setTimeout(()=>{let t=false;for(let e=0;e<a.length;e++)if(a[e].links.length>1)t=true;i.setUiAttribs({hideParam:!t});if(s.isCurrentUiOp())s.refreshParams()},60)}function c(){for(let e=0;e<l.length;e++)l[e].trigger()}function g(){let n=0;for(let i=0;i<a.length;i++){let t=[];if(a[i].links.length>1)for(let e=1;e<a[i].links.length;e++){while(a[n].links.length>0)n++;t.push(a[i].links[e]);const r=a[i].links[e].getOtherPort(a[i]);s.patch.link(s,"trigger "+n,r.op,r.name);n++}for(let e=0;e<t.length;e++)t[e].remove()}h();u()}}};CABLES.OPS["a466bc1f-06e9-4595-8849-bffb9fe22f99"]={f:Ops.Trigger.Sequence,objName:"Ops.Trigger.Sequence"};Ops.Gl.ImageCompose.ImageCompose_v4=class extends CABLES.Op{constructor(){super(...arguments);const i=this;const e=i.attachments={imgcomp_frag:"IN vec2 texCoord;\nUNI vec4 bgColor;\nUNI sampler2D tex;\n#ifdef USE_UVTEX\nUNI sampler2D UVTex;\n#endif\n\nvoid main()\n{\n\n #ifndef USE_TEX\n outColor=bgColor;\n #endif\n #ifdef USE_TEX\n #ifndef USE_UVTEX\n outColor=texture(tex,texCoord);\n #else\n outColor=texture(tex,texture(UVTex,texCoord).xy);\n #endif\n #endif\n\n\n\n}\n"};const t=i.patch.cgl,n=i.inTrigger("Render"),r=i.inTexture("Base Texture"),s=i.inTexture("UV Texture"),a=i.inSwitch("Size",["Auto","Canvas","Manual"],"Auto"),o=i.inValueInt("Width",640),l=i.inValueInt("Height",480),u=i.inSwitch("Filter",["nearest","linear","mipmap"],"linear"),h=i.inValueSelect("Wrap",["clamp to edge","repeat","mirrored repeat"],"repeat"),c=i.inSwitch("Anisotropic",["0","1","2","4","8","16"],"0"),g=i.inDropDown("Pixel Format",CGL.Texture.PIXELFORMATS,CGL.Texture.PFORMATSTR_RGBA8UB),f=i.inBool("Clear",true),d=i.inValueSlider("R",0),m=i.inValueSlider("G",0),p=i.inValueSlider("B",0),_=i.inValueSlider("A",0),v=i.outTrigger("Next"),x=i.outTexture("texture_out",CGL.Texture.getEmptyTexture(t)),b=i.outNumber("Aspect Ratio"),D=i.outNumber("Texture Width"),B=i.outNumber("Texture Height");i.setPortGroup("Texture Size",[a,o,l]);i.setPortGroup("Texture Parameters",[h,c,u,g]);d.setUiAttribs({colorPick:true});i.setPortGroup("Color",[d,m,p,_,f]);i.toWorkPortsNeedToBeLinked(n);const w=[0,0,0,0];let T=null;let E=null;let A=true;let U=false;let S=null;let V=null;let k=null;let G=null;h.onChange=u.onChange=c.onChange=g.onChange=j;r.onLinkChanged=f.onChange=a.onChange=s.onChange=N;n.onTriggered=i.preRender=L;N();function O(){if(T)T.delete();if(E)E.delete();E=null;T=new CGL.TextureEffect(t,{isFloatingPointTexture:CGL.Texture.isPixelFormatFloat(g.get()),name:i.name});const e=Math.min(t.maxAnisotropic,parseFloat(c.get()));E=new CGL.Texture(t,{anisotropic:e,name:"image_compose_v2_"+i.id,pixelFormat:g.get(),filter:C(),wrap:R(),width:I(),height:F()});T.setSourceTexture(E);D.set(I());B.set(F());b.set(I()/F());x.setRef(CGL.Texture.getEmptyTexture(t));A=false;N()}function C(){if(u.get()=="nearest")return CGL.Texture.FILTER_NEAREST;else if(u.get()=="linear")return CGL.Texture.FILTER_LINEAR;else if(u.get()=="mipmap")return CGL.Texture.FILTER_MIPMAP}function R(){if(h.get()=="repeat")return CGL.Texture.WRAP_REPEAT;else if(h.get()=="mirrored repeat")return CGL.Texture.WRAP_MIRRORED_REPEAT;else if(h.get()=="clamp to edge")return CGL.Texture.WRAP_CLAMP_TO_EDGE}function I(){let e=0;if(r.get()&&a.get()=="Auto")e=r.get().width;else if(a.get()=="Auto"||a.get()=="Canvas")e=t.canvasWidth;else if(a.get()=="ViewPort")e=t.getViewPort()[2];else e=Math.ceil(o.get());return i.patch.cgl.checkTextureSize(e)}function F(){let e=0;if(r.get()&&a.get()=="Auto")e=r.get().height;else if(a.get()=="Auto"||a.get()=="Canvas")e=t.canvasHeight;else if(a.get()=="ViewPort")e=t.getViewPort()[3];else e=Math.ceil(l.get());return i.patch.cgl.checkTextureSize(e)}function j(){A=true}function z(){if((I()!=E.width||F()!=E.height||E.pixelFormat!=g.get()||E.filter!=C()||E.wrap!=R())&&(I()!==0&&F()!==0)){O();T.setSourceTexture(E);x.setRef(E);M();P()}}function M(){let e=null;if(a.get()=="Manual"){e=null}else if(a.get()=="Auto"){if(r.get())e="Input Texture";else e="Canvas Size";e+=": "+I()+" x "+F()}let t=false;t=a.uiAttribs.info!=e;a.setUiAttribs({info:e});if(t)i.refreshParams()}function y(){if(S)S.toggleDefine("USE_TEX",r.isLinked()||!f.get());if(S)S.toggleDefine("USE_UVTEX",s.isLinked())}function N(){c.setUiAttribs({greyout:C()!=CGL.Texture.FILTER_MIPMAP});d.setUiAttribs({greyout:r.isLinked()});p.setUiAttribs({greyout:r.isLinked()});m.setUiAttribs({greyout:r.isLinked()});_.setUiAttribs({greyout:r.isLinked()});f.setUiAttribs({greyout:r.isLinked()});o.setUiAttribs({greyout:a.get()!="Manual"});l.setUiAttribs({greyout:a.get()!="Manual"});if(E)if(CGL.Texture.isPixelFormatFloat(g.get())&&C()==CGL.Texture.FILTER_MIPMAP)i.setUiError("fpmipmap","Don't use mipmap and 32bit at the same time, many systems do not support this.");else i.setUiError("fpmipmap",null);M();y();P()}function P(){if(E)if(r.isLinked()&&r.get()&&E.isFloatingPoint()<r.get().isFloatingPoint())i.setUiError("textypediff","Warning: Mixing floating point and non floating point texture can result in data/precision loss",1);else i.setUiError("textypediff",null)}i.preRender=()=>{L()};function H(){if(!S){S=new CGL.Shader(t,"copytextureshader");S.setSource(S.getDefaultVertexShader(),e.imgcomp_frag);V=new CGL.Uniform(S,"t","tex",0);k=new CGL.Uniform(S,"t","UVTex",1);G=new CGL.Uniform(S,"4f","bgColor",d,m,p,_);y()}t.pushShader(S);t.currentTextureEffect.bind();if(r.get())t.setTexture(0,r.get().tex);else if(!f.get()&&x.get())t.setTexture(0,x.get().tex);if(s.get())t.setTexture(1,s.get().tex);t.currentTextureEffect.finish();t.popShader()}function L(){if(!T||A)O();t.pushBlend(false);z();const e=t.currentTextureEffect;t.currentTextureEffect=T;t.currentTextureEffect.imgCompVer=3;t.currentTextureEffect.width=o.get();t.currentTextureEffect.height=l.get();T.setSourceTexture(E);T.startEffect(r.get()||CGL.Texture.getEmptyTexture(t,U),true);H();v.trigger();t.pushViewPort(0,0,o.get(),l.get());T.endEffect();x.setRef(T.getCurrentSourceTexture());t.popViewPort();t.popBlend();t.currentTextureEffect=e}}};CABLES.OPS["17212e2b-d692-464c-8f8d-2d511dd3410a"]={f:Ops.Gl.ImageCompose.ImageCompose_v4,objName:"Ops.Gl.ImageCompose.ImageCompose_v4"};Ops.Gl.Meshes.FullscreenRectangle_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={shader_frag:"UNI sampler2D tex;\nIN vec2 texCoord;\n\nvoid main()\n{\n outColor= texture(tex,texCoord);\n}\n\n",shader_vert:"{{MODULES_HEAD}}\n\nIN vec3 vPosition;\nUNI mat4 projMatrix;\nUNI mat4 mvMatrix;\n\nOUT vec2 texCoord;\nIN vec2 attrTexCoord;\n\nvoid main()\n{\n vec4 pos=vec4(vPosition, 1.0);\n\n texCoord=vec2(attrTexCoord.x,(1.0-attrTexCoord.y));\n\n gl_Position = projMatrix * mvMatrix * pos;\n}\n"};const i=e.inTrigger("render"),n=e.inSwitch("Scale",["Stretch","Fit"],"Fit"),r=e.inValueBool("Flip Y"),s=e.inValueBool("Flip X"),a=e.inTexture("Texture"),o=e.outTrigger("trigger");const l=e.patch.cgl;let u=null;let h=new CGL.Geometry("fullscreen rectangle");let c=0,g=0,f=0,d=0;e.toWorkShouldNotBeChild("Ops.Gl.TextureEffects.ImageCompose",CABLES.OP_PORT_TYPE_FUNCTION);e.toWorkPortsNeedToBeLinked(i);s.onChange=A;
30982r.onChange=A;i.onTriggered=E;a.onLinkChanged=x;n.onChange=T;const m=new CGL.Shader(l,"fullscreenrectangle",this);m.setModules(["MODULE_VERTEX_POSITION","MODULE_COLOR","MODULE_BEGIN_FRAG"]);m.setSource(t.shader_vert,t.shader_frag);m.fullscreenRectUniform=new CGL.Uniform(m,"t","tex",0);m.aspectUni=new CGL.Uniform(m,"f","aspectTex",0);let p=false;let _=true;let v=false;x();T();a.onChange=function(){_=true};function x(){if(!CABLES.UI)return;r.setUiAttribs({greyout:!a.isLinked()});s.setUiAttribs({greyout:!a.isLinked()});n.setUiAttribs({greyout:!a.isLinked()})}function b(){let e=a.get();if(e)p=true;else p=false}e.preRender=function(){b();m.bind();if(u)u.render(m);E()};function T(){v=n.get()=="Fit"}function E(){if(l.viewPort[2]!=f||l.viewPort[3]!=d||!u)S();if(_)b();l.pushPMatrix();mat4.identity(l.pMatrix);mat4.ortho(l.pMatrix,0,f,d,0,-10,1e3);l.pushModelMatrix();mat4.identity(l.mMatrix);l.pushViewMatrix();mat4.identity(l.vMatrix);if(v&&a.get()){const i=a.get().width/a.get().height;let e=d;let t=d*i;if(t>f){e=f*1/i;t=f}l.pushViewPort((f-t)/2,(d-e)/2,t,e)}if(p){if(a.get())l.setTexture(0,a.get().tex);u.render(m)}else{u.render(l.getShader())}l.gl.clear(l.gl.DEPTH_BUFFER_BIT);l.popPMatrix();l.popModelMatrix();l.popViewMatrix();if(v&&a.get())l.popViewPort();o.trigger()}function A(){u=null}function S(){if(l.viewPort[2]==f&&l.viewPort[3]==d&&u)return;let e=0,t=0;f=l.viewPort[2];d=l.viewPort[3];h.vertices=new Float32Array([e+f,t+d,0,e,t+d,0,e+f,t,0,e,t,0]);let i=null;if(r.get())i=new Float32Array([1,0,0,0,1,1,0,1]);else i=new Float32Array([1,1,0,1,1,0,0,0]);if(s.get()){i[0]=0;i[2]=1;i[4]=0;i[6]=1}h.setTexCoords(i);h.verticesIndices=new Uint16Array([2,1,0,3,1,2]);h.vertexNormals=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1]);h.tangents=new Float32Array([-1,0,0,-1,0,0,-1,0,0,-1,0,0]);h.biTangents==new Float32Array([0,-1,0,0,-1,0,0,-1,0,0,-1,0]);if(!u)u=new CGL.Mesh(l,h);else u.setGeom(h)}}};CABLES.OPS["fb70721a-eac2-4ff5-a5a2-5c59e2393972"]={f:Ops.Gl.Meshes.FullscreenRectangle_v2,objName:"Ops.Gl.Meshes.FullscreenRectangle_v2"};Ops.Gl.GradientTexture=class extends CABLES.Op{constructor(){super(...arguments);const i=this;const e=i.attachments={};const R=i.inGradient("Gradient"),I=i.inValueSelect("Direction",["X","XX","Y","YY","XY","YX","Radial"],"X"),F=i.inValueBool("Smoothstep",false),M=i.inBool("Step",false),y=i.inBool("Flip",false),N=i.inBool("sRGB",false),P=i.inBool("Oklab",false),L=i.inValueInt("Size",256),D=i.inSwitch("filter",["nearest","linear","mipmap"],"linear"),B=i.inValueSelect("wrap",["clamp to edge","repeat","mirrored repeat"],"clamp to edge"),m=i.inFloatSlider("Dither",0),n=i.inArray("Gradient Array"),t=i.inTriggerButton("Randomize Colors"),w=i.outTexture("Texture"),U=i.outArray("Colors",null,3),V=i.outArray("Colors Pos",null,1);const k=i.patch.cgl;let r=null;R.setUiAttribs({editShortcut:true});const s=[221,125,40,94,163,50,214,174,69,229,135,79,25,92,217,129,103,155,16,237,168,75,212,126,203,157,104,223,50,96,115,189,0,104,199,16,185,242,83,26,123,95,191,175,247,159,32,170,0,88,203,133,106,46,227,14,35,246,66,20,240,205,36,159,74,252,148,231,132,117,6,145,254,39,222,5,111,46,67,197,228,116,181,66,25,245,98,139,172,89,190,149,127,177,64,138,210,169,58,28,70,100,206,188,164,107,60,150,203,126,235,142,56,249,38,222,148,178,195,56,115,230,45,108,7,84,234,21,44,90,110,216,178,37,226,53,14,77,212,31,86,180,100,23,82,14,162,93,122,6,81,156,24,209,75,255,163,218,196,121,237,187,9,152,247,136,158,91,128,232,169,137,251,10,216,154,188,131,211,71,200,34,236,216,129,13,179,136,32,54,99,146,33,131,202,49,84,18,64,197,245,114,21,193,52,74,118,44,243,105,173,50,252,110,63,166,41,102,199,62,117,184,15,77,250,162,69,120,231,107,213,2,177,43,67,102,159,238,171,206,64,29,233,10,151,135,185,87,247,147,223,91,241,152,225,175,3,102,220,25,191,170,36,143,81,152,209,224,133,35,93,2,145,87,124,193,97,22,228,1,120,51,171,8,26,210,108,48,205,59,179,92,147,253,124,99,237,186,11,120,19,181,229,112,198,160,220,76,42,210,160,71,202,31,78,190,130,67,86,138,115,156,243,14,46,74,57,219,28,51,90,250,59,81,140,47,255,17,58,181,243,114,56,178,239,139,228,156,251,40,167,232,28,38,82,136,206,161,9,196,106,139,167,204,150,195,218,70,172,35,132,103,146,27,89,128,16,107,96,57,119,201,15,187,239,126,194,225,112,182,234,131,174,240,72,39,109,29,8,100,122,207,231,4,166,224,198,153,217,44,183,212,4,93,143,72,99,172,64,0,97,34,85,66,20,208,3,125,243,164,186,235,156,82,191,67,248,49,80,10,253,68,23,162,244,179,49,215,24,151,246,51,214,153,251,118,45,157,98,224,53,88,134,62,42,23,116,94,140,33,121,188,169,141,113,76,33,131,227,110,11,202,78,122,168,18,141,194,221,80,187,142,177,210,18,249,144,221,180,12,201,215,106,60,91,226,200,236,150,85,61,164,185,133,42,229,187,73,55,101,27,235,59,12,35,75,113,199,101,163,237,57,152,174,234,134,1,37,53,123,193,6,208,253,34,91,145,104,8,240,211,175,129,164,109,253,123,230,171,6,50,79,27,127,73,43,19,246,161,211,103,17,172,96,46,117,70,241,219,27,162,115,88,38,4,148,204,92,189,154,63,130,217,188,111,254,208,101,86,191,144,75,180,249,65,137,233,157,18,171,192,49,66,201,137,246,218,51,71,15,43,214,29,95,239,38,139,165,7,225,124,30,59,112,221,154,28,197,217,106,58,85,209,128,232,151,15,79,182,120,238,168,134,81,248,146,173,16,88,195,65,150,183,205,242,11,41,89,126,80,8,183,121,141,3,98,180,31,108,58,196,97,24,222,107,198,2,116,70,207,52,230,22,109,47,80,165,132,199,235,170,52,148,247,165,23,242,74,45,254,170,226,155,36,142,179,60,158,48,182,223,154,124,98,178,250,140,5,231,96,68,19,116,204,32,227,43,200,113,161,213,122,87,0,130,248,77,13,241,92,229,30,102,13,244,77,160,33,209,119,55,176,143,190,255,103,71,93,186,62,223,145,12,189,68,202,47,211,114,192,41,127,203,141,65,189,40,135,198,61,89,222,158,24,216,45,1,157,213,130,239,83,104,26,55,134,238,29,159,95,63,167,149,7,78,255,119,166,212,1,233,19,105,186,37,244,110,86,135,56,173,11,151,36,176,196,230,94,149,109,184,226,20,236,215,105,175,22,219,52,87,111,174,128,248,149,78,125,63,184,227,242,118,22,220,138,252,119,76,168,39,250,10,136,84,123,54,69,194,37,95,147,241,73,153,48,68,7,194,17,207,161,31,76,201,90,166,69,4,48,215,21,204,57,73,176,200,30,249,155,133,233,163,9,197,32,183,220,205,137,232,167,94,144,9,105,181,44,111,207,99,132,155,182,85,127,219,147,42,97,184,5,83,208,108,61,125,228,21,100,39,90,114,53,218,41,252,129,61,234,143,30,192,245,12,112,236,101,2,244,113,165,225,118,47,20,176,251,142,84,117,160,254,177,26,238,121,72,193,213,153,13,55,173,79,224,65,140,34,195,158,54,17,206,62,144,240,190,72,40,214,54,192,5,146,60,82,185,3,138,169,25,83,245];const p=32;m.onChange=B.onChange=D.onChange=M.onChange=y.onChange=N.onChange=P.onChange=L.onChange=R.onChange=F.onChange=I.onChange=n.onChange=a;R.set('{"keys" : [{"pos":0,"r":0,"g":0,"b":0},{"pos":1,"r":1,"g":1,"b":1}]}');i.onLoaded=a;t.onTriggered=()=>{const e=l();
30982if(e){e.forEach(e=>{e.r=Math.random();e.g=Math.random();e.b=Math.random()});const t=JSON.stringify({keys:e});R.set(t)}};function G(e,t,i){let n=.4122214708*e+.5363325363*t+.0514459929*i;let r=.2119034982*e+.6806995451*t+.1073969566*i;let s=.0883024619*e+.2817188376*t+.6299787005*i;n=Math.cbrt(n);r=Math.cbrt(r);s=Math.cbrt(s);return[n*+.2104542553+r*+.793617785+s*-.0040720468,n*+1.9779984951+r*-2.428592205+s*+.4505937099,n*+.0259040371+r*+.7827717662+s*-.808675766]}function j(e,t,i){let n=e+t*+.3963377774+i*+.2158037573;let r=e+t*-.1055613458+i*-.0638541728;let s=e+t*-.0894841775+i*-1.291485548;n**=3;r**=3;s**=3;let a=n*+4.0767416621+r*-3.3077115913+s*+.2309699292;let o=n*-1.2684380046+r*+2.6097574011+s*-.3413193965;let l=n*-.0041960863+r*-.7034186147+s*+1.707614701;a=CABLES.clamp(a,0,1);o=CABLES.clamp(o,0,1);l=CABLES.clamp(l,0,1);return[a,o,l]}function z(e,t,i){e/=255;const n=.0031308;let r=12.92*e;let s=1.055*Math.pow(e,.41666)-.055;return(e<n?r:s)*255}function a(){k.addNextFrameOnceCallback(o)}function o(){const e=l();if(e)u(e)}function l(){let t=null;i.setUiError("nodata",null);i.setUiError("parse",null);if(Array.isArray(n.get())){t=n.get()}else{let e=null;if(!R.get()||R.get()===""){return null}try{e=JSON.parse(R.get())}catch(e){i.setUiError("parse","could not parse gradient data")}if(!e||!e.keys){i.setUiError("nodata","gradient no data");return null}t=e.keys}return t}function _(e,t){e%=p;t%=p;return s[e+t*p]/255-.5}function H(r,s,a){if(m.get()==0)return r;for(let n=0;n<s;n++)for(let i=0;i<a;i++){const o=r[(n+i*s)*4+0];const l=r[(n+i*s)*4+1];const u=r[(n+i*s)*4+2];let e=s/8*m.get()*_(n,i);let t=a/8*m.get()*_(n+p/2,i+p/2);if(a==1)t=0;if(s==1)e=0;e=Math.round(e);t=Math.round(t);const h=CABLES.clamp(i+t,0,a-1);const c=CABLES.clamp(n+e,0,s-1);const g=r[(c+h*s)*4+0];const f=r[(c+h*s)*4+1];const d=r[(c+h*s)*4+2];r[(n+i*s)*4+0]=g;r[(n+i*s)*4+1]=f;r[(n+i*s)*4+2]=d;r[(c+h*s)*4+0]=o;r[(c+h*s)*4+1]=l;r[(c+h*s)*4+2]=u}return r}function u(t){let r=Math.round(L.get());if(r<4)r=4;R.setUiAttribs({editShortcut:true,gradEditSmoothstep:F.get(),gradEditStep:M.get(),gradOklab:P.get()});let e=0;let i=0;if(B.get()=="repeat")e=CGL.Texture.WRAP_REPEAT;else if(B.get()=="mirrored repeat")e=CGL.Texture.WRAP_MIRRORED_REPEAT;else if(B.get()=="clamp to edge")e=CGL.Texture.WRAP_CLAMP_TO_EDGE;if(D.get()=="nearest")i=CGL.Texture.FILTER_NEAREST;else if(D.get()=="linear")i=CGL.Texture.FILTER_LINEAR;else if(D.get()=="mipmap")i=CGL.Texture.FILTER_MIPMAP;const n=new CGL.Texture(k);let s=new Uint8Array(r*4);for(let e=0;e<t.length-1;e++){const l=t[e];const u=t[e+1];for(let i=l.pos*r;i<u.pos*r;i++){let e=CABLES.map(i,l.pos*r,u.pos*r,0,1);if(M.get())e=Math.round(e);if(F.get())e=CABLES.smoothStep(e);i=Math.round(i);let t=i;if(y.get())t=r-i-1;if(P.get()){const h=G(l.r,l.g,l.b);const c=h[0];const g=h[1];const f=h[2];const d=G(u.r,u.g,u.b);const m=d[0];const p=d[1];const _=d[2];const v=e*m+(1-e)*c;const x=e*p+(1-e)*g;const b=e*_+(1-e)*f;const T=j(v,x,b);s[t*4+0]=Math.round(T[0]*255);s[t*4+1]=Math.round(T[1]*255);s[t*4+2]=Math.round(T[2]*255)}else{s[t*4+0]=Math.round((e*u.r+(1-e)*l.r)*255);s[t*4+1]=Math.round((e*u.g+(1-e)*l.g)*255);s[t*4+2]=Math.round((e*u.b+(1-e)*l.b)*255)}if(typeof l.a!=="undefined"&&typeof u.a!=="undefined"){const E=Math.round((e*u.a+(1-e)*l.a)*255);s[t*4+3]=E}else{s[t*4+3]=Math.round(255)}}}if(N.get())for(let e=0;e<s.length;e+=4){s[e+0]=z(s[e+0]);s[e+1]=z(s[e+1]);s[e+2]=z(s[e+2])}if(I.get()=="X")n.initFromData(H(s,r,1),r,1,i,e);if(I.get()=="Y")n.initFromData(H(s,1,r),1,r,i,e);if(I.get()=="Radial"){const A=new Uint8Array(r*r*4);for(let n=0;n<r;n++){for(let i=0;i<r;i++){const S=n-(r-1)/2;const O=i-(r-1)/2;let e=Math.sqrt(S*S+O*O)/r*2;if(F.get())e=CABLES.smoothStep(e);let t=Math.round(e*r)*4;if(t>=r*4)t=r*4-4;A[n*4+i*4*r+0]=s[t+0];A[n*4+i*4*r+1]=s[t+1];A[n*4+i*4*r+2]=s[t+2];A[n*4+i*4*r+3]=Math.round(255)}}s=A;n.initFromData(H(s,r,r),r,r,i,e)}if(I.get()=="XX"){const A=new Uint8Array(r*r*4);for(let t=0;t<r;t++)for(let e=0;e<r;e++){const C=t*4;A[t*4+e*4*r+0]=s[C+0];A[t*4+e*4*r+1]=s[C+1];A[t*4+e*4*r+2]=s[C+2];A[t*4+e*4*r+3]=Math.round(255)}s=A;n.initFromData(H(s,r,r),r,r,i,e)}if(I.get()=="YY"){const A=new Uint8Array(r*r*4);for(let t=0;t<r;t++)for(let e=0;e<r;e++){const C=t*4;A[e*4+t*4*r+0]=s[C+0];A[e*4+t*4*r+1]=s[C+1];A[e*4+t*4*r+2]=s[C+2];A[e*4+t*4*r+3]=Math.round(255)}s=A;n.initFromData(H(s,r,r),r,r,i,e)}if(I.get()=="XY"||I.get()=="YX"){const A=new Uint8Array(r*r*4);for(let n=0;n<r;n++){let i=n;if(I.get()=="YX")i=r-n-1;for(let t=0;t<r;t++){let e=Math.round((i+t)/2)*4;A[n*4+t*4*r+0]=s[e+0];A[n*4+t*4*r+1]=s[e+1];A[n*4+t*4*r+2]=s[e+2];A[n*4+t*4*r+3]=Math.round(255)}}s=A;n.initFromData(H(s,r,r),r,r,i,e)}const a=[];for(let e=0;e<t.length-1;e++){a.push(t[e].r,t[e].g,t[e].b)}const o=[];for(let e=0;e<t.length-1;e++){o.push(t[e].pos)}U.set(a);V.set(o);w.setRef(n)}}};CABLES.OPS["01380a50-2dbb-4465-ae80-86349b0b717a"]={f:Ops.Gl.GradientTexture,objName:"Ops.Gl.GradientTexture"};Ops.Gl.ImageCompose.DrawImage_v3=class extends CABLES.Op{constructor(){super(...arguments);const n=this;const e=n.attachments={drawimage_frag:"#ifdef HAS_TEXTURES\n IN vec2 texCoord;\n UNI sampler2D tex;\n UNI sampler2D image;\n#endif\n\n#ifdef TEX_TRANSFORM\n IN mat3 transform;\n#endif\n// UNI float rotate;\n\n{{CGL.BLENDMODES}}\n\n#ifdef HAS_TEXTUREALPHA\n UNI sampler2D imageAlpha;\n#endif\n\nUNI float amount;
30982\n\n#ifdef ASPECT_RATIO\n UNI float aspectTex;\n UNI float aspectPos;\n#endif\n\nvoid main()\n{\n vec4 blendRGBA=vec4(0.0,0.0,0.0,1.0);\n\n #ifdef HAS_TEXTURES\n vec2 tc=texCoord;\n\n #ifdef TEX_FLIP_X\n tc.x=1.0-tc.x;\n #endif\n #ifdef TEX_FLIP_Y\n tc.y=1.0-tc.y;\n #endif\n\n #ifdef ASPECT_RATIO\n #ifdef ASPECT_AXIS_X\n tc.y=(1.0-aspectPos)-(((1.0-aspectPos)-tc.y)*aspectTex);\n #endif\n #ifdef ASPECT_AXIS_Y\n tc.x=(1.0-aspectPos)-(((1.0-aspectPos)-tc.x)/aspectTex);\n #endif\n #endif\n\n #ifdef TEX_TRANSFORM\n vec3 coordinates=vec3(tc.x, tc.y,1.0);\n tc=(transform * coordinates ).xy;\n #endif\n\n blendRGBA=texture(image,tc);\n\n vec3 blend=blendRGBA.rgb;\n vec4 baseRGBA=texture(tex,texCoord);\n vec3 base=baseRGBA.rgb;\n\n\n #ifdef PREMUL\n blend.rgb = (blend.rgb) + (base.rgb * (1.0 - blendRGBA.a));\n #endif\n\n vec3 colNew=_blend(base,blend);\n\n\n\n\n #ifdef REMOVE_ALPHA_SRC\n blendRGBA.a=1.0;\n #endif\n\n #ifdef HAS_TEXTUREALPHA\n vec4 colImgAlpha=texture(imageAlpha,tc);\n float colImgAlphaAlpha=colImgAlpha.a;\n\n #ifdef ALPHA_FROM_LUMINANCE\n vec3 gray = vec3(dot(vec3(0.2126,0.7152,0.0722), colImgAlpha.rgb ));\n colImgAlphaAlpha=(gray.r+gray.g+gray.b)/3.0;\n #endif\n\n #ifdef ALPHA_FROM_INV_UMINANCE\n vec3 gray = vec3(dot(vec3(0.2126,0.7152,0.0722), colImgAlpha.rgb ));\n colImgAlphaAlpha=1.0-(gray.r+gray.g+gray.b)/3.0;\n #endif\n\n #ifdef INVERT_ALPHA\n colImgAlphaAlpha=clamp(colImgAlphaAlpha,0.0,1.0);\n colImgAlphaAlpha=1.0-colImgAlphaAlpha;\n #endif\n\n blendRGBA.a=colImgAlphaAlpha*blendRGBA.a;\n #endif\n #endif\n\n float am=amount;\n\n #ifdef CLIP_REPEAT\n if(tc.y>1.0 || tc.y<0.0 || tc.x>1.0 || tc.x<0.0)\n {\n // colNew.rgb=vec3(0.0);\n am=0.0;\n }\n #endif\n\n #ifdef ASPECT_RATIO\n #ifdef ASPECT_CROP\n if(tc.y>1.0 || tc.y<0.0 || tc.x>1.0 || tc.x<0.0)\n {\n colNew.rgb=base.rgb;\n am=0.0;\n }\n\n #endif\n #endif\n\n\n\n #ifndef PREMUL\n blendRGBA.rgb=mix(colNew,base,1.0-(am*blendRGBA.a));\n blendRGBA.a=clamp(baseRGBA.a+(blendRGBA.a*am),0.,1.);\n #endif\n\n #ifdef PREMUL\n // premultiply\n // blendRGBA.rgb = (blendRGBA.rgb) + (baseRGBA.rgb * (1.0 - blendRGBA.a));\n blendRGBA=vec4(\n mix(colNew.rgb,base,1.0-(am*blendRGBA.a)),\n blendRGBA.a*am+baseRGBA.a\n );\n #endif\n\n #ifdef ALPHA_MASK\n blendRGBA.a=baseRGBA.a;\n #endif\n\n outColor=blendRGBA;\n}\n\n\n\n\n\n\n\n",drawimage_vert:"IN vec3 vPosition;\nIN vec2 attrTexCoord;\nIN vec3 attrVertNormal;\n\nUNI mat4 projMatrix;\nUNI mat4 mvMatrix;\n\nOUT vec2 texCoord;\n// OUT vec3 norm;\n\n#ifdef TEX_TRANSFORM\n UNI float posX;\n UNI float posY;\n UNI float scaleX;\n UNI float scaleY;\n UNI float rotate;\n OUT mat3 transform;\n#endif\n\nvoid main()\n{\n texCoord=attrTexCoord;\n// norm=attrVertNormal;\n\n #ifdef TEX_TRANSFORM\n vec3 coordinates=vec3(attrTexCoord.x, attrTexCoord.y,1.0);\n float angle = radians( rotate );\n vec2 scale= vec2(scaleX,scaleY);\n vec2 translate= vec2(posX,posY);\n\n transform = mat3( scale.x * cos( angle ), scale.x * sin( angle ), 0.0,\n - scale.y * sin( angle ), scale.y * cos( angle ), 0.0,\n - 0.5 * scale.x * cos( angle ) + 0.5 * scale.y * sin( angle ) - 0.5 * translate.x*2.0 + 0.5, - 0.5 * scale.x * sin( angle ) - 0.5 * scale.y * cos( angle ) - 0.5 * translate.y*2.0 + 0.5, 1.0);\n #endif\n\n gl_Position = projMatrix * mvMatrix * vec4(vPosition, 1.0);\n}\n"};const t=n.inTrigger("render"),i=CGL.TextureEffect.AddBlendSelect(n,"blendMode"),r=n.inValueSlider("amount",1),s=n.inTexture("Image"),a=n.inValueBool("Premultiplied",false),o=n.inValueBool("Alpha Mask",fal
30982se),l=n.inValueBool("removeAlphaSrc",false),u=n.inTexture("Mask"),h=n.inValueSelect("Mask Src",["alpha channel","luminance","luminance inv"],"luminance"),c=n.inBool("Invert alpha channel"),g=n.inValueBool("Aspect Ratio",false),f=n.inValueSelect("Stretch Axis",["X","Y"],"X"),d=n.inValueSlider("Position",0),m=n.inValueBool("Crop",false),p=n.outTrigger("trigger");i.set("normal");const _=n.patch.cgl;const v=new CGL.Shader(_,"drawimage");u.onLinkChanged=x;n.setPortGroup("Aspect Ratio",[g,d,m,f]);n.setPortGroup("Mask",[u,h,c]);function x(){if(u.isLinked()){l.setUiAttribs({greyout:true});h.setUiAttribs({greyout:false});c.setUiAttribs({greyout:false})}else{l.setUiAttribs({greyout:false});h.setUiAttribs({greyout:true});c.setUiAttribs({greyout:true})}}n.toWorkPortsNeedToBeLinked(s);v.setSource(e.drawimage_vert,e.drawimage_frag);const b=new CGL.Uniform(v,"t","tex",0),D=new CGL.Uniform(v,"t","image",1),B=new CGL.Uniform(v,"t","imageAlpha",2),T=new CGL.Uniform(v,"f","aspectTex",1),w=new CGL.Uniform(v,"f","aspectPos",d);g.onChange=m.onChange=f.onChange=E;function E(){v.removeDefine("ASPECT_AXIS_X");v.removeDefine("ASPECT_AXIS_Y");v.removeDefine("ASPECT_CROP");d.setUiAttribs({greyout:!g.get()});m.setUiAttribs({greyout:!g.get()});f.setUiAttribs({greyout:!g.get()});if(g.get()){v.define("ASPECT_RATIO");if(m.get())v.define("ASPECT_CROP");if(f.get()=="X")v.define("ASPECT_AXIS_X");if(f.get()=="Y")v.define("ASPECT_AXIS_Y")}else{v.removeDefine("ASPECT_RATIO");if(m.get())v.define("ASPECT_CROP");if(f.get()=="X")v.define("ASPECT_AXIS_X");if(f.get()=="Y")v.define("ASPECT_AXIS_Y")}}const A=n.inValueBool("flip x");const S=n.inValueBool("flip y");let O=n.inValueBool("Transform");let C=n.inValueSlider("Scale X",1);let R=n.inValueSlider("Scale Y",1);let I=n.inValue("Position X",0);let F=n.inValue("Position Y",0);let M=n.inValue("Rotation",0);const y=n.inValueBool("Clip Repeat",false);const U=new CGL.Uniform(v,"f","scaleX",C);const V=new CGL.Uniform(v,"f","scaleY",R);const k=new CGL.Uniform(v,"f","posX",I);const G=new CGL.Uniform(v,"f","posY",F);const j=new CGL.Uniform(v,"f","rotate",M);O.onChange=N;function N(){v.toggleDefine("TEX_TRANSFORM",O.get());C.setUiAttribs({greyout:!O.get()});R.setUiAttribs({greyout:!O.get()});I.setUiAttribs({greyout:!O.get()});F.setUiAttribs({greyout:!O.get()});M.setUiAttribs({greyout:!O.get()})}CGL.TextureEffect.setupBlending(n,v,i,r);const z=new CGL.Uniform(v,"f","amount",r);t.onTriggered=L;y.onChange=u.onChange=a.onChange=o.onChange=c.onChange=S.onChange=A.onChange=l.onChange=h.onChange=P;N();x();E();P();function P(){v.toggleDefine("REMOVE_ALPHA_SRC",l.get());v.toggleDefine("ALPHA_MASK",o.get());v.toggleDefine("CLIP_REPEAT",y.get());v.toggleDefine("HAS_TEXTUREALPHA",u.get()&&u.get().tex);v.toggleDefine("TEX_FLIP_X",A.get());v.toggleDefine("TEX_FLIP_Y",S.get());v.toggleDefine("INVERT_ALPHA",c.get());v.toggleDefine("ALPHA_FROM_LUMINANCE",h.get()=="luminance");v.toggleDefine("ALPHA_FROM_INV_UMINANCE",h.get()=="luminance_inv");v.toggleDefine("PREMUL",a.get())}function L(){if(!CGL.TextureEffect.checkOpInEffect(n))return;const e=s.get();if(e&&e.tex&&r.get()>0){_.pushShader(v);_.currentTextureEffect.bind();const t=_.currentTextureEffect.getCurrentSourceTexture();_.setTexture(0,t.tex);const i=1/(_.currentTextureEffect.getWidth()/_.currentTextureEffect.getHeight())*(e.width/e.height);T.setValue(i);_.setTexture(1,e.tex);if(u.get()&&u.get().tex){_.setTexture(2,u.get().tex)}_.pushBlendMode(CGL.BLEND_NONE,true);_.currentTextureEffect.finish();_.popBlendMode();_.popShader()}p.trigger()}}};CABLES.OPS["8f6b2f15-fcb0-4597-90c0-e5173f2969fe"]={f:Ops.Gl.ImageCompose.DrawImage_v3,objName:"Ops.Gl.ImageCompose.DrawImage_v3"};Ops.Gl.ImageCompose.RotateTexture_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={rotate_frag:"IN vec2 texCoord;\nUNI sampler2D tex;\nUNI sampler2D multiplierTex;\nUNI float amount;
30982\nUNI float resX;\nUNI float resY;\nUNI float rotate;\n\n{{CGL.BLENDMODES3}}\n\n#define PI 3.14159265\n#define TAU (2.0*PI)\n\nvoid pR(inout vec2 p, float a)\n{\n\tp = cos(a)*p + sin(a)*vec2(p.y, -p.x);\n}\n\nvoid main()\n{\n float multiplier = 0.0;\n\n #ifdef ROTATE_TEXTURE\n multiplier = dot(vec3(0.2126,0.7152,0.0722), texture(multiplierTex,texCoord).rgb);\n #endif\n\n vec2 uv = texCoord;\n vec2 res = vec2(resX,resY);\n uv -= 0.5;\n pR(uv.xy,(rotate + multiplier) * (TAU) );\n uv += 0.5;\n\n\n\n vec4 col=texture(tex,uv);\n vec4 base=texture(tex,texCoord);\n\n #ifdef CLEAR\n base.a=0.0;\n #endif\n\n\n #ifdef CROP_IMAGE\n if(uv.x>1.0 ||uv.x<0.0 || uv.y>1.0 ||uv.y<0.0 )\n {\n base.a=0.0;\n col.a=0.0;\n // discard;\n // return;\n }\n #endif\n\n outColor=cgl_blendPixel(base,col,amount);\n}"};const i=e.inTrigger("render"),n=e.inTexture("Multiplier"),r=CGL.TextureEffect.AddBlendSelect(e,"Blend Mode","normal"),s=e.inValueSlider("Amount",1),a=e.inValueSlider("Rotate",.125),o=e.inValueBool("Crop",true),l=e.inBool("Clear",true),u=e.outTrigger("trigger");const h=e.patch.cgl;const c=new CGL.Shader(h,e.name,e);c.setSource(c.getDefaultVertexShader(),t.rotate_frag);const g=new CGL.Uniform(c,"t","tex",0),f=new CGL.Uniform(c,"t","multiplierTex",1),d=new CGL.Uniform(c,"f","amount",s),m=new CGL.Uniform(c,"f","rotate",a);CGL.TextureEffect.setupBlending(e,c,r,s);o.onChange=n.onChange=p;p();function p(){c.toggleDefine("CLEAR",l.get());c.toggleDefine("CROP_IMAGE",o.get());c.toggleDefine("ROTATE_TEXTURE",n.isLinked())}i.onTriggered=function(){if(!CGL.TextureEffect.checkOpInEffect(e,3))return;h.pushShader(c);h.currentTextureEffect.bind();h.setTexture(0,h.currentTextureEffect.getCurrentSourceTexture().tex);if(n.get())h.setTexture(1,n.get().tex);h.currentTextureEffect.finish();h.popShader();u.trigger()}}};CABLES.OPS["20b8a2e6-2419-474b-98a4-71a5e3178631"]={f:Ops.Gl.ImageCompose.RotateTexture_v2,objName:"Ops.Gl.ImageCompose.RotateTexture_v2"};Ops.Devices.Mouse.Mouse_v4=class extends CABLES.Op{constructor(){super(...arguments);const t=this;const D=t.attachments={};const e=t.inSwitch("Coordinates",["-1 to 1","Pixel Display","Pixel","0 to 1"],"-1 to 1"),r=t.inValueSelect("Area",["Canvas Area","Canvas","Document","Parent Element"],"Canvas Area"),s=t.inValueBool("flip y",true),i=t.inBool("right click prevent default",true),n=t.inSwitch("Events",["Pointer","Touch","Mouse"]),a=t.inValueBool("Passive Events",false),o=t.inObject("Element","element"),l=t.inValueBool("Active",true),u=t.outNumber("x",0),h=t.outNumber("y",0),c=t.outTrigger("click"),B=t.outTrigger("click right"),g=t.outBoolNum("Button is down"),f=t.outBoolNum("Mouse is hovering"),w=t.outNumber("Movement X",0),U=t.outNumber("Movement Y",0),d=t.outObject("Event");const m=t.patch.cgl;let p=1;let _=null;let v=null;a.onChange=r.onChange=L;e.onChange=k;t.onDelete=P;L();t.on("loadedValueSet",x);function x(){if(p==0){if(v.clientWidth===0)setTimeout(x,50);u.set(v.clientWidth/2);h.set(v.clientHeight/2)}else if(p==1){u.set(0);h.set(0)}else if(p==2){u.set(.5);h.set(.5)}else if(p==3){if(v.clientWidth===0){setTimeout(x,50)}u.set(v.clientWidth/2/m.pixelDensity);h.set(v.clientHeight/2/m.pixelDensity)}else console.error("unknown normalize mouse",p)}function V(r,s){r=r||0;s=s||0;if(p==0){u.set(r);h.set(s)}else if(p==3){u.set(r*m.pixelDensity);h.set(s*m.pixelDensity)}else{let i=v.clientWidth/m.pixelDensity;let n=v.clientHeight/m.pixelDensity;i=i||1;n=n||1;if(p==1){let e=r/i*2-1;let t=s/n*2-1;e=CABLES.clamp(e,-1,1);t=CABLES.clamp(t,-1,1);u.set(e);h.set(t)}else if(p==2){let e=r/i;let t=s/n;e=CABLES.clamp(e,0,1);t=CABLES.clamp(t,0,1);u.set(e);h.set(t)}}}function b(e){if(!v)return;const t=v.getBoundingClientRect();return e.clientX>t.left&&e.clientX<t.left+t.width&&e.clientY>t.top&&e.clientY<t.top+t.height}o.onChange=n.onChange=function(){r.setUiAttribs({greyout:o.isLinked()});P();L()};l.onChange=function(){if(_)P();if(l.get())L()};function k(){if(e.get()=="Pixel")p=0;else if(e.get()=="-1 to 1")p=1;else if(e.get()=="0 to 1")p=2;else if(e.get()=="Pixel Display")p=3}function T(e){d.setRef(e);g.set(false);f.set(b(e))}function E(e){if(!b(e))return;N(e);d.setRef(e);g.set(true)}function A(e){N(e);d.setRef(e);g.set(false)}function S(e){if(!b(e))return;d.setRef(e);B.trigger();if(i.get())e.preventDefault()}function O(e){if(!b(e))return;N(e);d.setRef(e);c.trigger()}function C(e){d.setRef(e);g.set(false);f.set(b(e))}function R(e){f.set(b(e));if(r.get()==="Canvas Area"){const t=v.getBoundingClientRect();const i=e.clientX-t.left;const n=e.clientY-t.top;if(i<0||i>t.width||n>t.height||n<0)return}d.setRef(e);N(e);w.set(e.movementX/m.pixelDensity);U.set(e.movementY/m.pixelDensity)}function I(e){if(event.touches&&event.touches.length>0)N(e.touches[0]);d.setRef(e)}function F(e){g.set(true);if(e.touches&&e.touches.length>0)E(e.touches[0]);d.setRef(e)}function M(e){g.set(false);A();d.setRef(e)}
30982function y(e){console.log("mouse cancel");g.set(false);A();d.setRef(e)}function N(e){let t=e.clientX;let i=e.clientY;if(o.isLinked()){t=e.offsetX;i=e.offsetY}else{if(r.get()!="Document"){t=e.offsetX;i=e.offsetY}if(r.get()==="Canvas Area"){const n=v.getBoundingClientRect();t=e.clientX-n.left;i=e.clientY-n.top;if(t<0||t>n.width||i>n.height||i<0)return;t=CABLES.clamp(t,0,n.width);i=CABLES.clamp(i,0,n.height)}}if(s.get())i=v.clientHeight-i;V(t/m.pixelDensity,i/m.pixelDensity)}function P(){if(!_)return;_.removeEventListener("touchend",M);_.removeEventListener("touchstart",F);_.removeEventListener("touchmove",I);_.removeEventListener("touchcancel",y);_.removeEventListener("mousemove",R);_.removeEventListener("mouseleave",C);_.removeEventListener("mousedown",E);_.removeEventListener("mouseup",A);_.removeEventListener("mouseenter",T);_.removeEventListener("pointermove",R);_.removeEventListener("pointerleave",C);_.removeEventListener("pointerdown",E);_.removeEventListener("pointerup",A);_.removeEventListener("pointerenter",T);_.removeEventListener("pointercancel",y);_.removeEventListener("click",O);_.removeEventListener("contextmenu",S);_=null}function L(){if(_||!l.get())P();if(!l.get())return;_=v=m.canvas;if(o.isLinked()){_=v=o.get()}else{if(r.get()=="Canvas Area"&&m&&m.canvas){v=m.canvas.parentElement;_=document.body}if(r.get()=="Document")v=_=document.body;if(r.get()=="Parent Element")_=v=m.canvas.parentElement}if(!v){t.setUiError("noarea","could not find area element for mouse",2);return}t.setUiError("noarea",null);let e=false;if(a.get())e={passive:true};if(n.get()=="Touch"){_.addEventListener("touchend",M,e);_.addEventListener("touchstart",F,e);_.addEventListener("touchmove",I,e)}if(n.get()=="Mouse"){_.addEventListener("mousemove",R,e);_.addEventListener("mouseleave",C,e);_.addEventListener("mousedown",E,e);_.addEventListener("mouseup",A,e);_.addEventListener("mouseenter",T,e)}if(n.get()=="Pointer"){_.addEventListener("pointermove",R,e);_.addEventListener("pointerleave",C,e);_.addEventListener("pointerdown",E,e);_.addEventListener("pointerup",A,e);_.addEventListener("pointerenter",T,e)}_.addEventListener("contextmenu",S,e);_.addEventListener("click",O,e)}}};CABLES.OPS["c86eb411-a996-47cd-a149-264903dc408c"]={f:Ops.Devices.Mouse.Mouse_v4,objName:"Ops.Devices.Mouse.Mouse_v4"};Ops.Anim.Smooth=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inTrigger("Update"),n=e.inBool("Separate inc/dec",false),r=e.inValue("Value"),s=e.outTrigger("Next"),a=e.inValue("Inc factor",4),o=e.inValue("Dec factor",4),l=e.outNumber("Result",0);let u=0;let h=0;let c=0;let g=0;e.toWorkPortsNeedToBeLinked(i);let f;let d;let m=4;let p=true;let _=0;const v=0;const x=1;b();T();n.setUiAttribs({hidePort:true});a.onChange=o.onChange=T;n.onChange=b;E();function b(){const e=n.get();if(!e)_=v;else _=x;if(_==v){o.setUiAttribs({greyout:true});a.setUiAttribs({title:"Inc/Dec factor"})}else if(_==x){o.setUiAttribs({greyout:false});a.setUiAttribs({title:"Inc factor"})}T();E()}function T(){if(_==v){f=a.get();d=a.get()}else if(_==x){f=a.get();d=o.get()}if(f<=.2||f!=f)f=.2;if(d<=.2||d!=d)d=.2}r.onChange=function(){p=false;let e=h;h=r.get()};a.onChange=function(){T()};function E(){let e=1;if(performance.now()-g>500||g===0)u=r.get()||0;else e=(performance.now()-g)/(performance.now()-g);g=performance.now();if(u!=u)u=0;if(m<=0)m=1e-4;const t=h-u;if(t>=0)u+=t/(d*e);else u+=t/(f*e);if(Math.abs(t)<1e-5)u=h;if(m!=m)u=0;if(u!=u||u==-Infinity||u==Infinity)u=r.get();if(c!=u){l.set(u);c=u}if(u==h&&!p){p=true;l.set(u)}}i.onTriggered=function(){E();s.trigger()}}};CABLES.OPS["5677b5b5-753a-4fbf-9e91-64c81ec68a2f"]={f:Ops.Anim.Smooth,objName:"Ops.Anim.Smooth"};Ops.Gl.ImageCompose.BarrelDistortion_v3=class extends CABLES.Op{constructor(){super(...arguments);const t=this;const e=t.attachments={barreldistort_frag:"IN vec2 texCoord;\nUNI sampler2D tex;\nUNI float amount;
30982\nUNI float intensity;\n\n{{CGL.BLENDMODES3}}\n\n// adapted from https://www.shadertoy.com/view/MlSXR3\n\nvec2 brownConradyDistortion(vec2 uv)\n{\n// positive values of K1 give barrel distortion, negative give pincushion\n float barrelDistortion1 = intensity*10.; // K1 in text books\n float barrelDistortion2 = 0.; // K2 in text books\n float r2 = uv.x*uv.x + uv.y*uv.y;\n uv *= 1.0 + barrelDistortion1 * r2 + barrelDistortion2 * r2 * r2;\n\n // tangential distortion (due to off center lens elements)\n // is not modeled in this function, but if it was, the terms would go here\n return uv;\n}\n\nvoid main()\n{\n vec2 tc=brownConradyDistortion(texCoord-0.5)+0.5;\n vec4 col=texture(tex,texCoord);\n vec4 base=texture(tex,tc);\n\n col.a=0.0;\n outColor=cgl_blendPixel(col,base,amount);\n}"};const i=t.inTrigger("render"),n=CGL.TextureEffect.AddBlendSelect(t,"Blend Mode","normal"),r=t.inValueSlider("Amount",1),s=t.inValue("Intensity",10),a=t.outTrigger("Trigger");const o=t.patch.cgl;const l=new CGL.Shader(o,t.name,t);l.setSource(l.getDefaultVertexShader(),e.barreldistort_frag);const u=new CGL.Uniform(l,"t","tex",0),h=new CGL.Uniform(l,"f","intensity",0),c=new CGL.Uniform(l,"f","amount",r);CGL.TextureEffect.setupBlending(t,l,n,r);i.onTriggered=function(){if(!CGL.TextureEffect.checkOpInEffect(t,3))return;let e=o.currentTextureEffect.getCurrentSourceTexture();h.setValue(s.get()*(1/e.width));o.pushShader(l);o.currentTextureEffect.bind();o.setTexture(0,e.tex);o.currentTextureEffect.finish();o.popShader();a.trigger()}}};CABLES.OPS["d5efa9e4-d552-42f8-a345-d49e5e861602"]={f:Ops.Gl.ImageCompose.BarrelDistortion_v3,objName:"Ops.Gl.ImageCompose.BarrelDistortion_v3"};Ops.Math.Multiply=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inValueFloat("number1",1),n=e.inValueFloat("number2",1),r=e.outNumber("result");e.setUiAttribs({mathTitle:true});i.onChange=n.onChange=s;s();function s(){const e=i.get();const t=n.get();r.set(e*t)}}};CABLES.OPS["1bbdae06-fbb2-489b-9bcc-36c9d65bd441"]={f:Ops.Math.Multiply,objName:"Ops.Math.Multiply"};Ops.Math.Sum=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inValueFloat("number1",0),n=e.inValueFloat("number2",0),r=e.outNumber("result");e.setUiAttribs({mathTitle:true});i.onChange=n.onChange=s;s();function s(){const e=i.get()+n.get();if(!isNaN(e))r.set(e)}}};CABLES.OPS["c8fb181e-0b03-4b41-9e55-06b6267bc634"]={f:Ops.Math.Sum,objName:"Ops.Math.Sum"};Ops.Math.Sine=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inValue("value"),n=e.inValue("phase",0),r=e.inValue("frequency",1),s=e.inValue("amplitude",1),a=e.inValueBool("asine",false),o=e.outNumber("result");let l=Math.sin;r.onChange=s.onChange=n.onChange=i.onChange=function(){o.set(s.get()*l(i.get()*r.get()+n.get()))};a.onChange=function(){if(a.get())l=Math.asin;else l=Math.sin}}};CABLES.OPS["d24da018-9f3d-428b-85c9-6ff14d77548b"]={f:Ops.Math.Sine,objName:"Ops.Math.Sine"};Ops.Anim.Timer_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const s=e.inValue("Speed",1),i=e.inValueBool("Play",true),n=e.inTriggerButton("Reset"),r=e.inValueBool("Sync to timeline",false),a=e.outNumber("Time");e.setPortGroup("Controls",[i,n,s]);const o=new CABLES.Timer;let l=null;let u=0;let h=false;i.onChange=c;c();function c(){if(i.get()){o.play();
30982e.patch.addOnAnimFrame(e)}else{o.pause();e.patch.removeOnAnimFrame(e)}}n.onTriggered=g;function g(){u=0;l=null;o.setTime(0);a.set(0)}r.onChange=function(){h=r.get();i.setUiAttribs({greyout:h});n.setUiAttribs({greyout:h})};e.onAnimFrame=function(e,t,i){if(o.isPlaying()){if(CABLES.overwriteTime!==undefined){a.set(CABLES.overwriteTime*s.get())}else if(h){a.set(e*s.get())}else{o.update();const n=o.get();if(l===null){l=n;return}const r=Math.abs(n-l);l=n;u+=r*s.get();if(u!=u)u=0;a.set(u)}}}}};CABLES.OPS["aac7f721-208f-411a-adb3-79adae2e471a"]={f:Ops.Anim.Timer_v2,objName:"Ops.Anim.Timer_v2"};Ops.Gl.ImageCompose.Noise.PerlinNoise_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={perlinnoise3d_frag:'UNI float z;\nUNI float x;\nUNI float y;\nUNI float scale;\nUNI float rangeMul;\nUNI float harmonics;\nUNI float aspect;\n\nIN vec2 texCoord;\nUNI sampler2D tex;\n\n#ifdef HAS_TEX_OFFSETMAP\n UNI sampler2D texOffsetZ;\n UNI float offMul;\n#endif\n\n#ifdef HAS_TEX_MASK\n UNI sampler2D texMask;\n#endif\n\nUNI float amount;
30982\n\n{{CGL.BLENDMODES3}}\n\n\nfloat Interpolation_C2( float x ) { return x * x * x * (x * (x * 6.0 - 15.0) + 10.0); } // 6x^5-15x^4+10x^3\t( Quintic Curve. As used by Perlin in Improved Noise. http://mrl.nyu.edu/~perlin/paper445.pdf )\nvec2 Interpolation_C2( vec2 x ) { return x * x * x * (x * (x * 6.0 - 15.0) + 10.0); }\nvec3 Interpolation_C2( vec3 x ) { return x * x * x * (x * (x * 6.0 - 15.0) + 10.0); }\nvec4 Interpolation_C2( vec4 x ) { return x * x * x * (x * (x * 6.0 - 15.0) + 10.0); }\nvec4 Interpolation_C2_InterpAndDeriv( vec2 x ) { return x.xyxy * x.xyxy * ( x.xyxy * ( x.xyxy * ( x.xyxy * vec2( 6.0, 0.0 ).xxyy + vec2( -15.0, 30.0 ).xxyy ) + vec2( 10.0, -60.0 ).xxyy ) + vec2( 0.0, 30.0 ).xxyy ); }\nvec3 Interpolation_C2_Deriv( vec3 x ) { return x * x * (x * (x * 30.0 - 60.0) + 30.0); }\n\n\nvoid FAST32_hash_3D( vec3 gridcell, out vec4 lowz_hash, out vec4 highz_hash )\t//\tgenerates a random number for each of the 8 cell corners\n{\n // gridcell is assumed to be an integer coordinate\n\n //\tTODO: \tthese constants need tweaked to find the best possible noise.\n //\t\t\tprobably requires some kind of brute force computational searching or something....\n const vec2 OFFSET = vec2( 50.0, 161.0 );\n const float DOMAIN = 69.0;\n const float SOMELARGEFLOAT = 635.298681;\n const float ZINC = 48.500388;\n\n //\ttruncate the domain\n gridcell.xyz = gridcell.xyz - floor(gridcell.xyz * ( 1.0 / DOMAIN )) * DOMAIN;\n vec3 gridcell_inc1 = step( gridcell, vec3( DOMAIN - 1.5 ) ) * ( gridcell + 1.0 );\n\n //\tcalculate the noise\n vec4 P = vec4( gridcell.xy, gridcell_inc1.xy ) + OFFSET.xyxy;\n P *= P;\n P = P.xzxz * P.yyww;\n highz_hash.xy = vec2( 1.0 / ( SOMELARGEFLOAT + vec2( gridcell.z, gridcell_inc1.z ) * ZINC ) );\n lowz_hash = fract( P * highz_hash.xxxx );\n highz_hash = fract( P * highz_hash.yyyy );\n}\n\n\n\n\nvoid FAST32_hash_3D( \tvec3 gridcell,\n out vec4 lowz_hash_0,\n out vec4 lowz_hash_1,\n out vec4 lowz_hash_2,\n out vec4 highz_hash_0,\n out vec4 highz_hash_1,\n out vec4 highz_hash_2\t)\t\t//\tgenerates 3 random numbers for each of the 8 cell corners\n{\n // gridcell is assumed to be an integer coordinate\n\n //\tTODO: \tthese constants need tweaked to find the best possible noise.\n //\t\t\tprobably requires some kind of brute force computational searching or something....\n const vec2 OFFSET = vec2( 50.0, 161.0 );\n const float DOMAIN = 69.0;\n const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\n const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\n\n //\ttruncate the domain\n gridcell.xyz = gridcell.xyz - floor(gridcell.xyz * ( 1.0 / DOMAIN )) * DOMAIN;\n vec3 gridcell_inc1 = step( gridcell, vec3( DOMAIN - 1.5 ) ) * ( gridcell + 1.0 );\n\n //\tcalculate the noise\n vec4 P = vec4( gridcell.xy, gridcell_inc1.xy ) + OFFSET.xyxy;\n P *= P;\n P = P.xzxz * P.yyww;\n vec3 lowz_mod = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + gridcell.zzz * ZINC.xyz ) );\n vec3 highz_mod = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + gridcell_inc1.zzz * ZINC.xyz ) );\n lowz_hash_0 = fract( P * lowz_mod.xxxx );\n highz_hash_0 = fract( P * highz_mod.xxxx );\n lowz_hash_1 = fract( P * lowz_mod.yyyy );\n highz_hash_1 = fract( P * highz_mod.yyyy );\n lowz_hash_2 = fract( P * lowz_mod.zzzz );\n highz_hash_2 = fract( P * highz_mod.zzzz );\n}\nfloat Falloff_Xsq_C1( float xsq ) { xsq = 1.0 - xsq; return xsq*xsq; }\t// ( 1.0 - x*x )^2 ( Used by Humus for lighting falloff in Just Cause 2. GPUPro 1 )\nfloat Falloff_Xsq_C2( float xsq ) { xsq = 1.0 - xsq; return xsq*xsq*xsq; }\t// ( 1.0 - x*x )^3. NOTE: 2nd derivative is 0.0 at x=1.0, but non-zero at x=0.0\nvec4 Falloff_Xsq_C2( vec4 xsq ) { xsq = 1.0 - xsq; return xsq*xsq*xsq; }\n\n\n//\n//\tPerlin Noise 3D ( gradient noise )\n//\tReturn value range of -1.0->1.0\n//\thttp://briansharpe.files.wordpress.com/2011/11/perlinsample.jpg\n//\nfloat Perlin3D( vec3 P )\n{\n //\testablish our grid cell and unit position\n vec3 Pi = floor(P);\n vec3 Pf = P - Pi;\n vec3 Pf_min1 = Pf - 1.0;\n\n#if 1\n //\n //\tclassic noise.\n //\trequires 3 random values per point. with an effice
30982nt hash function will run faster than improved noise\n //\n\n //\tcalculate the hash.\n //\t( various hashing methods listed in order of speed )\n vec4 hashx0, hashy0, hashz0, hashx1, hashy1, hashz1;\n FAST32_hash_3D( Pi, hashx0, hashy0, hashz0, hashx1, hashy1, hashz1 );\n //SGPP_hash_3D( Pi, hashx0, hashy0, hashz0, hashx1, hashy1, hashz1 );\n\n //\tcalculate the gradients\n vec4 grad_x0 = hashx0 - 0.49999;\n vec4 grad_y0 = hashy0 - 0.49999;\n vec4 grad_z0 = hashz0 - 0.49999;\n vec4 grad_x1 = hashx1 - 0.49999;\n vec4 grad_y1 = hashy1 - 0.49999;\n vec4 grad_z1 = hashz1 - 0.49999;\n vec4 grad_results_0 = inversesqrt( grad_x0 * grad_x0 + grad_y0 * grad_y0 + grad_z0 * grad_z0 ) * ( vec2( Pf.x, Pf_min1.x ).xyxy * grad_x0 + vec2( Pf.y, Pf_min1.y ).xxyy * grad_y0 + Pf.zzzz * grad_z0 );\n vec4 grad_results_1 = inversesqrt( grad_x1 * grad_x1 + grad_y1 * grad_y1 + grad_z1 * grad_z1 ) * ( vec2( Pf.x, Pf_min1.x ).xyxy * grad_x1 + vec2( Pf.y, Pf_min1.y ).xxyy * grad_y1 + Pf_min1.zzzz * grad_z1 );\n\n#if 1\n //\tClassic Perlin Interpolation\n vec3 blend = Interpolation_C2( Pf );\n vec4 res0 = mix( grad_results_0, grad_results_1, blend.z );\n vec4 blend2 = vec4( blend.xy, vec2( 1.0 - blend.xy ) );\n float final = dot( res0, blend2.zxzx * blend2.wwyy );\n final *= 1.1547005383792515290182975610039;\t\t//\t(optionally) scale things to a strict -1.0->1.0 range *= 1.0/sqrt(0.75)\n return final;\n#else\n //\tClassic Perlin Surflet\n //\thttp://briansharpe.wordpress.com/2012/03/09/modifications-to-classic-perlin-noise/\n Pf *= Pf;\n Pf_min1 *= Pf_min1;\n vec4 vecs_len_sq = vec4( Pf.x, Pf_min1.x, Pf.x, Pf_min1.x ) + vec4( Pf.yy, Pf_min1.yy );\n float final = dot( Falloff_Xsq_C2( min( vec4( 1.0 ), vecs_len_sq + Pf.zzzz ) ), grad_results_0 ) + dot( Falloff_Xsq_C2( min( vec4( 1.0 ), vecs_len_sq + Pf_min1.zzzz ) ), grad_results_1 );\n final *= 2.3703703703703703703703703703704;\t\t//\t(optionally) scale things to a strict -1.0->1.0 range *= 1.0/cube(0.75)\n return final;\n#endif\n\n#else\n //\n //\timproved noise.\n //\trequires 1 random value per point. Will run faster than classic noise if a slow hashing function is used\n //\n\n //\tcalculate the hash.\n //\t( various hashing methods listed in order of speed )\n vec4 hash_lowz, hash_highz;\n FAST32_hash_3D( Pi, hash_lowz, hash_highz );\n //BBS_hash_3D( Pi, hash_lowz, hash_highz );\n //SGPP_hash_3D( Pi, hash_lowz, hash_highz );\n\n //\n //\t"improved" noise using 8 corner gradients. Faster than the 12 mid-edge point method.\n //\tKen mentions using diagonals like this can cause "clumping", but we\'ll live with that.\n //\t[1,1,1] [-1,1,1] [1,-1,1] [-1,-1,1]\n //\t[1,1,-1] [-1,1,-1] [1,-1,-1] [-1,-1,-1]\n //\n hash_lowz -= 0.5;\n vec4 grad_results_0_0 = vec2( Pf.x, Pf_min1.x ).xyxy * sign( hash_lowz );\n hash_lowz = abs( hash_lowz ) - 0.25;\n vec4 grad_results_0_1 = vec2( Pf.y, Pf_min1.y ).xxyy * sign( hash_lowz );\n vec4 grad_results_0_2 = Pf.zzzz * sign( abs( hash_lowz ) - 0.125 );\n vec4 grad_results_0 = grad_results_0_0 + grad_results_0_1 + grad_results_0_2;\n\n hash_highz -= 0.5;\n vec4 grad_results_1_0 = vec2( Pf.x, Pf_min1.x ).xyxy * sign( hash_highz );\n hash_highz = abs( hash_highz ) - 0.25;\n vec4 grad_results_1_1 = vec2( Pf.y, Pf_min1.y ).xxyy * sign( hash_highz );\n vec4 grad_results_1_2 = Pf_min1.zzzz * sign( abs( hash_highz ) - 0.125 );\n vec4 grad_results_1 = grad_results_1_0 + grad_results_1_1 + grad_results_1_2;\n\n //\tblend the gradients and return\n vec3 blend = Interpolation_C2( Pf );\n vec4 res0 = mix( grad_results_0, grad_results_1, blend.z );\n vec4 blend2 = vec4( blend.xy, vec2( 1.0 - blend.xy ) );\n return dot( res0, blend2.zxzx * blend2.wwyy ) * (2.0 / 3.0);\t//\t(optionally) mult by (2.0/3.0) to scale to a strict -1.0->1.0 range\n#endif\n}\n\nvoid main()\n{\n vec4 base=texture(tex,texCoord);\n vec2 p=vec2(texCoord.x-0.5,texCoord.y-0.5);\n\n p=p*scale;\n p=vec2(p.x+0.5-x,p.y+0.5-y);\n\n\n\n vec3 offset;\n #ifdef HAS_TEX_OFFSETMAP\n vec4 offMap=texture(texOffsetZ,texCoord);\n\n #ifdef OFFSET_X_R\n offset.x=offMap.r;\n #endif\n #ifdef OFFSET_X_G\n offset.x=offMap.g;\n #endif\n #ifdef OFFSET_X_B\n offset.x=offMap.b;\n #endif\n\n #ifdef OFFSET_Y_R\n offset.y=offMap.r;\n #endif\n #ifdef OFFSET_Y_G\n offset.y=offMap.g;\n #endif\n #ifdef OFFSET_Y_B\n offset.y=offMap.b;\n #endif\n\n #ifdef OFFSET_Z_R\n offset.z=offMap.r;\n #endif\n #ifdef OFFSET_Z_G\n offset.z=offMap.g;\n #endif\n #ifdef OFFSET_Z_B\n offset.z=offMap.b;\n #endif\n offset*=offMul;\n #endif\n\n float aa=texture(tex,texCoord).r;\n\n float v = 0.0;\n p.x*=aspect;\n\n v+=Perlin3D(vec3(p.x,p.y,z)+offset);\n\n #ifdef HARMONICS\n if (harmonics >= 2.0) v += Perlin3D(vec3(p.x,p.y,z)*2.2+offset) * 0.5;\n if (harmonics >= 3.0) v += Perlin3D(vec3(p.x,p.y,z)*4.3+offset) * 0.25;\n if (harmonics >= 4.0) v += Perlin3D(vec3(p.x,p.y,z)*8.4+offset) * 0.125;\n if (harmonics >= 5.0) v += Perlin3D(vec3(p.x,p.y,z)*16.5+offset) * 0.0625;\n #endif\n\n\n v*=rangeMul;\n v=v*0.5+0.5;\n float v2=v;\n float v3=v;\n\n #ifdef RGB\n v2=Perlin3D(vec3(p.x+2.0,p.y+2.0,z))*0.5+0.5;\n\n #ifdef HARMONICS\n if (harmonics >= 2.0) v2 += Perlin3D(vec3(p.x,p.y,z)*2.2+offset) * 0.5;\n if (harmonics >= 3.0) v2 += Perlin3D(vec3(p.x,p.y,z)*4.3+offset) * 0.25;\n if (harmonics >= 4.0) v2 += Perlin3D(vec3(p.x,p.y,z)*8.4+offset) * 0.125;\n if (harmonics >= 5.0) v2 += Perlin3D(vec3(p.x,p.y,z)*16.5+offset) * 0.0625;\n #endif\n\n v3=Perlin3D(vec3(p.x+3.0,p.y+3.0,z))*0.5+0.5;\n\n #ifdef HARMONICS\n if (harmonics >= 2.0) v3 += Perlin3D(vec3(p.x,p.y,z)*2.2+offset) * 0.5;\n if (harmonics >= 3.0) v3 += Perlin3D(vec3(p.x,p.y,z)*4.3+offset) * 0.25;\n if (harmonics >= 4.0) v3 += Perlin3D(vec3(p.x,p.y,z)*8.4+offset) * 0.125;\n if (harmonics >= 5.0) v3 += Perlin3D(vec3(p.x,p.y,z)*16.5+offset) * 0.0625;\n #endif\n\n #endif\n\n vec4 col=vec4(v,v2,v3,1.0);\n\n float str=1.0;\n #ifdef HAS_TEX_MASK\n str=texture(texMask,texCoord).r;\n #endif\n\n #ifdef RANGE_MIN1\n col=col*2.0-1.0;\n #endif\n\n col=cgl_blendPixel(base,col,amount*str);\n\n\n #ifdef NO_CHANNEL_R\n col.r=base.r;\n #endif\n #ifdef NO_CHANNEL_G\n col.g=base.g;\n #endif\n #ifdef NO_CHANNEL_B\n col.b=base.b;\n #endif\n\n\n\n outColor=col;\n}\n'};const i=e.inTrigger("render"),n=e.inTexture("Mask"),r=CGL.TextureEffect.AddBlendSelect(e),s=CGL.TextureEffect.AddBlendAlphaMask(e),a=e.inValueSlider("Amount",1),o=e.inSwitch("Color",["Mono","RGB","R","G","B"],"Mono"),l=e.inValue("Scale",8),u=e.inValue("Multiply",1),h=e.inSwitch("Value",["0-1","-1-1"],"0-1"),c=e.inSwitch("Harmonics",["1","2","3","4","5"],"1"),g=e.inValue("X",0),f=e.inValue("Y",0),d=e.inValue("Z",0),m=e.outTrigger("trigger");const p=e.patch.cgl;const _=new CGL.Shader(p,"perlinnoise");e.setPortGroup("Position",[g,f,d]);_.setSource(_.getDefaultVertexShader(),t.perlinnoise3d_frag);const v=new CGL.Uniform(_,"t","tex",0),x=new CGL.Uniform(_,"t","texOffsetZ",1),b=new CGL.Uniform(_,"t","texMask",2),T=new CGL.Uniform(_,"f","z",d),E=new CGL.Uniform(_,"f","x",g),A=new CGL.Uniform(_,"f","y",f),S=new CGL.Uniform(_,"f","scale",l),O=new CGL.Uniform(_,"f","amount",a),C=new CGL.Uniform(_,"f","rangeMul",u);CGL.TextureEffect.setupBlending(e,_,r,a,s);const R=e.inTexture("Offset"),I=e.inFloat("Offset Multiply",1),F=e.inSwitch("Offset X",["None","R","G","B"],"None"),M=e.inSwitch("Offset Y",["None","R","G","B"],"None"),y=e.inSwitch("Offset Z",["N
30982one","R","G","B"],"R");e.setPortGroup("Offset Map",[R,y,M,F,I]);const D=new CGL.Uniform(_,"f","offMul",I);const N=new CGL.Uniform(_,"f","aspect",1);const P=new CGL.Uniform(_,"f","harmonics",0);c.onChange=()=>{P.setValue(parseFloat(c.get()));_.toggleDefine("HARMONICS",c.get()>1)};h.onChange=F.onChange=M.onChange=y.onChange=n.onChange=o.onChange=R.onChange=L;L();function L(){_.toggleDefine("NO_CHANNEL_R",o.get()=="G"||o.get()=="B");_.toggleDefine("NO_CHANNEL_G",o.get()=="R"||o.get()=="B");_.toggleDefine("NO_CHANNEL_B",o.get()=="R"||o.get()=="G");_.toggleDefine("HAS_TEX_OFFSETMAP",R.get());_.toggleDefine("HAS_TEX_MASK",n.get());_.toggleDefine("OFFSET_X_R",F.get()=="R");_.toggleDefine("OFFSET_X_G",F.get()=="G");_.toggleDefine("OFFSET_X_B",F.get()=="B");_.toggleDefine("OFFSET_Y_R",M.get()=="R");_.toggleDefine("OFFSET_Y_G",M.get()=="G");_.toggleDefine("OFFSET_Y_B",M.get()=="B");_.toggleDefine("OFFSET_Z_R",y.get()=="R");_.toggleDefine("OFFSET_Z_G",y.get()=="G");_.toggleDefine("OFFSET_Z_B",y.get()=="B");_.toggleDefine("RANGE_MIN1",h.get()=="-1-1");F.setUiAttribs({greyout:!R.isLinked()});M.setUiAttribs({greyout:!R.isLinked()});y.setUiAttribs({greyout:!R.isLinked()});I.setUiAttribs({greyout:!R.isLinked()});_.toggleDefine("RGB",o.get()=="RGB")}i.onTriggered=function(){if(!CGL.TextureEffect.checkOpInEffect(e,3))return;p.pushShader(_);p.currentTextureEffect.bind();N.setValue(p.currentTextureEffect.aspectRatio);p.setTexture(0,p.currentTextureEffect.getCurrentSourceTexture().tex);if(R.get())p.setTexture(1,R.get().tex);if(n.get())p.setTexture(2,n.get().tex);p.currentTextureEffect.finish();p.popShader();m.trigger()}}};CABLES.OPS["b4b238d3-db68-4206-8dc7-4b52433fc932"]={f:Ops.Gl.ImageCompose.Noise.PerlinNoise_v2,objName:"Ops.Gl.ImageCompose.Noise.PerlinNoise_v2"};Ops.Html.Elements.Element_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const B=e.attachments={};const t=e.inString("Text","Element"),i=e.inSwitch("Position",["Absolute","Static","Relative","Fixed"],"Absolute"),n=e.inSwitch("Interactive",["True","False","No Pointer Events"],"True"),r=e.inValueBool("Set Size",false),s=e.inFloat("Width",100),a=e.inFloat("Height",100),o=e.inSwitch("Size Units",["px","%","vwh"],"px"),l=e.inSwitch("Overflow",["Visible","Hidden","Scroll","Auto"],"Hidden"),u=e.inStringEditor("Inline Style","","inline-css"),h=e.inString("CSS Class"),w=e.inString("Disable CSS Props"),c=e.inDropDown("Display",["None","Block","Inline","inline-block","flex","inline-flex","grid","inline-grid","flow-root"],"Block"),g=e.inString("Tag Name","div"),f=e.inFloatSlider("Opacity",1),U=e.inValueBool("Propagate Click-Events",true),d=e.inValueBool("Add to DOM",true),m=e.outObject("DOM Element",null,"element"),p=e.outBoolNum("Hovering"),_=e.outTrigger("Clicked");e.setPortGroup("Area",[s,a,r,o,l]);e.setPortGroup("CSS",[h,u,w]);let v=null;let x=null;let V="block";let b=null;const T=e.patch.containerElement;O();h.onChange=F;t.onChange=R;g.onChange=()=>{C();O();F();R();L()};r.onChange=S;c.onChange=f.onChange=i.onChange=s.onChange=a.onChange=l.onChange=o.onChange=a.onChange=u.onChange=I;n.onChange=L;R();S();D();L();let E="";e.onDelete=C;m.onLinkChanged=I;n.onLinkChanged=_.onLinkChanged=()=>{e.setUiError("interactiveProblem",null);if(_.isLinked()&&!G())e.setUiError("interactiveProblem","Interactive should be activated when linking clicked port")};d.onChange=()=>{if(!d.get())C();else{O();A()}};function A(){I();F();R();L()}function S(){s.setUiAttribs({greyout:!r.get()});o.setUiAttribs({greyout:!r.get()});a.setUiAttribs({greyout:!r.get()});I()}function O(){b=e.patch.getDocument().createElement(g.get()||"div");b.dataset.op=e.id;b.classList.add("cablesEle");T.appendChild(b);m.setRef(b);I()}function C(){if(b)k();if(b&&b.parentNode)b.parentNode.removeChild(b);x=null;b=null}function R(){let e=t.get();if(x===e)return;x=e;if(b&&b.innerHTML!=e)b.innerHTML=e}function I(){if(!b)return;b.setAttribute("style",u.get());b.style.position=i.get().toLowerCase();b.style.overflow=l.get().toLowerCase();b.style.display=c.get();b.style.opacity=f.get();if(n.get()=="No Pointer Events")b.style.pointerEvents="none";if(r.get()){b.style.width=s.get()+o.get();b.style.height=a.get()+o.get()}else{b.style.width="";b.style.height=""}m.setRef(b);if(!b.parentElement)T.appendChild(b);D()}function k(){if(!b)return;const t=(h.get()||"").split(" ");for(let e=0;e<t.length;e++){try{if(t[e])b.classList.remove(t[e])}catch(e){console.log("e",e)}}E=""}function F(){const t=(h.get()||"").split(" ");const i=(E||"").split(" ");let n=false;for(let e=0;e<i.length;e++){if(i[e]&&t.indexOf(i[e].trim())==-1){n=true;b.classList.remove(i[e])}}for(let e=0;e<t.length;e++){if(t[e]){b.classList.add(t[e].trim())}}E=h.get();D();m.setRef(b)}function M(e){p.set(true)}function y(e){p.set(false)}function N(e){if(e.keyCode==13||e.keyCode==32)_.trigger()}function P(e){if(!U.get())e.stopPropagation();_.trigger()}function G(){return n.get()!="No Pointer Events"}function L(){e.setUiError("interactiveProblem",null);j();if(G())z();I()}function j(){if(v){v.removeEventListener("pointerdown",P);v.removeEventListener("pointerleave",y);v.removeEventListener("pointerenter",M);v.removeEventListener("keydown",N,false);v.removeAttribute("tabindex");v=null}}function z(){if(v)j();v=b;if(v){v.addEventListener("pointerdown",P);v.addEventListener("pointerleave",y);v.addEventListener("pointerenter",M);v.setAttribute("tabindex",0);v.addEventListener("keydown",N,false)}}e.addEventListener("onEnabledChange",e=>{C();if(!e)return;O();A()});function D(){if(h.get()&&u.get()){e.setUiError("error","Element uses external and inline CSS",1)}else{e.setUiError("error",null)}}}};CABLES.OPS["a0d2cc80-0b2f-4422-ba2d-c903ac9ca297"]={f:Ops.Html.Elements.Element_v2,objName:"Ops.Html.Elements.Element_v2"};Ops.Boolean.IfTrueThen_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inTrigger("exe"),n=e.inValueBool("boolean",false),r=e.outTrigger("then"),s=e.outTrigger("else");i.onTriggered=a;function a(){if(n.get())r.trigger();else s.trigger()}}};CABLES.OPS["9549e2ed-a544-4d33-a672-05c7854ccf5d"]={f:Ops.Boolean.IfTrueThen_v2,objName:"Ops.Boolean.IfTrueThen_v2"};Ops.Html.QuerySelectorAll_v2=class extends CABLES.Op{constructor(){super(...arguments);const s=this;const e=s.attachments={};const t=s.inString("Query"),a=s.inValueSelect("Mode",["document","string input","element"],"document"),o=s.inValueSelect("Type",["text/html","text/xml"],"text/html"),l=s.inStringEditor("Document","xml"),u=s.inObject("Element",null,"element"),i=s.inTriggerButton("Update"),h=s.outArray("Elements");if(a.get()==="document"){l.setUiAttribs({greyout:true});o.set("text/html");o.setUiAttribs({greyout:true})}s.toWorkPortsNeedsString(t);i.onTriggered=n;a.onChange=r;function n(){s.setUiError("exc",null);const i=t.get();const n=l.get();const e=a.get();if(e==="string input"&&n){let e=new DOMParser;let t=null;try{t=e.parseFromString(n,o.get());const r=Array.from(t.querySelectorAll(i));h.set(r)}catch(e){s.setUiError("exc",e.message,1);s.logWarn(e)}}else if(e==="document"){try{const r=Array.from(document.querySelectorAll(i));h.set(r)}catch(e){s.setUiError("exc",e.message,1);s.logWarn(e)}}else{try{let e=null;if(u.get()){e=Array.from(u.get().querySelectorAll(i))}h.set(e)}catch(e){s.setUiError("exc",e.message,1);s.logWarn(e)}}}function r(){if(a.get()==="document"){l.setUiAttribs({greyout:true});o.setUiAttribs({greyout:true});u.setUiAttribs({greyout:true})}
30982else if(a.get()==="string input"){l.setUiAttribs({greyout:false});o.setUiAttribs({greyout:false});u.setUiAttribs({greyout:true})}else{l.setUiAttribs({greyout:true});o.setUiAttribs({greyout:true});u.setUiAttribs({greyout:false})}}}};CABLES.OPS["1a1d80e0-0de8-4c4d-8eaa-e2a0eac6239a"]={f:Ops.Html.QuerySelectorAll_v2,objName:"Ops.Html.QuerySelectorAll_v2"};Ops.Html.CSS.ElementCssTransform_v2=class extends CABLES.Op{constructor(){super(...arguments);const t=this;const e=t.attachments={};const i=t.inObject("Element",null,"element"),n=t.inBool("Translate Active",true),r=t.inFloat("Translate X",0),s=t.inFloat("Translate Y",0),a=t.inSwitch("Unit",["px","%"],"px"),o=t.inBool("Scale Active",true),l=t.inFloat("Scale",1),u=t.inBool("Rotate Active",true),h=t.inFloat("Rot Z",0),c=t.inBool("Set Origin",true),g=t.inSwitch("Origin X",["left","center","right"],"center"),f=t.inSwitch("Origin Y",["top","center","bottom"],"center"),d=t.inBool("Z Index Active",false),m=t.inFloat("Z Index",100),p=t.outObject("Passthrough",null,"element");t.setPortGroup("Element",[i]);t.setPortGroup("Translation",[n,s,r,a]);t.setPortGroup("Scaling",[l,o]);t.setPortGroup("Rotation",[u,h]);t.setPortGroup("Origin",[c,g,f]);a.onChange=g.onChange=f.onChange=r.onChange=s.onChange=l.onChange=m.onChange=h.onChange=b;let _=null;let v=null;n.onChange=c.onChange=o.onChange=d.onChange=u.onChange=x;i.onChange=i.onLinkChanged=function(){if(_&&_.style){_.style.transform="initial";if(CABLES.UI&&i.get()&&_!=i.get()){if(window.getComputedStyle(_).position!=="absolute")t.setUiError("oppos","Element position should be absolute")}}if(CABLES.UI)t.setUiError("oppos",null);b();p.setRef(i.get())};function x(){r.setUiAttribs({greyout:!n.get()});s.setUiAttribs({greyout:!n.get()});l.setUiAttribs({greyout:!o.get()});h.setUiAttribs({greyout:!u.get()});m.setUiAttribs({greyout:!d.get()});f.setUiAttribs({greyout:!c.get()});g.setUiAttribs({greyout:!c.get()});b()}function b(){_=i.get();if(_&&_.style){let e="";if(n.get())e+="translate("+r.get()+a.get()+" , "+s.get()+a.get()+") ";if(o.get())if(l.get()!=1)e+="scale("+l.get()+") ";if(u.get())if(h.get()!=0)e+="rotateZ("+h.get()+"deg) ";if(d.get())_.style["z-index"]=m.get();try{_.style.transform=e;if(c.get())_.style["transform-origin"]=f.get()+" "+g.get();else _.style["transform-origin"]="initial"}catch(e){t.logError(e)}p.setRef(_)}else{clearTimeout(v);v=setTimeout(b,150)}}}};CABLES.OPS["11381bfe-38b0-4051-aef9-69d83c292f0d"]={f:Ops.Html.CSS.ElementCssTransform_v2,objName:"Ops.Html.CSS.ElementCssTransform_v2"};Ops.Array.ArrayIteratorObjects=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inTrigger("exe"),n=e.inArray("array"),r=e.outTrigger("trigger"),s=e.outTrigger("finished"),a=e.outNumber("index"),o=e.outObject("value");i.onTriggered=function(){const t=n.get();if(!t)return;for(let e=0;e<t.length;e++){o.setRef(t[e]);a.set(e);r.trigger()}s.trigger()}}};CABLES.OPS["481d2d8f-b9ee-42a0-a905-caf9dc23a63f"]={f:Ops.Array.ArrayIteratorObjects,objName:"Ops.Array.ArrayIteratorObjects"};Ops.Cables.UIMode=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.outBoolNum("UI",e.patch.isEditorMode()),n=e.outBoolNum("Overlay Mode",false),r=e.outBoolNum("Remote Viewer",window.gui?window.gui.isRemoteClient:false),s=e.outBoolNum("Is Standalone",CABLES.platform&&CABLES.platform.frontendOptions.isElectron),a=e.outNumber("Canvas Mode"),o=e.outBoolNum("Patch Field Visible");if(CABLES.UI){n.set(gui.shouldDrawOverlay);gui.on("overlaysChanged",e=>{n.set(e)});gui.on("canvasModeChange",()=>{a.set(gui.canvasManager.mode);o.set(gui.patchView.element.classList.contains("hidden"))})}}};CABLES.OPS["7c110d60-829f-4b06-b3e4-0af911550570"]={f:Ops.Cables.UIMode,objName:"Ops.Cables.UIMode"};Ops.Gl.Meshes.TextMesh_v2=class extends CABLES.Op{constructor(){super(...arguments);const t=this;const e=t.attachments={textmesh_frag:"{{MODULES_HEAD}}\n\n#define INSTANCING\n\nUNI sampler2D tex;\n#ifdef DO_MULTEX\n UNI sampler2D texMul;\n#endif\n#ifdef DO_MULTEX_MASK\n UNI sampler2D texMulMask;\n#endif\nIN vec2 texCoord;\nIN vec2 texPos;\nUNI float r;\nUNI float g;\nUNI float b;\nUNI float a;\n\nflat IN float frag_instIndex;\n\nvoid main()\n{\n {{MODULE_BEGIN_FRAG}}\n\n vec4 col=texture(tex,texCoord);\n col.a=col.r;\n col.r*=r;\n col.g*=g;\n col.b*=b;\n col*=a;\n\n if(col.a==0.0)discard;\n\n #ifdef DO_MULTEX\n col*=texture(texMul,texPos);\n #endif\n\n #ifdef DO_MULTEX_MASK\n col*=texture(texMulMask,texPos).r;\n #endif\n\n {{MODULE_COLOR}}\n\n outColor=col;\n}",textmesh_vert:"{{MODULES_HEAD}}\n\nUNI sampler2D tex;\nUNI mat4 projMatrix;\nUNI mat4 modelMatrix;\nUNI mat4 viewMatrix;\nUNI float scale;\nIN vec3 vPosition;\nIN vec2 attrTexCoord;\nIN mat4 instMat;\nIN vec2 attrTexOffsets;\nIN vec2 attrTexSize;\nIN vec2 attrTexPos;\nIN float attrVertIndex;\nIN float instanceIndex;\nflat OUT float frag_instIndex;\n\nOUT vec2 texPos;\n\nOUT vec2 texCoord;\nOUT vec4 modelPos;\n\nvoid main()\n{\n\n texCoord=(attrTexCoord*(attrTexSize)) + attrTexOffsets;\n mat4 instMVMat=instMat;\n instMVMat[3][0]*=scale;\n\n texPos=attrTexPos;\n\n vec4 pos=vec4( vPosition.x*(attrTexSize.x/attrTexSize.y)*scale,vPosition.y*scale,vPosition.z*scale, 1. );\n\n mat4 mvMatrix=viewMatrix * modelMatrix * instMVMat;\n frag_instIndex=instanceIndex;\n\n {{MODULE_VERTEX_POSITION}}\n\n gl_Position = projMatrix * mvMatrix * pos;\n}\n\n"};const i=t.inTrigger("Render"),v=t.inString("Text","cables"),n=t.inFloat("Scale Text",1),r=t.inValueFloat("Scale",1),h=t.inString("Font","Arial"),x=t.inValueSelect("align",["left","center","right"],"center"),s=t.inValueSelect("vertical align",["Top","Middle","Bottom"],"Middle"),b=t.inValueFloat("Line Height",1),T=t.inValueFloat("Letter Spacing"),o=t.inSwitch("filter",["nearest","linear","mipmap"],"mipmap"),l=t.inSwitch("Anisotropic",[0,1,2,4,8,16],0),a=t.inTexture("Texture Color"),u=t.inTexture("Texture Mask"),B=t.outTrigger("Next"),E=t.outTexture("texture"),w=t.outNumber("Total Lines",0),U=t.outNumber("Width",0),V=t.outBoolNum("Font Available",0);const A=t.patch.cgl;const c=vec3.create();vec3.set(c,1,1,1);t.toWorkPortsNeedToBeLinked(i);t.setPortGroup("Masking",[a,u]);r.setUiAttribs({title:"Line Scale"});E.setUiAttribs({hidePort:true});const g=1024;let f=false;let d=true;x.onChange=v.onChange=b.onChange=k;function k(){d=true}let m=null;CABLES.OpTextureMeshCanvas={};let p=0;const G=null;let S=null;let O=true;let C=true;t.onDelete=function(){if(S)S.dispose()};n.onChange=()=>{vec3.set(c,n.get(),n.get(),n.get())};l.onChange=o.onChange=()=>{R().texture=null;C=true};u.onChange=a.onChange=function(){I.toggleDefine("DO_MULTEX",a.get());I.toggleDefine("DO_MULTEX_MASK",u.get())};E.setRef(null);h.onChange=function(){C=true;O=true;_()};
30982t.patch.on("fontLoaded",e=>{if(e==h.get()){C=true;O=true}});function _(){const e=f;try{f=document.fonts.check('20px "'+h.get()+'"')}catch(e){t.logError(e)}if(!e&&f){V.set(true);C=true;O=true}if(!f)setTimeout(_,250)}s.onChange=function(){if(s.get()=="Middle")p=0;else if(s.get()=="Top")p=1;else if(s.get()=="Bottom")p=2};function R(){m=""+h.get();if(CABLES.OpTextureMeshCanvas.hasOwnProperty(m))return CABLES.OpTextureMeshCanvas[m];const e=document.createElement("canvas");e.dataset.font=h.get();e.id="texturetext_"+CABLES.generateUUID();e.style.display="none";const t=document.getElementsByTagName("body")[0];t.appendChild(e);const i=e.getContext("2d");CABLES.OpTextureMeshCanvas[m]={ctx:i,canvas:e,chars:{},characters:"",fontSize:320};return CABLES.OpTextureMeshCanvas[m]}t.onDelete=function(){if(m&&CABLES.OpTextureMeshCanvas[m])CABLES.OpTextureMeshCanvas[m].canvas.remove()};const I=new CGL.Shader(A,"TextMesh",this);I.setSource(e.textmesh_vert,e.textmesh_frag);const j=new CGL.Uniform(I,"t","tex",0);const z=new CGL.Uniform(I,"t","texMul",1);const H=new CGL.Uniform(I,"t","texMulMask",2);const X=new CGL.Uniform(I,"f","scale",r);const F=t.inValueSlider("r",1),M=t.inValueSlider("g",1),y=t.inValueSlider("b",1),W=t.inValueSlider("a",1),q=new CGL.Uniform(I,"f","r",F),Y=new CGL.Uniform(I,"f","g",M),Z=new CGL.Uniform(I,"f","b",y),Q=new CGL.Uniform(I,"f","a",W);F.setUiAttribs({colorPick:true});t.setPortGroup("Display",[r,h]);t.setPortGroup("Alignment",[x,s]);t.setPortGroup("Color",[F,M,y,W]);let N=0;const P=vec3.create();let K=-1;let L=false;i.onTriggered=function(){if(d){J();d=false}const e=R();if(e.lastChange!=K){O=true;K=e.lastChange}if(C)$();if(O)J();if(S&&S.numInstances>0){A.pushBlendMode(CGL.BLEND_NORMAL,true);A.pushShader(I);A.setTexture(0,E.get().tex);const t=a.get();if(t)A.setTexture(1,t.tex);const i=u.get();if(i)A.setTexture(2,i.tex);if(p===2)vec3.set(P,0,N,0);else if(p===1)vec3.set(P,0,0,0);else if(p===0)vec3.set(P,0,N/2,0);P[1]-=b.get();A.pushModelMatrix();mat4.translate(A.mMatrix,A.mMatrix,P);mat4.scale(A.mMatrix,A.mMatrix,c);if(!L)S.render(A.getShader());A.popModelMatrix();A.setTexture(0,null);A.popShader();A.popBlendMode()}B.trigger()};T.onChange=function(){O=true};function J(){const e=String(v.get()+"");if(!E.get())return;const s=R();if(!s.geom){s.geom=new CGL.Geometry("textmesh");s.geom.vertices=[1,1,0,0,1,0,1,0,0,0,0,0];s.geom.texCoords=new Float32Array([1,1,0,1,1,0,0,0]);s.geom.verticesIndices=[0,1,2,2,1,3]}if(!S)S=new CGL.Mesh(A,s.geom);const a=e.split("\n");w.set(a.length);const o=[];const l=[];const u=[];const h=[];const c=mat4.create();let g=0;let f=0;C=false;for(let r=0;r<a.length;r++){const d=a[r];const m=d.length;let t=0;let i=0;let n=0;for(let e=0;e<m;e++){const p=d.substring(e,e+1);const _=s.chars[String(p)];if(_){n+=_.texCoordWidth/_.texCoordHeight;n+=T.get()}}n-=T.get();N=0;if(x.get()=="left")i=0;else if(x.get()=="right")i=n;else if(x.get()=="center")i=n/2;N=(r+1)*b.get();for(let e=0;e<m;e++){const p=d.substring(e,e+1);const _=s.chars[String(p)];if(!_){C=true;return}else{h.push(t/n*.99+.005,(1-r/(a.length-1))*.99+.005);l.push(_.texCoordX,1-_.texCoordY-_.texCoordHeight);u.push(_.texCoordWidth,_.texCoordHeight);mat4.identity(c);mat4.translate(c,c,[t-i,0-r*b.get(),0]);t+=_.texCoordWidth/_.texCoordHeight+T.get();f=Math.max(f,t-i);o.push(Array.prototype.slice.call(c));g++}}}const t=[].concat.apply([],o);L=false;if(t.length==0)L=true;const i=t.length/16;S.setNumInstances(i);if(S.numInstances==0){L=true;return}U.set(f*r.get());S.setAttribute("instMat",new Float32Array(t),16,{instanced:true});S.setAttribute("attrTexOffsets",new Float32Array(l),2,{instanced:true});S.setAttribute("attrTexSize",new Float32Array(u),2,{instanced:true});S.setAttribute("attrTexPos",new Float32Array(h),2,{instanced:true});O=false;if(C)$()}function D(t,i){const n=R();if(!i)n.chars={};const r=n.ctx;r.font=t+"px "+h.get();r.textAlign="left";let s=0;let a=0;const o=t*1.4;const e={fits:true};for(let e=0;e<n.characters.length;e++){const l=String(n.characters.substring(e,e+1));const u=r.measureText(l).width;if(a+u>=g){s+=o+2;a=0}if(!i){n.chars[l]={str:l,texCoordX:a/g,texCoordY:s/g,texCoordWidth:u/g,texCoordHeight:o/g};r.fillText(l,a,s+t)}a+=u+12}if(s>g-o){e.fits=false}e.spaceLeft=g-s;return e}function $(){let e=CGL.Texture.FILTER_LINEAR;if(o.get()=="nearest")e=CGL.Texture.FILTER_NEAREST;if(o.get()=="mipmap")e=CGL.Texture.FILTER_MIPMAP;const t=R();let i=String(v.get());if(i==null||i==undefined)i="";for(let e=0;e<i.length;e++){const a=i.substring(e,e+1);if(t.characters.indexOf(a)==-1){t.characters+=a;C=true}}const n=t.ctx;t.canvas.width=t.canvas.height=g;if(!t.texture)t.texture=CGL.Texture.createFromImage(A,t.canvas,{filter:e,anisotropic:parseFloat(l.get())});t.texture.setSize(g,g);n.fillStyle="transparent";n.clearRect(0,0,g,g);n.fillStyle="rgba(255,255,255,255)";let r=t.fontSize+40;let s=D(r,true);
30982while(!s.fits){r-=5;s=D(r,true)}D(r,false);n.restore();t.texture.initTexture(t.canvas,e);t.texture.unpackAlpha=true;E.setRef(t.texture);t.lastChange=CABLES.now();O=true;C=false}}};CABLES.OPS["2390f6b3-2122-412e-8c8d-5c2f574e8bd1"]={f:Ops.Gl.Meshes.TextMesh_v2,objName:"Ops.Gl.Meshes.TextMesh_v2"};Ops.Cables.FPS_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.outNumber("FPS"),n=e.outNumber("MS");const r=e.patch.cgl.fpsCounter.addEventListener("performance",s);e.onDelete=function(){e.patch.removeEventListener(r)};function s(e){i.set(e.fps);n.set(e.ms)}}};CABLES.OPS["6dbb866c-b57a-4875-9f1d-22172162eaa8"]={f:Ops.Cables.FPS_v2,objName:"Ops.Cables.FPS_v2"};Ops.String.NumberToString_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inValue("Number"),n=e.inInt("Decimal Places",4),r=e.outString("Result");let s=false;let a=1;n.onChange=o;i.onChange=l;o();l();function o(){s=n.get()<100;a=Math.pow(10,n.get());l()}function l(){if(s)r.set(String(Math.round(i.get()*a)/a));else r.set(String(i.get()||0))}}};CABLES.OPS["5c6d375a-82db-4366-8013-93f56b4061a9"]={f:Ops.String.NumberToString_v2,objName:"Ops.String.NumberToString_v2"};Ops.Graphics.Transform=class extends CABLES.Op{constructor(){super(...arguments);const i=this;const e=i.attachments={};const t=i.inTrigger("render"),n=i.inValue("posX",0),r=i.inValue("posY",0),s=i.inValue("posZ",0),a=i.inValue("scale",1),o=i.inValue("rotX",0),l=i.inValue("rotY",0),u=i.inValue("rotZ",0),h=i.outTrigger("trigger");i.setPortGroup("Rotation",[o,l,u]);i.setPortGroup("Position",[n,r,s]);i.setPortGroup("Scale",[a]);i.setUiAxisPorts(n,r,s);i.toWorkPortsNeedToBeLinked(t,h);const c=vec3.create();const g=vec3.create();const f=mat4.create();mat4.identity(f);let d=false,m=false,p=true,_=true,v=true;o.onChange=l.onChange=u.onChange=S;n.onChange=r.onChange=s.onChange=E;a.onChange=A;t.onTriggered=function(){let e=false;if(p){b();e=true}if(_){T();e=true}if(v)e=true;if(e)x();const t=i.patch.cg||i.patch.cgl;t.pushModelMatrix();mat4.multiply(t.mMatrix,t.mMatrix,f);h.trigger();t.popModelMatrix();if(CABLES.UI){if(!n.isLinked()&&!r.isLinked()&&!s.isLinked()){gui.setTransform(i.id,n.get(),r.get(),s.get());if(i.isCurrentUiOp())gui.setTransformGizmo({posX:n,posY:r,posZ:s})}}};function x(){mat4.identity(f);if(m)mat4.translate(f,f,c);if(o.get()!==0)mat4.rotateX(f,f,o.get()*CGL.DEG2RAD);if(l.get()!==0)mat4.rotateY(f,f,l.get()*CGL.DEG2RAD);if(u.get()!==0)mat4.rotateZ(f,f,u.get()*CGL.DEG2RAD);if(d)mat4.scale(f,f,g);v=false}function b(){m=false;if(n.get()!==0||r.get()!==0||s.get()!==0)m=true;vec3.set(c,n.get(),r.get(),s.get());p=false}function T(){d=true;vec3.set(g,a.get(),a.get(),a.get());_=false}function E(){p=true}function A(){_=true}function S(){v=true}x()}};CABLES.OPS["650baeb1-db2d-4781-9af6-ab4e9d4277be"]={f:Ops.Graphics.Transform,objName:"Ops.Graphics.Transform"};Ops.Gl.Shader.CustomShader_v2=class extends CABLES.Op{constructor(){super(...arguments);const _=this;const e=_.attachments={};const t=_.inTrigger("render"),i=_.inStringEditor("Fragment Code"),n=_.inStringEditor("Vertex Code"),r=_.inValueBool("Use As Material",true),s=_.outTrigger("trigger"),a=_.outObject("Shader",null,"shader"),o=_.outBool("Has Errors");const v=7;const x=_.patch.cgl;const b=[];const T=[];const E=[];_.toWorkPortsNeedToBeLinked(t);i.setUiAttribs({editorSyntax:"glsl"});n.setUiAttribs({editorSyntax:"glsl"});const A=new CGL.Shader(x,"customshader",_);A.logError=false;A.setModules(["MODULE_VERTEX_POSITION","MODULE_COLOR","MODULE_BEGIN_FRAG","MODULE_VERTEX_MODELVIEW"]);_.setPortGroup("Source Code",[i,n]);_.setPortGroup("Options",[r]);i.set(CGL.Shader.getDefaultFragmentShader());n.set(CGL.Shader.getDefaultVertexShader());i.onChange=n.onChange=function(){if(i.isLinked()&&!i.get())return;u=true};t.onTriggered=c;let l=0;let u=true;_.onLoadedValueSet=h;function h(i){p();if(!i)return;for(let t=0;t<b.length;t++)for(let e=0;e<i.portsIn.length;e++)if(b[t]&&b[t].name==i.portsIn[e].name){b[t].set(i.portsIn[e].value);b[t].deSerializeSettings(i.portsIn[e])}}_.init=function(){p()};function c(){F();if(u)p();if(r.get())x.pushShader(A);g();s.trigger();A.popTextures();if(r.get())x.popShader()}function g(){for(let e=0;e<T.length;e++)if(T[e]&&T[e].get()&&T[e].get().tex)A.pushTexture(T[e].uniform,T[e].get().tex);else A.pushTexture(T[e],CGL.Texture.getEmptyTexture(x))}function f(){for(let e=0;e<T.length;e++)if(T[e]&&T[e].get()&&T[e].get().tex)x.setTexture(0+e+v,T[e].get().tex)}function S(t){for(let e=0;e<b.length;e++)if(b[e]&&b[e].name==t)return true;for(let e=0;e<T.length;e++)if(T[e]&&T[e].name==t)return true;return false}const d=mat4.create();const O=["modelMatrix","viewMatrix","normalMatrix","mvMatrix","projMatrix","inverseViewMatrix","camPos"];let C=0;const R=[];function m(e){const t=e.split("\n");const r=[];for(let e=0;e<t.length;e++){const i=t[e].split(";");for(let e=0;e<i.length;e++){let n=i[e].split(" ");for(let e=0;e<n.length;e++)n[e]=(n[e]+"").trim();if(n[0]==="UNI"||n[0]==="uniform"){let t=n[2];if(n.length>4)for(let e=3;e<n.length;e++)t+=n[e];n=n.filter(function(e){return e!==""});const s=n[1];let i=[];if(t){i=[t];if(t.indexOf(",")>-1)i=t.split(",")}for(let e=0;e<i.length;e++){if(O.indexOf(i[e])>-1)continue;const a=i[e].trim().replace(/\[\d+\]$/,"");if(s==="float"){R.push(a);if(!S(a)){const o=i[e].trim().match(/\[\d+\]$/);if(o){const l=parseInt(o[0].trim().slice(1,-1));const u=_.inArray(a,[]);u.uniform=new CGL.Uniform(A,"f[]",a,new Float32Array(l));b.push(u);r.push(u);const h={name:a,num:l,port:u,uni:u.uniform,changed:false};u.onChange=function(){this.changed=true}.bind(h);E.push(h)}else{const u=_.inFloat(a,0);u.uniform=new CGL.Uniform(A,"f",a,u);b.push(u);r.push(u)}}}else if(s==="int"){R.push(a);if(!S(a)){const u=_.inInt(a,0);u.uniform=new CGL.Uniform(A,"i",a,u);b.push(u);r.push(u)}}else if(s==="bool"){R.push(a);if(!S(a)){const u=_.inBool(a,false);u.uniform=new CGL.Uniform(A,"b",a,u);b.push(u);r.push(u)}}else if(s==="mat4"){R.push(a);if(!S(a)){const u=_.inArray(a,0);u.uniform=new CGL.Uniform(A,"m4",a,u);b.push(u);r.push(u);const h={name:a,num:16,port:u,uni:u.uniform,changed:false};u.onChange=function(){this.changed=true}.bind(h);E.push(h)}}else if(s==="sampler2D"||s==="samplerCube"){R.push(a);if(!S(a)){const c=_.inObject(a);let e="t";if(s==="samplerCube")e="tc";c.uniform=new CGL.Uniform(A,e,a,v+T.length);T.push(c);
30982r.push(c);c.set(CGL.Texture.getTempTexture(x));c.on("change",(e,t)=>{if(!e)t.set(CGL.Texture.getTempTexture(x))});C++}}else if(s==="vec3"||s==="vec2"||s==="vec4"){let e=2;if(s==="vec4")e=4;if(s==="vec3")e=3;R.push(a+" X");R.push(a+" Y");if(e>2)R.push(a+" Z");if(e>3)R.push(a+" W");if(!S(a+" X")){const g=[];const h={name:a,num:e,changed:false};E.push(h);I(h);const f=_.inFloat(a+" X",0);f.onChange=function(){this.changed=true}.bind(h);b.push(f);g.push(f);h.x=f;const d=_.inFloat(a+" Y",0);d.onChange=function(){this.changed=true}.bind(h);b.push(d);g.push(d);h.y=d;if(e>2){const m=_.inFloat(a+" Z",0);m.onChange=function(){this.changed=true}.bind(h);b.push(m);g.push(m);h.z=m}if(e>3){const p=_.inFloat(a+" W",0);p.onChange=function(){this.changed=true}.bind(h);b.push(p);g.push(p);h.w=p}_.setPortGroup(a,g)}}}}}}_.setPortGroup("uniforms",r)}function p(){if(!A)return;let e=false;l++;if(l>2)e=true;A.setSource(n.get(),i.get(),e);if(x.glVersion==1){x.enableExtension("OES_standard_derivatives");A.enableExtension("GL_OES_standard_derivatives")}C=0;R.length=0;m(n.get());m(i.get());for(let t=0;t<T.length;t++)for(let e=0;e<R.length;e++)if(T[t]&&R.indexOf(T[t].name)==-1){T[t].remove();T[t]=null}for(let t=0;t<b.length;t++)for(let e=0;e<R.length;e++)if(b[t]&&R.indexOf(b[t].name)==-1){b[t].remove();b[t]=null}for(let e=0;e<E.length;e++){I(E[e]);E[e].changed=true}for(let e=0;e<b.length;e++)if(b[e]&&b[e].uniform)b[e].uniform.needsUpdate=true;A.compile();_.refreshParams();a.setRef(A);u=false;if(A.hasErrors())_.setUiError("compile","Shader has errors",2,{button:"show",buttonCb:()=>{CABLES.UI.showShaderError(A)}});else _.setUiError("compile",null);o.set(A.hasErrors())}function I(e){if(e.num==2)e.uni=new CGL.Uniform(A,"2f",e.name,[0,0]);else if(e.num==3)e.uni=new CGL.Uniform(A,"3f",e.name,[0,0,0]);else if(e.num==4)e.uni=new CGL.Uniform(A,"4f",e.name,[0,0,0,0])}function F(){for(let e=0;e<E.length;e++){const t=E[e];if(t.changed){if(t.num===2)t.uni.setValue([t.x.get(),t.y.get()]);else if(t.num===3)t.uni.setValue([t.x.get(),t.y.get(),t.z.get()]);else if(t.num===4)t.uni.setValue([t.x.get(),t.y.get(),t.z.get(),t.w.get()]);else if(t.num>4){t.uni.setValue(t.port.get())}t.changed=false}}}}};CABLES.OPS["a165fc89-a35b-4d39-8930-7345b098bd9d"]={f:Ops.Gl.Shader.CustomShader_v2,objName:"Ops.Gl.Shader.CustomShader_v2"};Ops.Gl.TextureArray=class extends CABLES.Op{constructor(){super(...arguments);const i=this;const e=i.attachments={};const n=i.outArray("Array"),r=i.outNumber("Count");n.ignoreValueSerialize=true;const s=15;let a=[];let o=[];function l(){let e=0;let t=0;for(e=0;e<a.length;e++)if(a[e].isLinked())t++;o.length=t;t=0;for(e=0;e<a.length;e++){if(a[e].isLinked()){o[t]=a[e].get();t++}}n.set(null);n.set(o);r.set(t)}for(let t=0;t<s;t++){let e=i.inTexture("Texture "+t);e.onLinkChanged=l;e.onChange=l;a.push(e)}}};CABLES.OPS["fac012e2-43c8-4e21-85ac-189fe85d5723"]={f:Ops.Gl.TextureArray,objName:"Ops.Gl.TextureArray"};Ops.Array.ArrayGetTexture=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inArray("array"),n=e.inValueInt("index"),r=e.outTexture("value");let s=null;i.ignoreValueSerialize=true;r.ignoreValueSerialize=true;n.onChange=i.onChange=o;e.toWorkPortsNeedToBeLinked(i,r);const a=CGL.Texture.getEmptyTexture(e.patch.cgl);function o(){const e=i.get();let t=n.get();if(t<0||!e||t>=e.length){r.setRef(a);return}if(e[t]){r.setRef(e[t]||a);s=e[t]}else r.setRef(a)}}};CABLES.OPS["afea522b-ab72-4574-b721-5d37f5abaf77"]={f:Ops.Array.ArrayGetTexture,objName:"Ops.Array.ArrayGetTexture"};Ops.Html.Attributes.ElementSetAttribute=class extends CABLES.Op{constructor(){super(...arguments);const t=this;const e=t.attachments={};const i=t.inObject("Element"),n=t.inString("Attribute"),r=t.inString("Value"),s=t.inBool("Active",true),a=t.outObject("HTML Element");t.setPortGroup("Element",[i]);t.setPortGroup("Attributes",[n,r]);n.onChange=h;r.onChange=c;let o=null;let l="";i.onChange=a.onLinkChanged=i.onLinkChanged=u;s.onChange=()=>{if(!s.get())u();else c()};function u(){if(o)o.removeAttribute(n.get());o=null;c()}function h(){c();t.setUiAttrib({extendTitle:n.get()+""})}function c(){if(!s.get())return;if(n.get()=="")return;if(i.get())o=i.get();if(o&&o.setAttribute){t.setUiError("errd",null);if(n.get()!=l){o.removeAttribute(l);l=n.get()}const e=r.get();try{o.setAttribute(n.get(),e)}catch(e){if(e.message)t.setUiError("errd",e.message)}}a.setRef(i.get())}}};CABLES.OPS["d5864a5d-bb65-417a-99c1-2a3b340fd9bb"]={f:Ops.Html.Attributes.ElementSetAttribute,objName:"Ops.Html.Attributes.ElementSetAttribute"};Ops.Html.ElementDataSet=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inObject("HTML Element",null,"element");const n=e.outObject("Dataset");i.onChange=r;function r(){let e=i.get();let t={};if(e)t={...e.dataset};n.setRef(t)}}};CABLES.OPS["898adc47-b9e5-4ce4-ad21-644984b44503"]={f:Ops.Html.ElementDataSet,objName:"Ops.Html.ElementDataSet"};Ops.Json.ObjectGetNumber_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inObject("Data"),n=e.inString("Key"),r=e.outNumber("Result"),s=e.outBoolNum("Found");e.toWorkPortsNeedsString(n);r.ignoreValueSerialize=true;i.ignoreValueSerialize=true;e.toWorkPortsNeedToBeLinked(i);e.setUiAttrib({extendTitlePort:n.name});n.setUiAttribs({stringTrim:true});n.onChange=i.onChange=a;function a(){const e=i.get();
30982if(e){const t=e[n.get()];r.set(parseFloat(t));if(t===undefined)s.set(0);else s.set(1)}else{r.set(0);s.set(0)}}}};CABLES.OPS["a7335e79-046e-40da-9e9c-db779b0a5e53"]={f:Ops.Json.ObjectGetNumber_v2,objName:"Ops.Json.ObjectGetNumber_v2"};Ops.Boolean.OrNumber_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inFloat("Number",0),n=e.inFloat("Number 2",0),r=e.inFloat("Number 3",0),s=e.inFloat("Number 4",0),a=e.inFloat("Number 5",0),o=e.inFloat("Number 6",0),l=e.inFloat("Number 7",0),u=e.inFloat("Number 8",0),h=e.outNumber("Result");i.onChange=n.onChange=r.onChange=s.onChange=a.onChange=o.onChange=l.onChange=u.onChange=c;c();function c(){h.set(i.get()||n.get()||r.get()||s.get()||a.get()||o.get()||l.get()||u.get())}}};CABLES.OPS["1f634c57-fb61-485a-8d78-9b8ef2319b2e"]={f:Ops.Boolean.OrNumber_v2,objName:"Ops.Boolean.OrNumber_v2"};Ops.Json.SequenceObjects_v2=class extends CABLES.Op{constructor(){super(...arguments);const t=this;const e=t.attachments={};const i=[];const n=[];for(let e=0;e<16;e++){const r=t.inObject("Number "+e,0);const s=t.outObject("Output "+e);r.changeAlways=true;i.push(s);n.push(r)}for(let e=0;e<n.length;e++){const r=n[e];r.onChange=function(){for(let e=0;e<i.length;e++)i[e].set(r.get())}}}};CABLES.OPS["76c7d6a7-64c9-4a95-bc92-c68213601d28"]={f:Ops.Json.SequenceObjects_v2,objName:"Ops.Json.SequenceObjects_v2"};Ops.Gl.Textures.ColorTexture=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inValueSlider("r",Math.random()),n=e.inValueSlider("g",Math.random()),r=e.inValueSlider("b",Math.random()),s=e.inValueSlider("a",1),a=e.outTexture("texture_out");i.setUiAttribs({colorPick:true});const o=e.patch.cgl;let l=null;let u=false;i.onChange=n.onChange=r.onChange=s.onChange=()=>{o.addNextFrameOnceCallback(h)};o.addNextFrameOnceCallback(h);function h(){const e=u||i.get()<0||i.get()>1||n.get()<0||n.get()>1||r.get()<0||r.get()>1;if(!l||u!=e){if(l)l.dispose();if(o.glVersion==1)l=new CGL.Framebuffer(o,8,8,{name:"colorTexture"});else l=new CGL.Framebuffer2(o,8,8,{name:"colorTexture",depth:false,isFloatingPointTexture:e});l.setFilter(CGL.Texture.FILTER_LINEAR);u=e}l.renderStart();o.gl.clearColor(i.get(),n.get(),r.get(),s.get());o.gl.clear(o.gl.COLOR_BUFFER_BIT);l.renderEnd();a.setRef(l.getTextureColor())}e.onDelete=()=>{if(l)l.dispose()}}};CABLES.OPS["59b94270-0364-4c0f-a9fc-ba2561696a23"]={f:Ops.Gl.Textures.ColorTexture,objName:"Ops.Gl.Textures.ColorTexture"};Ops.Html.DocumentBody=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};e.outObject("Body",document.body,"element")}};CABLES.OPS["bf95148a-832f-4c89-ad31-5acff0d1f214"]={f:Ops.Html.DocumentBody,objName:"Ops.Html.DocumentBody"};Ops.Boolean.BoolToNumber_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inBool("Use Value 1",false),n=e.inFloat("Value 0",0),r=e.inFloat("Value 1",1),s=e.outNumber("Out Value",0);n.onChange=r.onChange=i.onChange=a;function a(){const e=i.get();if(e){s.set(r.get())}else{s.set(n.get())}}}};CABLES.OPS["400eea7d-5a68-4dda-a94d-2bb2ee7c2331"]={f:Ops.Boolean.BoolToNumber_v2,objName:"Ops.Boolean.BoolToNumber_v2"};Ops.Html.ElementHasClass=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inObject("Element",null,"element"),n=e.inString("Classname",""),r=e.inTrigger("Update"),s=e.outBoolNum("Has Class");r.onTriggered=i.onChange=n.onChange=()=>{const e=i.get();if(!e||!e.classList){s.set(false);return}s.set(e.classList.contains(n.get()))}}};CABLES.OPS["65bd64bc-ab1b-4d04-8f85-5eccdf7198b4"]={f:Ops.Html.ElementHasClass,objName:"Ops.Html.ElementHasClass"};Ops.Trigger.Interval=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inValue("interval"),n=e.outTrigger("trigger"),r=e.inValueBool("Active",true);r.onChange=function(){clearTimeout(s);s=-1;if(!r.get()){}else a()};i.set(1e3);let s=-1;function a(){if(!r.get())return;if(s!=-1)return;s=setTimeout(function(){s=-1;n.trigger();a()},i.get())}i.onChange=a;a()}};CABLES.OPS["3e9bae10-38af-4e36-9fcc-35faeeaf57f8"]={f:Ops.Trigger.Interval,objName:"Ops.Trigger.Interval"};Ops.Dev.Html.GlCopyToCanvas=class extends CABLES.Op{constructor(){super(...arguments);const s=this;const e=s.attachments={};const t=s.inTrigger("Render"),a=s.inObject("Canvas",null,"element"),o=s.inBool("Smooth",true),l=s.outTrigger("Next");t.onTriggered=()=>
30982{if(a.isLinked())try{const i=a.get();const n=i.getContext("2d");let e=0;let t=0;const r=s.patch.cgl.canvas;if(r){n.imageSmoothingEnabled=!!o.get();n.imageSmoothingQuality="high";n.drawImage(r,0,0,r.width,r.height,0,0,i.width,i.height);n.imageSmoothingEnabled=true}}catch(e){console.log(e)}l.trigger()}}};CABLES.OPS["0a70d9aa-6e90-4ea9-8ed3-1f197598cb0d"]={f:Ops.Dev.Html.GlCopyToCanvas,objName:"Ops.Dev.Html.GlCopyToCanvas"};Ops.Trigger.TriggerCounter=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inTriggerButton("exe"),n=e.inTriggerButton("reset"),r=e.outTrigger("trigger"),s=e.outNumber("timesTriggered");e.toWorkPortsNeedToBeLinked(i);e.setUiAttrib({extendTitle:0});let a=0;n.onTriggered=e.onLoaded=o;i.onTriggered=function(){a++;s.set(a);e.setUiAttrib({extendTitle:a});r.trigger()};function o(){a=0;e.setUiAttrib({extendTitle:a});s.set(a)}}};CABLES.OPS["e640619f-235c-4543-bbf8-b358e0283180"]={f:Ops.Trigger.TriggerCounter,objName:"Ops.Trigger.TriggerCounter"};Ops.Gl.ElementInBrowserViewport=class extends CABLES.Op{constructor(){super(...arguments);const i=this;const e=i.attachments={};const t=i.inTriggerButton("Update"),n=i.inObject("Element",null,"element"),r=i.outTrigger("Next"),s=i.outBoolNum("Fully Visible"),a=i.outBoolNum("Partly Visible");t.onTriggered=h;function o(e,t){return t>=0&&e>=0&&t<=(window.innerHeight||document.documentElement.clientHeight)&&e<=(window.innerWidth||document.documentElement.clientWidth)}function l(e){if(!e.getBoundingClientRect)return;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function u(e){if(!e.getBoundingClientRect)return;let t=e.getBoundingClientRect();return t.top<0&&t.bottom>0||t.left<0&&t.right>0||o(t.left,t.top)||o(t.left,t.bottom)||o(t.right,t.top)||o(t.right,t.bottom)}function h(){let e=l(n.get()||i.patch.cgl.canvas);let t=u(n.get()||i.patch.cgl.canvas);a.set(t);s.set(e);r.trigger()}}};CABLES.OPS["2721f83b-246c-46fa-9ad9-d8c829adb94d"]={f:Ops.Gl.ElementInBrowserViewport,objName:"Ops.Gl.ElementInBrowserViewport"};Ops.Trigger.TriggerLimiter=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inTrigger("In Trigger"),n=e.inValue("Milliseconds",300),r=e.outTrigger("Out Trigger"),s=e.outNumber("Progress");let a=0;i.onTriggered=function(){const e=CABLES.now();let t=(e-a)/n.get();if(t>1)t=1;if(t<0)t=0;s.set(t);if(e>=a+n.get()){a=e;r.trigger()}}}};CABLES.OPS["47641d85-9f81-4287-8aa2-35753b0727e0"]={f:Ops.Trigger.TriggerLimiter,objName:"Ops.Trigger.TriggerLimiter"};Ops.Ui.VizTexture=class extends CABLES.Op{constructor(){super(...arguments);const B=this;const i=B.attachments={viztex_frag:"IN vec2 texCoord;\nUNI sampler2D tex;\nUNI samplerCube cubeMap;\nUNI float width;\nUNI float height;\nUNI float type;\nUNI float time;\n\nfloat LinearizeDepth(float d,float zNear,float zFar)\n{\n float z_n = 2.0 * d - 1.0;\n return 2.0 * zNear / (zFar + zNear - z_n * (zFar - zNear));\n}\n\nvoid main()\n{\n vec4 col=vec4(vec3(0.),0.0);\n\n vec4 colTex=texture(tex,texCoord);\n\n\n\n if(type==1.0)\n {\n vec4 depth=vec4(0.);\n vec2 localST=texCoord;\n localST.y = 1. - localST.y;\n\n localST.t = mod(localST.t*3.,1.);\n localST.s = mod(localST.s*4.,1.);\n\n #ifdef WEBGL2\n #define texCube texture\n #endif\n #ifdef WEBGL1\n #define texCube textureCube\n #endif\n\n// //Due to the way my depth-cubeMap is rendered, objects to the -x,y,z side is projected to the positive x,y,z side\n// //Inside where top/bottom is to be drawn?\n if (texCoord.s*4.> 1. && texCoord.s*4.<2.)\n {\n //Bottom (-y) quad\n if (texCoord.t*3. < 1.)\n {\n vec3 dir=vec3(localST.s*2.-1.,-1.,-localST.t*2.+1.);//Due to the (arbitrary) way I choose as up in my depth-viewmatrix, i her emultiply the latter coordinate with -1\n depth = texCube(cubeMap, dir);\n }\n //top (+y) quad\n else if (texCoord.t*3. > 2.)\n {\n vec3 dir=vec3(localST.s*2.-1.,1.,localST.t*2.-1.);//Get lower y texture, which is projected to the +y part of my cubeMap\n depth = texCube(cubeMap, dir);\n }\n else//Front (-z) quad\n {\n vec3 dir=vec3(localST.s*2.-1.,-localST.t*2.+1.,1.);\n depth = texCube(cubeMap, dir);\n }\n }\n// //If not, only these ranges should be drawn\n else if (texCoord.t*3. > 1. && texCoord.t*3. < 2.)\n {\n if (texCoord.x*4. < 1.)//left (-x) quad\n {\n vec3 dir=vec3(-1.,-localST.t*2.+1.,localST.s*2.-1.);\n depth = texCube(cubeMap, dir);\n }\n else if (texCoord.x*4. < 3.)//right (+x) quad (front was done above)\n {\n vec3 dir=vec3(1,-localST.t*2.+1.,-localST.s*2.+1.);\n depth = texCube(cubeMap, dir);\n }\n else //back (+z) quad\n {\n vec3 dir=vec3(-localST.s*2.+1.,-localST.t*2.+1.,-1.);\n depth = texCube(cubeMap, dir);\n }\n }\n // colTex = vec4(vec3(depth),1.);\n colTex = vec4(depth);\n }\n\n if(type==2.0)\n {\n float near = 0.1;\n float far = 50.;\n float depth = LinearizeDepth(colTex.r, near, far);\n colTex.rgb = vec3(depth);\n }\n\n\n\n\n #ifdef ANIM_RANGE\n\n if(colTex.r>1.0 || colTex.r<0.0)\n colTex.r=mod(colTex.r,1.0)*0.5+(sin(colTex.r+mod(colTex.r*3.0,1.0)+time*5.0)*0.5+0.5)*0.5;\n if(colTex.g>1.0 || colTex.g<0.0)\n colTex.g=mod(colTex.g,1.0)*0.5+(sin(colTex.g+mod(colTex.g*3.0,1.0)+time*5.0)*0.5+0.5)*0.5;\n if(colTex.b>1.0 || colTex.b<0.0)\n colTex.b=mod(colTex.b,1.0)*0.5+(sin(colTex.b+mod(colTex.b*3.0,1.0)+time*5.0)*0.5+0.5)*0.5;\n\n #endif\n\n\n // #ifdef ANIM_RANGE\n // if(colTex.r>1.0 || colTex.r<0.0)\n // {\n // float r=mod( time+colTex.r,1.0)*0.5+0.5;\n // colTex.r=r;\n // }\n // if(colTex.g>1.0 || colTex.g<0.0)\n // {\n // float r=mod( time+colTex.g,1.0)*0.5+0.5;\n // colTex.g=r;\n // }\n // if(colTex.b>1.0 || colTex.b<0.0)\n // {\n // float r=mod( time+colTex.b,1.0)*0.5+0.5;\n // colTex.b=r;\n // }\n // #endif\n\n #ifdef MOD_RANGE\n colTex.r=mod(colTex.r,1.0001);\n colTex.g=mod(colTex.g,1.0001);\n colTex.b=mod(colTex.b,1.0001);\n\n #endif\n\n #ifdef ALPHA_ONE\n colTex.a=1.0;\n #endif\n #ifdef ALPHA_INV\n colTex.a=1.0-colTex.a;\n #endif\n\n outColor = mix(col,colTex,colTex.a);\n}\n\n",viztex_vert:"IN vec3 vPosition;\nIN vec2 attrTexCoord;\nOUT vec2 texCoord;\nUNI mat4 projMatrix;\nUNI mat4 modelMatrix;\nUNI mat4 viewMatrix;\n\nvoid main()\n{\n texCoord=vec2(attrTexCoord.x,1.0-attrTexCoord.y);\n vec4 pos = vec4( vPosition, 1. );\n mat4 mvMatrix=viewMatrix * modelMatrix;\n gl_Position = projMatrix * mvMatrix * pos;\n}"};
30982const w=B.inTexture("Texture In"),U=B.inBool("Show Info",false),e=B.inSwitch("Visualize outside 0-1",["Off","Anim","Modulo"],"Anim"),t=B.inSwitch("Alpha",["A","1","1-A"],"A"),V=B.inBool("Show Color",false),k=B.inFloatSlider("X",.5),G=B.inFloatSlider("Y",.5),n=B.outTexture("Texture Out"),j=B.outString("Info");B.setUiAttrib({height:150,resizable:true});const z=new CABLES.Timer;let r=null;let H=null;let X=null;let W="";let s=true;t.onChange=e.onChange=o;V.onChange=a;a();if(CABLES.UI){z.play()}function a(){k.setUiAttribs({greyout:!V.get()});G.setUiAttribs({greyout:!V.get()})}w.onChange=()=>{const e=w.get();n.setRef(e);let t="";if(w.get()&&w.isLinked())t=w.links[0].getOtherPort(w).name;B.setUiAttrib({extendTitle:t})};function o(){if(!r)return;r.toggleDefine("MOD_RANGE",e.get()=="Modulo");r.toggleDefine("ANIM_RANGE",e.get()=="Anim");r.toggleDefine("ALPHA_INV",t.get()=="1-A");r.toggleDefine("ALPHA_ONE",t.get()=="1")}B.renderVizLayerGl=(h,c)=>{if(!w.isLinked())return;if(!c.useGl)return;const g=w;const f=5;const d=f+1;const e=gui.uiProfiler.start("previewlayer texture");const m=g.op.patch.cgl;if(!this._emptyCubemap)this._emptyCubemap=CGL.Texture.getEmptyCubemapTexture(m);g.op.patch.cgl.profileData.profileTexPreviews++;const p=g.get()||CGL.Texture.getEmptyTexture(m);if(!this._mesh){const t=new CGL.Geometry("vizTexture rect");t.vertices=[1,1,0,-1,1,0,1,-1,0,-1,-1,0];t.texCoords=[1,1,0,1,1,0,0,0];t.verticesIndices=[0,1,2,3,1,2];this._mesh=new CGL.Mesh(m,t)}if(!this._shader){this._shader=new CGL.Shader(m,"glpreviewtex");this._shader.setModules(["MODULE_VERTEX_POSITION","MODULE_COLOR","MODULE_BEGIN_FRAG"]);this._shader.setSource(i.viztex_vert,i.viztex_frag);this._shaderTexUniform=new CGL.Uniform(this._shader,"t","tex",f);this._shaderTexCubemapUniform=new CGL.Uniform(this._shader,"tc","cubeMap",d);r=this._shader;o();this._shaderTexUniformW=new CGL.Uniform(this._shader,"f","width",p.width);this._shaderTexUniformH=new CGL.Uniform(this._shader,"f","height",p.height);this._shaderTypeUniform=new CGL.Uniform(this._shader,"f","type",0);this._shaderTimeUniform=new CGL.Uniform(this._shader,"f","time",0)}m.pushPMatrix();const _=[p.width,p.height];const v=g.op.patch.cgl.canvasWidth>_[0]&&g.op.patch.cgl.canvasHeight>_[1];if(v){mat4.ortho(m.pMatrix,0,g.op.patch.cgl.canvasWidth,g.op.patch.cgl.canvasHeight,0,.001,11)}else mat4.ortho(m.pMatrix,-1,1,1,-1,.001,11);const x=m.getTexture(f);const b=m.getTexture(d);let T=0;if(p){if(p.cubemap)T=1;if(p.textureType==CGL.Texture.TYPE_DEPTH)T=2;if(T==0||T==2){m.setTexture(f,p.tex);m.setTexture(d,this._emptyCubemap.cubemap,m.gl.TEXTURE_CUBE_MAP)}else if(T==1){m.setTexture(d,p.cubemap,m.gl.TEXTURE_CUBE_MAP)}z.update();this._shaderTimeUniform.setValue(z.get());this._shaderTypeUniform.setValue(T);let t=[g.op.patch.cgl.canvasWidth,g.op.patch.cgl.canvasHeight];m.gl.clearColor(0,0,0,0);m.gl.clear(m.gl.COLOR_BUFFER_BIT|m.gl.DEPTH_BUFFER_BIT);m.pushModelMatrix();if(v){t=_;mat4.translate(m.mMatrix,m.mMatrix,[_[0]/2,_[1]/2,0]);mat4.scale(m.mMatrix,m.mMatrix,[_[0]/2,_[1]/2,0])}this._mesh.render(this._shader);m.popModelMatrix();if(T==0)m.setTexture(f,x);if(T==1)m.setTexture(d,b);m.popPMatrix();m.resetViewPort();const E=[c.width,c.height];const A=false;if(p.width>p.height)E[1]=c.width*_[1]/_[0];else{E[1]=c.width*(_[1]/_[0]);if(E[1]>c.height){const R=c.height/E[1];E[0]*=R;E[1]*=R}}const S=E[0]>_[0]&&E[1]>_[1];h.imageSmoothingEnabled=true;h.fillStyle="#ffffff";h.fillRect(c.x,c.y-10,10,10);h.fillStyle="#000000";h.fillRect(c.x,c.y-10,5,5);h.fillRect(c.x+5,c.y-10+5,5,5);let e=c.height;let i=10*c.width/e;let n=e/10;let r=c.width/i;for(let t=0;t<i;t++)for(let e=0;e<10;e++){if((t+e)%2==0)h.fillStyle="#333333";else h.fillStyle="#393939";h.fillRect(c.x+r*t,c.y+n*e,r,n)}h.fillStyle="#222";const O=(c.width-E[0])/2;const C=(e-E[1])/2;let s=c.x+(c.width-E[0])/2;let a=c.y+(e-E[1])/2;let o=E[0];let l=E[1];if(e-E[1]<0){s=c.x+(c.width-E[0]*e/E[1])/2;a=c.y;o=E[0]*e/E[1];l=e}h.fillRect(c.x,c.y,s-c.x,e);h.fillRect(c.x+o+s-c.x,c.y,o,e);h.fillRect(c.x,c.y,c.width,C);h.fillRect(c.x,c.y+E[1]+C,c.width,C);if(m.canvas&&m.canvasWidth>0&&m.canvasHeight>0&&m.canvas.width>0&&m.canvas.height>0){try{const I=o/t[0]>3||l/t[1]>3;const F=o/t[0]>10||l/t[1]>10;if(_[1]==1){h.imageSmoothingEnabled=false;h.drawImage(m.canvas,0,0,t[0],t[1],c.x,c.y,c.width,e);h.imageSmoothingEnabled=true}else if(_[0]==1){h.imageSmoothingEnabled=false;h.drawImage(m.canvas,0,0,t[0],t[1],c.x,c.y,c.width,e);h.imageSmoothingEnabled=true}else if(E[0]!=0&&E[1]!=0&&c.width!=0&&e!=0&&o!=0&&l!=0){h.imageSmoothingEnabled=!I;h.drawImage(m.canvas,0,0,t[0],t[1],s,a,o,l)}if(F){const M=o/t[0];const y=l/t[1];h.imageSmoothingEnabled=true;h.lineWidth=1;h.globalAlpha=.5;h.beginPath();for(let e=0;e<=t[0];e++){h.moveTo(s+e*M,a);h.lineTo(s+e*M,a+l)}for(let e=0;e<=t[1];e++){h.moveTo(s,a+e*y);h.lineTo(s+o,a+e*y)}h.strokeStyle="#555";h.stroke();h.globalAlpha=1}}catch(e){console.error("canvas drawimage exception...",e)}}let u="";if(U.get()&&g.get()&&g.get().getInfoOneLine)u+=g.get().getInfoOneLine()+"\n";j.set(u);
30982if(V.get()){u+=W+"\n";const N=s+o*k.get();const P=a+l*G.get();for(let e=0;e<2;e++){if(e==0)h.fillStyle="#000";else h.fillStyle="#fff";h.fillRect(N-1+e,P-10+e,1,20);h.fillRect(N-10+e,P-1+e,20,1)}}if(U.get()||V.get()){B.setUiAttrib({comment:u})}if(V.get()){const L=m.gl;const D=w.get();if(!D){W="";return}if(!H)H=L.createFramebuffer();if(!X)X=new CGL.PixelReader;L.bindFramebuffer(L.FRAMEBUFFER,H);L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_2D,D.tex,0);L.bindFramebuffer(L.FRAMEBUFFER,null);X.read(m,H,D.pixelFormat,k.get()*D.width,D.height-G.get()*D.height,1,1,e=>{if(!CGL.Texture.isPixelFormatFloat(D.pixelFormat)){W="Pixel Float: "+Math.floor(e[0]/255*100)/100;if(!isNaN(e[1]))W+=", "+Math.floor(e[1]/255*100)/100;if(!isNaN(e[2]))W+=", "+Math.floor(e[2]/255*100)/100;if(!isNaN(e[3]))W+=", "+Math.floor(e[3]/255*100)/100;W+="\n";if(D.pixelFormat.indexOf("ubyte")>0){W+="Pixel UByte: ";W+=Math.round(e[0]);if(!isNaN(e[1]))W+=", "+Math.round(e[1]);if(!isNaN(e[2]))W+=", "+Math.round(e[2]);if(!isNaN(e[3]))W+=", "+Math.round(e[3]);W+="\n"}}else{W="Pixel Float: "+Math.round(e[0]*100)/100+", "+Math.round(e[1]*100)/100+", "+Math.round(e[2]*100)/100+", "+Math.round(e[3]*100)/100;W+="\n"}})}}m.gl.clearColor(0,0,0,0);m.gl.clear(m.gl.COLOR_BUFFER_BIT|m.gl.DEPTH_BUFFER_BIT);e.finish()}}};CABLES.OPS["4ea2d7b0-ca74-45db-962b-4d1965ac20c0"]={f:Ops.Ui.VizTexture,objName:"Ops.Ui.VizTexture"};Ops.Html.Event.ElementsArrayEventHandler=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inArray("Elements",null,"element");const n=e.inString("Event Name","click");const r=e.inValueBool("Use Capture",false);const s=e.inValueBool("Prevent Default",true);const a=e.inValueBool("Stop Propagation",true);const o=e.outTrigger("Event Trigger");const l=e.outNumber("Index",-1);const u=e.outObject("Event Object");const h=e.outObject("Event Element",null,"element");e.toWorkPortsNeedsString(n);e.toWorkPortsNeedToBeLinked(i);e.onDelete=p;const c="op"+e.id+"listenerIndex";let g=[];let f="";const d=e=>{const t=e.currentTarget;l.set(-1);if(t.dataset.hasOwnProperty(c))l.set(parseInt(t.dataset[c],10));u.setRef(e);h.setRef(t);o.trigger()};n.onChange=r.onChange=s.onChange=a.onChange=i.onChange=()=>{if(!n.get())return;p(f);g=i.get()||[];f=n.get();m(f)};function m(i){g.forEach((e,t)=>{e.dataset[c]=t;e.addEventListener(i,d,r.get())})}function p(t){g.forEach(e=>{e.removeEventListener(t,d,r.get());e.removeEventListener(t,d,!r.get())})}}};CABLES.OPS["a8d569d1-5238-4c3e-be3c-4507df51740f"]={f:Ops.Html.Event.ElementsArrayEventHandler,objName:"Ops.Html.Event.ElementsArrayEventHandler"};Ops.Cables.LoadingStatus_v2=class extends CABLES.Op{constructor(){super(...arguments);const n=this;const e=n.attachments={};const t=n.inTrigger("exe"),r=n.inBool("Play Timeline",true),i=n.outTrigger("Next"),s=n.outBoolNum("Finished Initial Loading",false),a=n.outBoolNum("Loading"),o=n.outNumber("Progress"),l=n.outArray("Jobs"),u=n.outTrigger("Trigger Loading Finished ");n.toWorkPortsNeedToBeLinked(t);const h=n.patch;let c=false;const g=[];let f=true;let d=0;document.body.classList.add("cables-loading");let m=h.loading.start("loadingStatusInit","loadingStatusInit",n);n.patch.loading.on("finishedTask",p.bind(this));n.patch.loading.on("startTask",p.bind(this));function p(){const e=n.patch.loading.getListJobs();o.set(h.loading.getProgress());let t=e.length===0;const i=!t;if(i){l.set(n.patch.loading.getListJobs())}if(i){if(f){n.patch.timer.setTime(0);if(r.get()){n.patch.timer.play()}else{n.patch.timer.pause()}}f=false;document.body.classList.remove("cables-loading");document.body.classList.add("cables-loaded")}else{c=true;l.set(n.patch.loading.getListJobs());if(h.loading.getProgress()<1){n.patch.timer.setTime(0);n.patch.timer.pause()}}s.set(c);if(a.get()&&t)u.trigger();a.set(i);n.setUiAttribs({loading:i})}t.onTriggered=()=>{p();i.trigger();if(m){h.loading.finished(m);m=null}}}};CABLES.OPS["e62f7f4c-7436-437e-8451-6bc3c28545f7"]={f:Ops.Cables.LoadingStatus_v2,objName:"Ops.Cables.LoadingStatus_v2"};Ops.Trigger.TriggerOnChangeObject_v2=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inObject("Object"),n=e.outTrigger("Changed"),r=e.outObject("Result");r.ignoreValueSerialize=true;i.onChange=function(){r.setRef(i.get());n.trigger()};e.init=()=>{if(i.get())n.trigger()}}};CABLES.OPS["67969ea9-7d2b-48e5-8bb0-a2e4f6c4888d"]={f:Ops.Trigger.TriggerOnChangeObject_v2,objName:"Ops.Trigger.TriggerOnChangeObject_v2"};Ops.Html.CSS.ElementCssBorder=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inObject("Element"),n=e.inFloat("Thickness",3),r=e.inFloat("Radius",0),s=e.inValueSlider("Color R",1),a=e.inValueSlider("Color G",1),o=e.inValueSlider("Color B",1),l=e.inValueSlider("Color A",1),u=e.inBool("Top",true),h=e.inBool("Bottom",true),c=e.inBool("Left",true),g=e.inBool("Right",true),f=e.outObject("HTML Element",null,"element");s.setUiAttribs({colorPick:true});let d=null;u.onChange=h.onChange=c.onChange=g.onChange=i.onChange=i.onLinkChanged=n.onChange=r.onChange=s.onChange=a.onChange=o.onChange=l.onChange=p;e.onDelete=m;function m(){if(d){d.style.removeProperty("border");d.style.removeProperty("borderTop");d.style.removeProperty("borderBottom");d.style.removeProperty("borderLeft");d.style.removeProperty("borderRight");d.style.removeProperty("border-radius")}}function p(){m();d=i.get();if(d&&d.style){let e="rgba("+Math.floor(s.get()*255)+","+Math.floor(a.get()*255)+","+Math.floor(o.get()*255)+","+l.get()+")";if(u.get()&&h.get()&&g.get()&&c.get()){d.style.border=n.get()+"px solid "+e}else{if(u.get())d.style.borderTop=n.get()+"px solid "+e;if(h.get())d.style.borderBottom=n.get()+"px solid "+e;if(c.get())d.style.borderLeft=n.get()+"px solid "+e;if(g.get())d.style.borderRight=n.get()+"px solid "+e}d.style["border-radius"]=r.get()+"px"}else{setTimeout(p,50)}f.setRef(i.get())}}};CABLES.OPS["e1c84aec-667d-426f-8922-99fa8a175bad"]={f:Ops.Html.CSS.ElementCssBorder,objName:"Ops.Html.CSS.ElementCssBorder"};Ops.Array.ArrayGetObject=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inArray("array"),n=e.inValueInt("index"),r=e.outObject("value");let s=null;i.ignoreValueSerialize=true;r.ignoreValueSerialize=true;n.onChange=a;i.onChange=a;e.toWorkPortsNeedToBeLinked(i);function a(){if(n.get()<0){r.set(null);return}const e=i.get();if(!e){r.set(null);return}const t=n.get();if(t>=e.length){r.set(null);return}if(e[t]){r.setRef(e[t]);s=e[t]}}}};CABLES.OPS["44d34542-174c-47c6-b9c6-adde6fc371ac"]={f:Ops.Array.ArrayGetObject,objName:"Ops.Array.ArrayGetObject"};Ops.Math.Subtract=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};
30982const i=e.inValue("number1",1),n=e.inValue("number2",1),r=e.outNumber("result");e.setUiAttribs({mathTitle:true});i.onChange=n.onChange=s;s();function s(){let e=i.get()-n.get();if(!isNaN(e))r.set(e)}}};CABLES.OPS["a4ffe852-d200-4b96-9347-68feb01122ca"]={f:Ops.Math.Subtract,objName:"Ops.Math.Subtract"};Ops.Number.Number=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inValueFloat("value"),n=e.outNumber("result");i.onChange=s;let r=false;i.onLinkChanged=()=>{if(!r&&i.isLinked())e.setUiAttribs({extendTitle:null});r=i.isLinked()};function s(){if(CABLES.UI&&!r)e.setUiAttribs({extendTitle:i.get()});n.set(Number(i.get()))}}};CABLES.OPS["8fb2bb5d-665a-4d0a-8079-12710ae453be"]={f:Ops.Number.Number,objName:"Ops.Number.Number"};Ops.Html.CSS.GetCssVariable=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inTriggerButton("Update"),n=e.inString("Var Name"),r=e.outString("Result");const s=document.documentElement;i.onTriggered=function(){let e=s.style.getPropertyValue("--"+n.get());if(!e)e=getComputedStyle(s).getPropertyValue("--"+n.get());r.set(e)}}};CABLES.OPS["ef03f407-e365-47c7-9829-be54ba53c54d"]={f:Ops.Html.CSS.GetCssVariable,objName:"Ops.Html.CSS.GetCssVariable"};Ops.String.StringToNumber=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inString("String",0),n=e.outNumber("Number"),r=e.outBoolNum("Not a number",false);i.onChange=function(){r.set(false);let e=parseFloat(i.get());if(e!=e){e=0;r.set(true)}n.set(e)}}};CABLES.OPS["fa36a56b-a64d-4269-9a9e-addc16493006"]={f:Ops.String.StringToNumber,objName:"Ops.String.StringToNumber"};Ops.Boolean.BoolByTrigger=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inTriggerButton("True"),n=e.inTriggerButton("false"),r=e.outBoolNum("Result");i.onTriggered=function(){r.set(true)};n.onTriggered=function(){r.set(false)}}};CABLES.OPS["31f65abe-9d6c-4ba6-a291-ef2de41d2087"]={f:Ops.Boolean.BoolByTrigger,objName:"Ops.Boolean.BoolByTrigger"};Ops.Math.Floor=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inValue("Number");const n=e.outNumber("Result");i.onChange=r;function r(){n.set(Math.floor(i.get()))}}};CABLES.OPS["0c77617c-b688-4b55-addf-2cbcaabf98af"]={f:Ops.Math.Floor,objName:"Ops.Math.Floor"};Ops.Trigger.TimeSinceTrigger=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inTrigger("exe"),n=e.inTriggerButton("trigger"),r=e.inTriggerButton("reset"),s=e.outTrigger("next"),a=e.outNumber("time");let o=e.patch.freeTimer.get();a.set(0);i.onTriggered=function(){a.set(e.patch.freeTimer.get()-o);s.trigger()};r.onTriggered=function(){a.set(0)};n.onTriggered=function(){o=e.patch.freeTimer.get();a.set(0)}}};CABLES.OPS["df54103f-5ef6-4a4f-adcf-dddc005132f8"]={f:Ops.Trigger.TimeSinceTrigger,objName:"Ops.Trigger.TimeSinceTrigger"};Ops.Math.MapRange=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const g=e.inValueFloat("value",0),f=e.inValueFloat("old min",0),d=e.inValueFloat("old max",1),m=e.inValueFloat("new min",0),p=e.inValueFloat("new max",1),i=e.inValueSelect("Easing",["Linear","Smoothstep","Smootherstep"],"Linear"),n=e.inBool("Clamp",true),_=e.outNumber("result",0);e.setPortGroup("Input Range",[f,d]);e.setPortGroup("Output Range",[m,p]);let v=true;let x=0;let b=0;g.onChange=f.onChange=d.onChange=m.onChange=p.onChange=r;r();n.onChange=()=>{v=n.get();r()};i.onChange=function(){if(i.get()=="Smoothstep")x=1;else if(i.get()=="Smootherstep")x=2;else x=0};function r(){const e=m.get();const t=p.get();const i=f.get();const n=d.get();let r=g.get();if(v){if(r>=Math.max(n,i)){_.set(t);return}else if(r<=Math.min(n,i)){_.set(e);return}}let s=false;const a=Math.min(i,n);const o=Math.max(i,n);if(a!=i)s=true;let l=false;const u=Math.min(e,t);const h=Math.max(e,t);if(u!=e)l=true;
30982let c=0;if(s)c=(o-r)*(h-u)/(o-a);else c=(r-a)*(h-u)/(o-a);if(l)b=h-c;else b=c+u;if(x===0){_.set(b)}else if(x==1){r=Math.max(0,Math.min(1,(b-e)/(t-e)));_.set(e+r*r*(3-2*r)*(t-e))}else if(x==2){r=Math.max(0,Math.min(1,(b-e)/(t-e)));_.set(e+r*r*r*(r*(r*6-15)+10)*(t-e))}}}};CABLES.OPS["2617b407-60a0-4ff6-b4a7-18136cfa7817"]={f:Ops.Math.MapRange,objName:"Ops.Math.MapRange"};Ops.Number.SwitchNumber=class extends CABLES.Op{constructor(){super(...arguments);const i=this;const e=i.attachments={};const t=i.inValueInt("Index");const n=[];const r=i.outNumber("Result");t.onChange=s;for(let t=0;t<16;t++){let e=i.inValueFloat("Value "+t);n.push(e);e.onChange=s}function s(){const e=t.get();if(e>=0&&n[e]){r.set(n[e].get())}}}};CABLES.OPS["fbb89f72-f2e3-4d34-ad01-7d884a1bcdc0"]={f:Ops.Number.SwitchNumber,objName:"Ops.Number.SwitchNumber"};Ops.Math.Compare.GreaterThan=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inValueFloat("number1"),n=e.inValueFloat("number2"),r=e.outBoolNum("result");e.setUiAttribs({mathTitle:true});i.onChange=n.onChange=s;function s(){r.set(i.get()>n.get())}}};CABLES.OPS["b250d606-f7f8-44d3-b099-c29efff2608a"]={f:Ops.Math.Compare.GreaterThan,objName:"Ops.Math.Compare.GreaterThan"};Ops.Boolean.Not=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inValueBool("Boolean"),n=e.outBoolNum("Result");i.changeAlways=true;i.onChange=function(){n.set(!i.get())}}};CABLES.OPS["6d123c9f-7485-4fd9-a5c2-76e59dcbeb34"]={f:Ops.Boolean.Not,objName:"Ops.Boolean.Not"};Ops.Anim.BoolAnim=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=new CABLES.Anim;const n=e.inTrigger("exe"),r=e.inValueBool("bool"),s=i.createPort(e,"easing"),a=e.inValue("duration",.25),o=e.inValueSelect("Direction",["Both","Only True","Only False"],"Both"),l=e.inValue("value false",0),u=e.inValue("value true",1),h=e.outTrigger("trigger"),c=e.outNumber("value"),g=e.outBoolNum("finished"),f=e.outTrigger("Finished Trigger");const d=CABLES.now();e.toWorkPortsNeedToBeLinked(n);e.setPortGroup("Animation",[a,s]);e.setPortGroup("Values",[l,u]);o.onChange=r.onChange=l.onChange=u.onChange=a.onChange=m;m();function m(){if(o.get()=="Animate Both")o.set("Both");g.set(false);const e=(CABLES.now()-d)/1e3;const t=i.getValue(e);i.clear();i.setValue(e,t);if(!r.get()){if(o.get()!="Only True")i.setValue(e+a.get(),l.get());else i.setValue(e,l.get())}else{if(o.get()!="Only False")i.setValue(e+a.get(),u.get());else i.setValue(e,u.get())}}n.onTriggered=function(){const e=(CABLES.now()-d)/1e3;c.set(i.getValue(e));if(i.hasEnded(e)){if(!g.get())f.trigger();g.set(true)}h.trigger()}}};CABLES.OPS["06ad9d35-ccf5-4d31-889c-e23fa062588a"]={f:Ops.Anim.BoolAnim,objName:"Ops.Anim.BoolAnim"};Ops.Boolean.Boolean=class extends CABLES.Op{constructor(){super(...arguments);const e=this;const t=e.attachments={};const i=e.inBool("value",false),n=e.outBoolNum("result");n.set(false);i.onChange=r;function r(){if(n.get()!=i.get())n.set(i.get())}}};CABLES.OPS["83e2d74c-9741-41aa-a4d7-1bda4ef55fb3"]={f:Ops.Boolean.Boolean,objName:"Ops.Boolean.Boolean"};Ops.Html.ElementClientRect=class extends CABLES.Op{constructor(){super(...arguments);const r=this;const e=r.attachments={};const t=r.inTriggerButton("Update"),s=r.inObject("Element",null,"element"),a=r.inSwitch("Pixel Units",["CSS Pixels","Display Pixels"],"CSS Pixels"),o=r.inSwitch("Position",["In Canvas","Absolute"],"In Canvas"),l=r.outNumber("X"),u=r.outNumber("Y"),h=r.outNumber("Width"),c=r.outNumber("Height");s.onChange=t.onTriggered=()=>{let e=s.get();if(!e||!e.getBoundingClientRect){l.set(0);u.set(0);h.set(0);c.set(0);return}const t=e.getBoundingClientRect();const i=r.patch.containerElement.getBoundingClientRect();let n=1;if(a.get()=="Display Pixels"){n=r.patch.cgl.pixelDensity}if(o.get()=="In Canvas"){l.set(t.left*n-i.left*n);u.set(t.top*n-i.top*n)}else{l.set(t.left*n);u.set(t.top*n)}h.set(t.width*n);c.set(t.height*n)}}};CABLES.OPS["7a046f98-2adc-4f8e-ad47-c600e3ef5bca"]={f:Ops.Html.ElementClientRect,objName:"Ops.Html.ElementClientRect"};window.addEventListener("load",function(e){CABLES.jsLoaded=new Event("CABLES.jsLoaded");document.dispatchEvent(CABLES.jsLoaded)});(()=>{var K={};(()=>{K.d=(e,t)=>{for(var i in t){if(K.o(t,i)&&!K.o(e,i)){Object.defineProperty(e,i,{enumerable:true,get:t[i]})}}}})();(()=>{K.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)})();(()=>{K.r=e=>{if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}
30982Object.defineProperty(e,"__esModule",{value:true})}})();var J={};(()=>{"use strict";K.r(J);K.d(J,{CopyTexture:()=>Q});const E=CABLES;const h=CABLES.SHARED;const t=8;class i{constructor(e={}){this.id=E.utils.uuid();this.width=0;this.height=0;this.name="unknown";e=e||{};this.pixelFormat=e.pixelFormat||i.PFORMATSTR_RGBA8UB;this.name=e.name||"unknown";if(!e.width)e.width=t;if(!e.height)e.height=t}}i.getDefaultTextureData=(e,s,a={})=>{if(e=="empty"){return new Uint8Array(s*s*4).fill(0)}else if(e=="color"){const r=new Uint8Array(s*s*4);let t=a.r||1;let i=a.g||1;let n=a.b||1;for(let e=0;e<s*s;e++){r[e*4+0]=t;r[e*4+1]=i;r[e*4+2]=n;r[e*4+3]=255}return r}else if(e=="randomUInt"){const r=new Uint8Array(s*s*4);for(let e=0;e<s*s;e++){r[e*4+0]=Math.random()*255;r[e*4+1]=Math.random()*255;r[e*4+2]=Math.random()*255;r[e*4+3]=255}return r}else if(e=="random"||e=="randomFloat"){const r=new Float32Array(s*s*4);for(let e=0;e<s*s;e++){r[e*4+0]=(Math.random()-.5)*2;r[e*4+1]=(Math.random()-.5)*2;r[e*4+2]=(Math.random()-.5)*2;r[e*4+3]=1}return r}else if(e=="stripes"){const o=[];let i=a.r;let n=a.g;let r=a.b;if(i===undefined)i=1;if(n===undefined)n=1;if(r===undefined)r=1;for(let t=0;t<s;t++){for(let e=0;e<s;e++){if((e+t)%64<32){o.push((200+t/s*25+e/s*25)*i);o.push((200+t/s*25+e/s*25)*n);o.push((200+t/s*25+e/s*25)*r)}else{o.push((40+t/s*25+e/s*25)*i);o.push((40+t/s*25+e/s*25)*n);o.push((40+t/s*25+e/s*25)*r)}o.push(255)}}return new Uint8Array(o)}else{console.warn("unknown default texture",e);return i.getDefaultTextureData("stripes",s,{r:1,g:0,b:0})}};i.FILTER_NEAREST=0;i.FILTER_LINEAR=1;i.FILTER_MIPMAP=2;i.WRAP_REPEAT=0;i.WRAP_MIRRORED_REPEAT=1;i.WRAP_CLAMP_TO_EDGE=2;i.TYPE_DEFAULT=0;i.TYPE_DEPTH=1;i.TYPE_FLOAT=2;i.PFORMATSTR_RGB565="RGB 5/6/5bit ubyte";i.PFORMATSTR_R8UB="R 8bit ubyte";i.PFORMATSTR_RG8UB="RG 8bit ubyte";i.PFORMATSTR_RGB8UB="RGB 8bit ubyte";i.PFORMATSTR_RGBA8UB="RGBA 8bit ubyte";i.PFORMATSTR_SRGBA8="SRGBA 8bit ubyte";i.PFORMATSTR_R11FG11FB10F="RGB 11/11/10bit float";i.PFORMATSTR_R16F="R 16bit float";i.PFORMATSTR_RG16F="RG 16bit float";i.PFORMATSTR_RGB16F="RGB 16bit float";i.PFORMATSTR_RGBA16F="RGBA 16bit float";i.PFORMATSTR_R32F="R 32bit float";i.PFORMATSTR_RG32F="RG 32bit float";i.PFORMATSTR_RGB32F="RGB 32bit float";i.PFORMATSTR_RGBA32F="RGBA 32bit float";i.PFORMATSTR_DEPTH="DEPTH";i.PIXELFORMATS=[i.PFORMATSTR_RGB565,i.PFORMATSTR_R8UB,i.PFORMATSTR_RG8UB,i.PFORMATSTR_RGB8UB,i.PFORMATSTR_RGBA8UB,i.PFORMATSTR_SRGBA8,i.PFORMATSTR_R11FG11FB10F,i.PFORMATSTR_R16F,i.PFORMATSTR_RG16F,i.PFORMATSTR_RGBA16F,i.PFORMATSTR_R32F,i.PFORMATSTR_RGBA32F];const n=8;const a=new h.Logger("cgl_texture");class u extends i{constructor(e,t={}){super(t);if(!e)throw new Error("no cgl");this._cgl=e;this._log=new h.Logger("tex");this.tex=this._cgl.gl.createTexture();this.loading=false;this.flip=true;this.flipped=false;this.shadowMap=false;this.deleted=false;this.image=null;this.anisotropic=0;this.filter=u.FILTER_NEAREST;this.wrap=u.WRAP_CLAMP_TO_EDGE;this.texTarget=this._cgl.gl.TEXTURE_2D;if(t&&t.type)this.texTarget=t.type;this.textureType=u.TYPE_DEFAULT;this.unpackAlpha=true;this._fromData=true;this._glDataType=-1;this._glInternalFormat=-1;this._glDataFormat=-1;if(t){if(t.isDepthTexture)this.textureType=u.TYPE_DEPTH;if(t.isFloatingPointTexture===true)this.textureType=u.TYPE_FLOAT;if("textureType"in t)this.textureType=t.textureType;if("filter"in t)this.filter=t.filter;if("wrap"in t)this.wrap=t.wrap;if("unpackAlpha"in t)this.unpackAlpha=t.unpackAlpha;if("flip"in t)this.flip=t.flip;if("shadowMap"in t)this.shadowMap=t.shadowMap;if("anisotropic"in t)this.anisotropic=t.anisotropic}else{t={}}if(!t.pixelFormat&&t.isFloatingPointTexture)this.pixelFormat=u.PFORMATSTR_RGBA32F;if(this.textureType==u.TYPE_DEPTH)this.pixelFormat=u.PFORMATSTR_DEPTH;this._cgl.profileData.profileTextureNew++;this.setFormat(u.setUpGlPixelFormat(this._cgl,this.pixelFormat));this._cgl.profileData.addHeavyEvent("texture created",this.name,t.width+"x"+t.height);this.setSize(t.width,t.height);this.getInfoOneLine()}isFloatingPoint(){return u.isPixelFormatFloat(this.pixelFormat)}compareSettings(e){if(!e)return false;return e.width==this.width&&e.height==this.height&&e.filter==this.filter&&e.
30982wrap==this.wrap&&e.textureType==this.textureType&&e.unpackAlpha==this.unpackAlpha&&e.anisotropic==this.anisotropic&&e.shadowMap==this.shadowMap&&e.texTarget==this.texTarget&&e.flip==this.flip}clone(){const e=new u(this._cgl,{name:this.name,filter:this.filter,anisotropic:this.anisotropic,wrap:this.wrap,textureType:this.textureType,pixelFormat:this.pixelFormat,unpackAlpha:this.unpackAlpha,flip:this.flip,width:this.width,height:this.height});this._cgl.profileData.addHeavyEvent("texture created",this.name,this.width+"x"+this.height);if(!this.compareSettings(e)){this._log.error("Cloned texture settings do not compare!");this._log.error(this);this._log.error(e)}return e}setFormat(e){this.pixelFormat=e.pixelFormat;this._glDataFormat=e.glDataFormat;this._glInternalFormat=e.glInternalFormat;this._glDataType=e.glDataType}setSize(e,t){if(this._cgl.aborted)return;if(e!=e||e<=0||!e)e=n;if(t!=t||t<=0||!t)t=n;if(e>this._cgl.maxTexSize||t>this._cgl.maxTexSize)this._log.error("texture size too big! "+e+"x"+t+" / max: "+this._cgl.maxTexSize);e=Math.min(e,this._cgl.maxTexSize);t=Math.min(t,this._cgl.maxTexSize);e=Math.floor(e);t=Math.floor(t);if(this.width==e&&this.height==t)return;e=this._cgl.checkTextureSize(e);t=this._cgl.checkTextureSize(t);this.width=e;this.height=t;this.deleted=false;this.setFormat(u.setUpGlPixelFormat(this._cgl,this.pixelFormat));this.shortInfoString=this.getInfoOneLine();this._cgl.gl.bindTexture(this.texTarget,this.tex);this._cgl.profileData.profileTextureResize++;const i=null;this._cgl.gl.texImage2D(this.texTarget,0,this._glInternalFormat,e,t,0,this._glDataFormat,this._glDataType,i);this._setFilter();this.updateMipMap();this._cgl.gl.bindTexture(this.texTarget,null)}initFromData(e,t,i,n,r){this.filter=n;this.wrap=r;if(n==undefined)this.filter=u.FILTER_LINEAR;if(r==undefined)this.wrap=u.WRAP_CLAMP_TO_EDGE;this.width=t;this.height=i;this._fromData=true;this.deleted=false;if(this.height>this._cgl.maxTexSize||this.width>this._cgl.maxTexSize){const s=CGL.Texture.getTempTexture(this._cgl);this.width=s.width;this.height=s.height;this.tex=s.tex;this._log.warn("[cgl_texture] texture size too big!",this.width,this.height,this._cgl.maxTexSize);return}if(this.flip)this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_FLIP_Y_WEBGL,this.flip);this._cgl.gl.bindTexture(this.texTarget,this.tex);this.setFormat(u.setUpGlPixelFormat(this._cgl,this.pixelFormat));this._cgl.gl.texImage2D(this.texTarget,0,this._glInternalFormat,t,i,0,this._glDataFormat,this._glDataType,e);this._setFilter();this.updateMipMap();if(this.flip)this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_FLIP_Y_WEBGL,false);this._cgl.gl.bindTexture(this.texTarget,null)}updateMipMap(){if((this._cgl.glVersion==2||this.isPowerOfTwo())&&this.filter==u.FILTER_MIPMAP){this._cgl.gl.generateMipmap(this.texTarget);this._cgl.profileData.profileGenMipMap++}}initTexture(e,t=null){this._cgl.printError("before initTexture");this._cgl.checkFrameStarted("texture inittexture");this._fromData=false;this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.unpackAlpha);if(e.width||e.videoWidth)this.width=e.videoWidth||e.width;if(e.height||e.videoHeight)this.height=e.videoHeight||e.height;if(t!==null)this.filter=t;if(e.height>this._cgl.maxTexSize||e.width>this._cgl.maxTexSize){const i=CGL.Texture.getTempTexture(this._cgl);this.width=i.width;this.height=i.height;this.tex=i.tex;this._log.warn("[cgl_texture] texture size too big!",e.width,e.height,this._cgl.maxTexSize);return}this._cgl.gl.bindTexture(this.texTarget,this.tex);this.deleted=false;this.flipped=!this.flip;if(this.flipped)this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_FLIP_Y_WEBGL,this.flipped);this.setFormat(u.setUpGlPixelFormat(this._cgl,this.pixelFormat));this._cgl.gl.texImage2D(this.texTarget,0,this._glInternalFormat,this._glDataFormat,this._glDataType,e);this._setFilter();this.updateMipMap();this._cgl.gl.bindTexture(this.texTarget,null);this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false);if(this.flipped)this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_FLIP_Y_WEBGL,false);this.getInfoOneLine();this._cgl.printError("initTexture")}dispose(){this.delete()}delete(){if(this.loading){return}this.deleted=true;this.width=0;this.height=0;this._cgl.profileData.profileTextureDelete++;this._cgl.gl.deleteTexture(this.tex);this.image=null;this.tex=null}isPowerOfTwo(){return u.isPowerOfTwo(this.width)&&u.isPowerOfTwo(this.height)}printInfo(){a.log(this.getInfo())}getInfoReadable(){const t=this.getInfo();let i="";t.name=t.name.substr(0,t.name.indexOf("?rnd="));for(const e in t){i+="* "+e+": **"+t[e]+"**\n"}return i}getInfoOneLine(){let e=""+this.width+"x"+this.height;e+=" ";e+=this.pixelFormat;if(this.filter===u.FILTER_NEAREST)e+=" nearest";if(this.filter===u.FILTER_LINEAR)e+=" linear";if(this.filter===u.FILTER_MIPMAP)e+=" mipmap";if(this.wrap===u.WRAP_CLAMP_TO_EDGE)e+=" clamp";if(this.wrap===u.WRAP_REPEAT)e+=" repeat";if(this.wrap===u.WRAP_MIRRORED_REPEAT)e+=" repeatmir";this.shortInfoString=e;return e}getInfoOneLineShort(){let e=""+this.width+"x"+this.height;e+=" ";e+=this.pixelFormat;this.shortInfoString=e;return e}getInfo(){return u.getTexInfo(this)}_setFilter(){this._cgl.printError("before _setFilter");if(!this._fromData){this._cgl.gl.pixelStorei(this._cgl.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.unpackAlpha)}if(this.shadowMap){this._cgl.gl.texParameteri(this._cgl.gl.TEXTURE_2D,this._cgl.gl.TEXTURE_COMPARE_MODE,this._cgl.gl.COMPARE_REF_TO_TEXTURE);this._cgl.gl.texParameteri(this._cgl.gl.TEXTURE_2D,this._cgl.gl.TEXTURE_COMPARE_FUNC,this._cgl.gl.LEQUAL)}if(this.textureType==u.TYPE_FLOAT&&this.filter==u.FILTER_MIPMAP){this.filter=u.FILTER_LINEAR;this._log.stack("texture: HDR and mipmap filtering at the same time is not possible")}if(this._cgl.glVersion==1&&!this.isPowerOfTwo()){this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_MAG_FILTER,this._cgl.gl.NEAREST);this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_MIN_FILTER,this._cgl.gl.NEAREST);this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_WRAP_S,this._cgl.gl.CLAMP_TO_EDGE);this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_WRAP_T,this._cgl.gl.CLAMP_TO_EDGE);this.filter=u.FILTER_NEAREST;this.wrap=u.WRAP_CLAMP_TO_EDGE}else{if(this.wrap==u.WRAP_CLAMP_TO_EDGE){this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_WRAP_S,this._cgl.gl.CLAMP_TO_EDGE);this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_WRAP_T,this._cgl.gl.CLAMP_TO_EDGE)}else if(this.wrap==u.WRAP_REPEAT){this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_WRAP_S,this._cgl.gl.REPEAT);this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_WRAP_T,this._cgl.gl.REPEAT)}else if(this.wrap==u.WRAP_MIRRORED_REPEAT){this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_WRAP_S,this._cgl.gl.MIRRORED_REPEAT);this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_WRAP_T,this._cgl.gl.MIRRORED_REPEAT)}if(this.filter==u.FILTER_NEAREST){this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_MAG_FILTER,this._cgl.gl.NEAREST);this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_MIN_FILTER,this._cgl.gl.NEAREST)}else if(this.filter==u.FILTER_LINEAR){this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_MIN_FILTER,this._cgl.gl.LINEAR);this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_MAG_FILTER,this._cgl.gl.LINEAR)}else if(this.filter==u.FILTER_MIPMAP){this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_MAG_FILTER,this._cgl.gl.LINEAR);this._cgl.gl.texParameteri(this.texTarget,this._cgl.gl.TEXTURE_MIN_FILTER,this._cgl.gl.LINEAR_MIPMAP_LINEAR)}else{this._log.log("unknown texture filter!",this.filter);throw new Error("unknown texture filter!"+this.filter)}if(this.anisotropic){const e=this._cgl.enableExtension("EXT_texture_filter_anisotropic");if(this._cgl.maxAnisotropic){const t=Math.min(this._cgl.maxAnisotropic,this.anisotropic);this._cgl.gl.texParameterf(this._cgl.gl.TEXTURE_2D,e.TEXTURE_MAX_ANISOTROPY_EXT,t)}}}this.getInfoOneLine();this._cgl.printError("_setFilter")}}u.load=function(i,n,r,e){if(!n)return r({error:true});let s=null;if(!i.patch.loading.existByName(n))s=i.patch.loading.start("cgl.texture",n);const a=new u(i);a.name=n;a.image=new Image;a.image.crossOrigin="anonymous";a.loading=true;if(e&&e.hasOwnProperty("filter"))a.filter=e.filter;if(e&&e.hasOwnProperty("flip"))a.flip=e.flip;if(e&&e.hasOwnProperty("wrap"))a.wrap=e.wrap;if(e&&e.hasOwnProperty("anisotropic"))a.anisotropic=e.anisotropic;if(e&&e.hasOwnProperty("unpackAlpha"))a.unpackAlpha=e.unpackAlpha;if(e&&e.hasOwnProperty("pixelFormat"))a.pixelFormat=e.pixelFormat;a.image.onabort=a.image.onerror=e=>{console.warn("[cgl.texture.load] error loading texture",n,e);a.loading=false;if(s)i.patch.loading.finished(s);const t={error:true};if(r)r(t,a)};a.image.onload=function(e){i.addNextFrameOnceCallback(()=>{a.initTexture(a.image);if(s)i.patch.loading.finished(s);a.loading=false;if(r)r(null,a)})};a.image.src=n;return a};u.getTempTexture=function(e){if(!e)console.error("[getTempTexture] no cgl!");if(!e.tempTexture)e.tempTexture=u.getTemporaryTexture(e,256,u.FILTER_LINEAR,u.REPEAT);return e.tempTexture};u.getErrorTexture=function(e){if(!e)console.error("[getTempTexture] no cgl!");if(!e.errorTexture)e.errorTexture=u.getTemporaryTexture(e,256,u.FILTER_LINEAR,u.REPEAT,1,.2,.2);return e.errorTexture};u.getEmptyTexture=function(e,t){if(t)return u.getEmptyTextureFloat(e);
30982if(!e)console.error("[getEmptyTexture] no cgl!");if(e.tempTextureEmpty)return e.tempTextureEmpty;let i=8;e.tempTextureEmpty=new u(e,{name:"emptyTexture"});const n=u.getDefaultTextureData("empty",i);e.tempTextureEmpty.initFromData(n,i,i,u.FILTER_NEAREST,u.WRAP_REPEAT);return e.tempTextureEmpty};u.getEmptyTextureFloat=function(e){if(!e)console.error("[getEmptyTextureFloat] no cgl!");if(e.tempTextureEmptyFloat)return e.tempTextureEmptyFloat;e.tempTextureEmptyFloat=new u(e,{name:"emptyTexture",isFloatingPointTexture:true});const t=new Float32Array(8*8*4).fill(1);for(let e=0;e<8*8*4;e+=4)t[e+3]=0;e.tempTextureEmptyFloat.initFromData(t,8,8,u.FILTER_NEAREST,u.WRAP_REPEAT);return e.tempTextureEmptyFloat};u.getRandomTexture=function(e){if(!e)console.error("[getRandomTexture] no cgl!");if(e.randomTexture)return e.randomTexture;const t=256;const i=u.getDefaultTextureData("randomUInt",t);e.randomTexture=new u(e);e.randomTexture.initFromData(i,t,t,u.FILTER_NEAREST,u.WRAP_REPEAT);return e.randomTexture};u.getRandomFloatTexture=function(e){if(!e)console.error("[getRandomTexture] no cgl!");if(e.getRandomFloatTexture)return e.getRandomFloatTexture;const t=256;const i=u.getDefaultTextureData("randomFloat",t);e.getRandomFloatTexture=new u(e,{isFloatingPointTexture:true});e.getRandomFloatTexture.initFromData(i,t,t,u.FILTER_NEAREST,u.WRAP_REPEAT);return e.getRandomFloatTexture};u.getBlackTexture=function(e){if(e.blackTexture)return e.blackTexture;const t=8;const i=u.getDefaultTextureData("color",t,{r:0,g:0,b:0});e.blackTexture=new u(e);e.blackTexture.initFromData(i,t,t,u.FILTER_NEAREST,u.WRAP_REPEAT);return e.blackTexture};u.getEmptyCubemapTexture=function(t){const i=[t.gl.TEXTURE_CUBE_MAP_POSITIVE_X,t.gl.TEXTURE_CUBE_MAP_NEGATIVE_X,t.gl.TEXTURE_CUBE_MAP_POSITIVE_Y,t.gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.gl.TEXTURE_CUBE_MAP_POSITIVE_Z,t.gl.TEXTURE_CUBE_MAP_NEGATIVE_Z];const e=t.gl.createTexture();const n=t.gl.TEXTURE_CUBE_MAP;const r=u.FILTER_NEAREST;const s=u.WRAP_CLAMP_TO_EDGE;const a=8;const o=8;t.profileData.profileTextureNew++;t.gl.bindTexture(n,e);t.profileData.profileTextureResize++;for(let e=0;e<6;e+=1){const l=new Uint8Array(8*8*4);t.gl.texImage2D(i[e],0,t.gl.RGBA,8,8,0,t.gl.RGBA,t.gl.UNSIGNED_BYTE,l);t.gl.texParameteri(n,t.gl.TEXTURE_MAG_FILTER,t.gl.NEAREST);t.gl.texParameteri(n,t.gl.TEXTURE_MIN_FILTER,t.gl.NEAREST);t.gl.texParameteri(n,t.gl.TEXTURE_WRAP_S,t.gl.CLAMP_TO_EDGE);t.gl.texParameteri(n,t.gl.TEXTURE_WRAP_T,t.gl.CLAMP_TO_EDGE)}t.gl.bindTexture(n,null);return{id:E.utils.uuid(),tex:e,cubemap:e,width:a,height:o,filter:r,wrap:s,unpackAlpha:true,flip:true,_fromData:true,name:"emptyCubemapTexture",anisotropic:0}};u.getTempGradientTexture=function(e){if(!e)console.error("[getTempGradientTexture] no cgl!");return u.getTempTexture(e)};u.getTemporaryTexture=function(e,t,i,n,r,s,a){const o=u.getDefaultTextureData("stripes",256,{r:r,g:s,b:a});const l=new u(e);l.initFromData(o,t,t,i,n);return l};u.createFromImage=function(e,t,i){i=i||{};const n=new u(e,i);n.flip=false;n.image=t;n.width=t.videoWidth||t.width||8;n.height=t.videoHeight||t.height||8;if(i.hasOwnProperty("wrap"))n.wrap=i.wrap;n.initTexture(t,i.filter);return n};u.fromImage=function(e,t,i,n){console.error("deprecated texture from image...");const r=new u(e);r.flip=false;if(i)r.filter=i;if(n)r.wrap=n;r.image=t;r.initTexture(t);return r};u.isPowerOfTwo=function(e){return e==1||e==2||e==4||e==8||e==16||e==32||e==64||e==128||e==256||e==512||e==1024||e==2048||e==4096||e==8192||e==16384};u.getTexInfo=function(e){const t={};t.name=e.name;t["power of two"]=e.isPowerOfTwo();t.size=e.width+" x "+e.height;let i=e.texTarget;if(e.texTarget==e._cgl.gl.TEXTURE_2D)i="TEXTURE_2D";t.target=i;t.unpackAlpha=e.unpackAlpha;if(e.cubemap)t.cubemap=true;if(e.textureType==u.TYPE_FLOAT)t.textureType="TYPE_FLOAT";if(e.textureType==u.TYPE_HALF_FLOAT)t.textureType="TYPE_HALF_FLOAT";else if(e.textureType==u.TYPE_DEPTH)t.textureType="TYPE_DEPTH";else if(e.textureType==u.TYPE_DEFAULT)t.textureType="TYPE_DEFAULT";else t.textureType="UNKNOWN "+this.textureType;if(e.wrap==u.WRAP_CLAMP_TO_EDGE)t.wrap="CLAMP_TO_EDGE";else if(e.wrap==u.WRAP_REPEAT)t.wrap="WRAP_REPEAT";else if(e.wrap==u.WRAP_MIRRORED_REPEAT)t.wrap="WRAP_MIRRORED_REPEAT";else t.wrap="UNKNOWN";if(e.filter==u.FILTER_NEAREST)t.filter="FILTER_NEAREST";else if(e.filter==u.FILTER_LINEAR)t.filter="FILTER_LINEAR";else if(e.filter==u.FILTER_MIPMAP)t.filter="FILTER_MIPMAP";else t.filter="UNKNOWN";t.pixelFormat=e.pixelFormat||"unknown";return t};u.setUpGlPixelFormat=function(e,t){const i={};if(!t){e._log.error("no pixelformatstr!");e._log.log(new Error);t=u.PFORMATSTR_RGBA8UB}i.pixelFormatBase=t;i.pixelFormat=t;i.glDataType=e.gl.UNSIGNED_BYTE;i.glInternalFormat=e.gl.RGBA8;i.glDataFormat=e.gl.RGBA;let n=e.gl.FLOAT;if(e.glUseHalfFloatTex){if(t==u.PFORMATSTR_RGBA32F)t=u.PFORMATSTR_RGBA16F;if(t==u.PFORMATSTR_RG32F)t=u.PFORMATSTR_RG16F;if(t==u.PFORMATSTR_R32F)t=u.PFORMATSTR_R16F}if(t.includes("16bit")){if(e.glVersion==2){const r=e.enableExtension("EXT_color_buffer_half_float");
30982if(!r){console.warn("no 16bit extension, fallback to 32bit",t);if(t==u.PFORMATSTR_RGBA16F)t=u.PFORMATSTR_RGBA32F;if(t==u.PFORMATSTR_RGB16F)t=u.PFORMATSTR_RGB32F;if(t==u.PFORMATSTR_RG16F)t=u.PFORMATSTR_RG32F;if(t==u.PFORMATSTR_R16F)t=u.PFORMATSTR_R32F}else{n=e.gl.HALF_FLOAT}}}if(e.glVersion==1){i.glInternalFormat=e.gl.RGBA;if(t==u.PFORMATSTR_RGBA16F||t==u.PFORMATSTR_RG16F||t==u.PFORMATSTR_R16F){const s=e.enableExtension("OES_texture_half_float");if(!s)throw new Error("no half float texture extension");n=s.HALF_FLOAT_OES}}if(t==u.PFORMATSTR_RGBA8UB){}else if(t==u.PFORMATSTR_RGB565){i.glInternalFormat=e.gl.RGB565;i.glDataFormat=e.gl.RGB}else if(t==u.PFORMATSTR_R8UB){i.glInternalFormat=e.gl.R8;i.glDataFormat=e.gl.RED}else if(t==u.PFORMATSTR_RG8UB){i.glInternalFormat=e.gl.RG8;i.glDataFormat=e.gl.RG}else if(t==u.PFORMATSTR_RGB8UB){i.glInternalFormat=e.gl.RGB8;i.glDataFormat=e.gl.RGB}else if(t==u.PFORMATSTR_SRGBA8){i.glInternalFormat=e.gl.SRGB8_ALPHA8}else if(t==u.PFORMATSTR_R32F){i.glInternalFormat=e.gl.R32F;i.glDataFormat=e.gl.RED;i.glDataType=n}else if(t==u.PFORMATSTR_R16F){i.glInternalFormat=e.gl.R16F;i.glDataType=n;i.glDataFormat=e.gl.RED}else if(t==u.PFORMATSTR_RG16F){i.glInternalFormat=e.gl.RG16F;i.glDataType=n;i.glDataFormat=e.gl.RG}else if(t==u.PFORMATSTR_RGBA16F){if(e.glVersion==1)i.glInternalFormat=e.gl.RGBA;else i.glInternalFormat=e.gl.RGBA16F;i.glDataType=n}else if(t==u.PFORMATSTR_R11FG11FB10F){i.glInternalFormat=e.gl.R11F_G11F_B10F;i.glDataType=n;i.glDataFormat=e.gl.RGB}else if(t==u.PFORMATSTR_RGBA32F){if(e.glVersion==1)i.glInternalFormat=e.gl.RGBA;else i.glInternalFormat=e.gl.RGBA32F;i.glDataType=n}else if(t==u.PFORMATSTR_DEPTH){if(e.glVersion==1){i.glInternalFormat=e.gl.DEPTH_COMPONENT;i.glDataType=e.gl.UNSIGNED_SHORT;i.glDataFormat=e.gl.DEPTH_COMPONENT}else{i.glInternalFormat=e.gl.DEPTH_COMPONENT32F;i.glDataType=e.gl.FLOAT;i.glDataFormat=e.gl.DEPTH_COMPONENT}}else{a.log("unknown pixelformat ",t)}if(t.includes("32bit")||t==u.PFORMATSTR_R11FG11FB10F){if(e.glVersion==2)e.enableExtension("EXT_color_buffer_float");if(e.glVersion==2)e.enableExtension("EXT_float_blend");e.enableExtension("OES_texture_float_linear")}i.numColorChannels=u.getPixelFormatNumChannels(t);if(!i.glDataType||!i.glInternalFormat||!i.glDataFormat)a.log("pixelformat wrong ?!",t,i.glDataType,i.glInternalFormat,i.glDataFormat,this);return i};u.getPixelFormatNumChannels=e=>{if(e.startsWith("RGBA"))return 4;if(e.startsWith("RGB"))return 3;if(e.startsWith("RG"))return 2;return 1};u.isPixelFormatFloat=e=>{return(e||"").includes("float")};u.isPixelFormatHalfFloat=e=>{return(e||"").includes("float")&&(e||"").includes("16bit")};class e{constructor(t,e,i,n){this._log=new h.Logger("cgl_framebuffer2");if(t.glVersion==1)this._log.error("framebuffer2 used on webgl1");this.Framebuffer2DrawTargetsDefault=null;this.Framebuffer2BlittingFramebuffer=null;this.Framebuffer2FinalFramebuffer=null;this._cgl=t;this._cgl.printError("before framebuffer2 constructor");this._width=0;this._height=0;this.valid=true;this._depthRenderbuffer=null;this._frameBuffer=null;this._textureFrameBuffer=null;this._colorRenderbuffers=[];this._drawTargetArray=[];this._disposed=false;if(!this.Framebuffer2BlittingFramebuffer)this.Framebuffer2BlittingFramebuffer=t.gl.createFramebuffer();if(!this.Framebuffer2FinalFramebuffer)this.Framebuffer2FinalFramebuffer=t.gl.createFramebuffer();if(!this.Framebuffer2DrawTargetsDefault)this.Framebuffer2DrawTargetsDefault=[t.gl.COLOR_ATTACHMENT0];this._options=n||{isFloatingPointTexture:false};this.name=this._options.name||"unknown";this._cgl.profileData.addHeavyEvent("framebuffer create",this.name);if(!this._options.hasOwnProperty("numRenderBuffers"))this._options.numRenderBuffers=1;if(!this._options.hasOwnProperty("depth"))this._options.depth=true;if(!this._options.hasOwnProperty("clear"))this._options.clear=true;if(!this._options.hasOwnProperty("multisampling")){this._options.multisampling=false;this._options.multisamplingSamples=0}if(this._options.multisamplingSamples){if(this._cgl.glSlowRenderer)this._options.multisamplingSamples=0;if(!this._cgl.gl.MAX_SAMPLES)this._options.multisamplingSamples=0;else this._options.multisamplingSamples=Math.min(this._cgl.maxSamples,this._options.multisamplingSamples)}if(!this._options.hasOwnProperty("filter"))this._options.filter=u.FILTER_LINEAR;if(!this._options.hasOwnProperty("wrap"))this._options.wrap=u.WRAP_REPEAT;
30982this._numRenderBuffers=this._options.numRenderBuffers;this._colorTextures=[];this.clearColors=[];for(let e=0;e<this._numRenderBuffers;e++)this.clearColors.push([0,0,0,1]);if(!n.pixelFormat){if(n.isFloatingPointTexture)this._options.pixelFormat=u.PFORMATSTR_RGBA32F;else this._options.pixelFormat=u.PFORMATSTR_RGBA8UB}for(let e=0;e<this._numRenderBuffers;e++){this._colorTextures[e]=new u(t,{name:"fb2 "+this.name+" "+e,isFloatingPointTexture:this._options.isFloatingPointTexture,anisotropic:this._options.anisotropic||0,pixelFormat:this._options.pixelFormat,filter:this._options.filter,wrap:this._options.wrap})}let r=u.FILTER_NEAREST;if(this._options.shadowMap)r=u.FILTER_LINEAR;const s=512;if(this._options.depth){this._textureDepth=new u(t,{name:"fb2 depth "+this.name,isDepthTexture:true,filter:r,shadowMap:this._options.shadowMap||false,width:e||s,height:i||s})}if(t.aborted)return;this.setSize(e||s,i||s);this._cgl.printError("framebuffer2 constructor")}getWidth(){return this._width}getHeight(){return this._height}getGlFrameBuffer(){return this._frameBuffer}getDepthRenderBuffer(){return this._depthRenderbuffer}getTextureColor(){return this._colorTextures[0]}getTextureColorNum(e){return this._colorTextures[e]}getTextureDepth(){return this._textureDepth}setFilter(t){for(let e=0;e<this._numRenderBuffers;e++){this._colorTextures[e].filter=t;this._colorTextures[e].setSize(this._width,this._height)}}delete(){this.dispose()}dispose(){this._disposed=true;let e=0;for(e=0;e<this._numRenderBuffers;e++)this._colorTextures[e].delete();if(this._textureDepth)this._textureDepth.delete();for(e=0;e<this._numRenderBuffers;e++)this._cgl.gl.deleteRenderbuffer(this._colorRenderbuffers[e]);this._cgl.gl.deleteRenderbuffer(this._depthRenderbuffer);this._cgl.gl.deleteFramebuffer(this._frameBuffer);this._cgl.gl.deleteFramebuffer(this._textureFrameBuffer)}setSize(e,t){if(this._disposed)return this._log.warn("disposed framebuffer setsize...");this._cgl.profileData.addHeavyEvent("framebuffer resize",this.name);let i=0;this._width=this._cgl.checkTextureSize(e);this._height=this._cgl.checkTextureSize(t);this._cgl.profileData.profileFrameBuffercreate++;if(this._frameBuffer){for(i=0;i<this._numRenderBuffers;i++)this._cgl.gl.deleteRenderbuffer(this._colorRenderbuffers[i]);this._cgl.gl.deleteRenderbuffer(this._depthRenderbuffer);this._cgl.gl.deleteFramebuffer(this._frameBuffer);this._cgl.gl.deleteFramebuffer(this._textureFrameBuffer)}this._frameBuffer=this._cgl.gl.createFramebuffer();this._textureFrameBuffer=this._cgl.gl.createFramebuffer();const n=this._options.depth;for(i=0;i<this._numRenderBuffers;i++){this._colorTextures[i].setSize(this._width,this._height)}for(i=0;i<this._numRenderBuffers;i++){const a=this._cgl.gl.createRenderbuffer();this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._frameBuffer);this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER,a);const o=u.setUpGlPixelFormat(this._cgl,this._options.pixelFormat);let e=o.glInternalFormat;if(CGL.Texture.isPixelFormatHalfFloat(o.pixelFormat)){if(!this._cgl.enableExtension("OES_texture_float_linear")){this._options.filter=u.FILTER_NEAREST;this.setFilter(this._options.filter)}}else if(CGL.Texture.isPixelFormatFloat(o.pixelFormat)){if(!this._cgl.enableExtension("OES_texture_float_linear")){this._log.warn("no linear pixelformat,using nearest");this._options.filter=u.FILTER_NEAREST;this.setFilter(this._options.filter)}}if(this._options.multisampling&&this._options.multisamplingSamples){this._cgl.gl.renderbufferStorageMultisample(this._cgl.gl.RENDERBUFFER,this._options.multisamplingSamples,e,this._width,this._height)}else{this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER,e,this._width,this._height)}this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.COLOR_ATTACHMENT0+i,this._cgl.gl.RENDERBUFFER,a);this._colorRenderbuffers[i]=a}this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._textureFrameBuffer);for(i=0;i<this._numRenderBuffers;i++){this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.COLOR_ATTACHMENT0+i,this._cgl.gl.TEXTURE_2D,this._colorTextures[i].tex,0)}if(this._options.depth){this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.DEPTH_ATTACHMENT,this._cgl.gl.TEXTURE_2D,this._textureDepth.tex,0)}this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._frameBuffer);let r=this._cgl.gl.DEPTH_COMPONENT32F;if(this._cgl.glSlowRenderer)r=this._cgl.gl.DEPTH_COMPONENT16;if(n){this._textureDepth.setSize(this._width,this._height);this._depthRenderbuffer=this._cgl.gl.createRenderbuffer();this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER,this._depthRenderbuffer);if(this._options.isFloatingPointTexture){if(this._options.multisampling)this._cgl.gl.renderbufferStorageMultisample(this._cgl.gl.RENDERBUFFER,this._options.multisamplingSamples,r,this._width,this._height);else this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER,r,this._width,this._height)}else if(this._options.multisampling){this._cgl.gl.renderbufferStorageMultisample(this._cgl.gl.RENDERBUFFER,this._options.multisamplingSamples,r,this._width,this._height)}else{this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER,r,this._width,this._height)}this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.DEPTH_ATTACHMENT,this._cgl.gl.RENDERBUFFER,this._depthRenderbuffer)}this._drawTargetArray.length=0;for(i=0;
30982i<this._numRenderBuffers;i++)this._drawTargetArray.push(this._cgl.gl.COLOR_ATTACHMENT0+i);if(!this._cgl.gl.isFramebuffer(this._textureFrameBuffer))this._log.warn("invalid framebuffer");const s=this._cgl.gl.checkFramebufferStatus(this._cgl.gl.FRAMEBUFFER);if(s!=this._cgl.gl.FRAMEBUFFER_COMPLETE){this._log.error("framebuffer incomplete: "+this.name,this);this._log.log("options",this._options);this._log.log("options pixelformat",this._options.pixelFormat);switch(s){case this._cgl.gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:this._log.warn("FRAMEBUFFER_INCOMPLETE_ATTACHMENT...",this);throw new Error("Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT");case this._cgl.gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:this._log.warn("FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");throw new Error("Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");case this._cgl.gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:this._log.warn("FRAMEBUFFER_INCOMPLETE_DIMENSIONS");throw new Error("Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS");case this._cgl.gl.FRAMEBUFFER_UNSUPPORTED:this._log.warn("FRAMEBUFFER_UNSUPPORTED");throw new Error("Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED");default:this.valid=false;this._log.error("incomplete framebuffer",s,this._frameBuffer);this._cgl.printError();this._frameBuffer=null;throw new Error("Incomplete framebuffer: "+s)}}this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,null);this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER,null)}renderStart(){if(this._disposed)return this._log.warn("disposed framebuffer renderStart...");this._cgl.checkFrameStarted("fb2 renderstart");this._cgl.pushModelMatrix();this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._frameBuffer);this._cgl.pushGlFrameBuffer(this._frameBuffer);this._cgl.pushFrameBuffer(this);this._cgl.pushPMatrix();this._cgl.pushViewPort(0,0,this._width,this._height);this._cgl.gl.drawBuffers(this._drawTargetArray);if(this._options.clear){this._cgl.gl.clearColor(0,0,0,0);this._cgl.gl.clear(this._cgl.gl.COLOR_BUFFER_BIT|this._cgl.gl.DEPTH_BUFFER_BIT)}}clear(){if(this._numRenderBuffers<=1){this._cgl.gl.bindFramebuffer(this._cgl.gl.READ_FRAMEBUFFER,this._frameBuffer);this._cgl.gl.bindFramebuffer(this._cgl.gl.DRAW_FRAMEBUFFER,this._textureFrameBuffer)}else this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._frameBuffer);this._cgl.gl.drawBuffers(this._drawTargetArray);for(let e=0;e<this._numRenderBuffers;e++){this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.COLOR_ATTACHMENT0+e,this._cgl.gl.TEXTURE_2D,this._colorTextures[e].tex,0);this._cgl.gl.clearBufferfv(this._cgl.gl.COLOR,e,this.clearColors[e])}this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,null)}renderEnd(){if(this._disposed)return this._log.warn("disposed framebuffer renderEnd...");this._cgl.popPMatrix();this._cgl.profileData.profileFramebuffer++;if(this._numRenderBuffers<=1){this._cgl.gl.bindFramebuffer(this._cgl.gl.READ_FRAMEBUFFER,this._frameBuffer);this._cgl.gl.bindFramebuffer(this._cgl.gl.DRAW_FRAMEBUFFER,this._textureFrameBuffer);this._cgl.gl.clearBufferfv(this._cgl.gl.COLOR,0,[0,0,0,1]);this._cgl.gl.blitFramebuffer(0,0,this._width,this._height,0,0,this._width,this._height,this._cgl.gl.COLOR_BUFFER_BIT|this._cgl.gl.DEPTH_BUFFER_BIT,this._cgl.gl.NEAREST)}else{this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this.Framebuffer2BlittingFramebuffer);this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.DEPTH_ATTACHMENT,this._cgl.gl.RENDERBUFFER,this._depthRenderbuffer);this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this.Framebuffer2FinalFramebuffer);this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.DEPTH_ATTACHMENT,this._cgl.gl.TEXTURE_2D,this._textureDepth.tex,0);for(let t=0;t<this._numRenderBuffers;t++){this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this.Framebuffer2BlittingFramebuffer);this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.COLOR_ATTACHMENT0,this._cgl.gl.RENDERBUFFER,this._colorRenderbuffers[t]);this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this.Framebuffer2FinalFramebuffer);this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.COLOR_ATTACHMENT0,this._cgl.gl.TEXTURE_2D,this._colorTextures[t].tex,0);this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,null);this._cgl.gl.bindFramebuffer(this._cgl.gl.READ_FRAMEBUFFER,this.Framebuffer2BlittingFramebuffer);this._cgl.gl.bindFramebuffer(this._cgl.gl.DRAW_FRAMEBUFFER,this.Framebuffer2FinalFramebuffer);let e=this._cgl.gl.COLOR_BUFFER_BIT;if(t==0)e|=this._cgl.gl.DEPTH_BUFFER_BIT;this._cgl.gl.blitFramebuffer(0,0,this._width,this._height,0,0,this._width,this._height,e,this._cgl.gl.NEAREST)}}this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._cgl.popGlFrameBuffer());this._cgl.popFrameBuffer();this._cgl.popModelMatrix();this._cgl.popViewPort();if(this._colorTextures[0].filter==u.FILTER_MIPMAP){for(let e=0;
30982e<this._numRenderBuffers;e++){this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D,this._colorTextures[e].tex);this._colorTextures[e].updateMipMap();this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D,null)}}}}const r=function(e){this.draw=function(e,t,i){}};const s=function(e){this.render=function(e,t){}};const o=function(e){this.render=function(e,t,i,n){}};class l{constructor(e,t,i,n,r,s,a,o,l,u){this._log=new h.Logger("cg_uniform");this._type=t;this._name=i;this._shader=e;this._value=1e-5;this._oldValue=null;this._port=null;this._structName=l;this._structUniformName=o;this._propertyName=u;if(this._shader._addUniform)this._shader._addUniform(this);this.needsUpdate=true;this.shaderType=null;this.comment=null;if(t=="f"){this.set=this.setValue=this.setValueF.bind(this);this.updateValue=this.updateValueF.bind(this)}else if(t=="f[]"){this.set=this.setValue=this.setValueArrayF.bind(this);this.updateValue=this.updateValueArrayF.bind(this)}else if(t=="2f[]"){this.set=this.setValue=this.setValueArray2F.bind(this);this.updateValue=this.updateValueArray2F.bind(this)}else if(t=="3f[]"){this.set=this.setValue=this.setValueArray3F.bind(this);this.updateValue=this.updateValueArray3F.bind(this)}else if(t=="4f[]"){this.set=this.setValue=this.setValueArray4F.bind(this);this.updateValue=this.updateValueArray4F.bind(this)}else if(t=="i"){this.set=this.setValue=this.setValueI.bind(this);this.updateValue=this.updateValueI.bind(this)}else if(t=="2i"){this.set=this.setValue=this.setValue2I.bind(this);this.updateValue=this.updateValue2I.bind(this)}else if(t=="3i"){this.set=this.setValue=this.setValue3I.bind(this);this.updateValue=this.updateValue3I.bind(this)}else if(t=="4i"){this.set=this.setValue=this.setValue4I.bind(this);this.updateValue=this.updateValue4I.bind(this)}else if(t=="b"){this.set=this.setValue=this.setValueBool.bind(this);this.updateValue=this.updateValueBool.bind(this)}else if(t=="4f"){this.set=this.setValue=this.setValue4F.bind(this);this.updateValue=this.updateValue4F.bind(this)}else if(t=="3f"){this.set=this.setValue=this.setValue3F.bind(this);this.updateValue=this.updateValue3F.bind(this)}else if(t=="2f"){this.set=this.setValue=this.setValue2F.bind(this);this.updateValue=this.updateValue2F.bind(this)}else if(t=="t"){this.set=this.setValue=this.setValueT.bind(this);this.updateValue=this.updateValueT.bind(this)}else if(t=="sampler"){if(this.setValueAny){this.set=this.setValue=this.setValueAny.bind(this);this.updateValue=this.updateValueAny.bind(this)}}else if(t=="tc"){this.set=this.setValue=this.setValueT.bind(this);this.updateValue=this.updateValueT.bind(this)}else if(t=="t[]"){this.set=this.setValue=this.setValueArrayT.bind(this);this.updateValue=this.updateValueArrayT.bind(this)}else if(t=="m4"||t=="m4[]"){this.set=this.setValue=this.setValueM4.bind(this);this.updateValue=this.updateValueM4.bind(this)}else{this._log.error("Unknown uniform type "+t,i,typeof this._shader)}if(typeof n=="object"&&n instanceof E.Port){this._port=n;this._value=this._port.get();if(r&&s&&a){if(!(r instanceof E.Port)||!(s instanceof E.Port)||!(a instanceof E.Port)){this._log.error("[cgl_uniform] mixed port/value parameter for vec4 ",this._name)}this._value=[0,0,0,0];this._port2=r;this._port3=s;this._port4=a;this._port.on("change",this.updateFromPort4f.bind(this));this._port2.on("change",this.updateFromPort4f.bind(this));this._port3.on("change",this.updateFromPort4f.bind(this));this._port4.on("change",this.updateFromPort4f.bind(this));this.updateFromPort4f()}else if(r&&s){if(!(r instanceof E.Port)||!(s instanceof E.Port)){this._log.error("[cgl_uniform] mixed port/value parameter for vec4 ",this._name)}this._value=[0,0,0];this._port2=r;this._port3=s;this._port.on("change",this.updateFromPort3f.bind(this));this._port2.on("change",this.updateFromPort3f.bind(this));this._port3.on("change",this.updateFromPort3f.bind(this));this.updateFromPort3f()}else if(r){if(!(r instanceof E.Port)){this._log.error("[cgl_uniform] mixed port/value parameter for vec4 ",this._name)}this._value=[0,0];this._port2=r;this._port.on("change",this.updateFromPort2f.bind(this));this._port2.on("change",this.updateFromPort2f.bind(this));this.updateFromPort2f()}else{this._port.on("change",this.updateFromPort.bind(this))}}else this._value=n;if(this._value==undefined){this._value=0}this.setValue(this._value);this.needsUpdate=true}getType(){return this._type}get type(){return this._type}get name(){return this._name}getName(){return this._name}getValue(){return this._value}getShaderType(){return this.shaderType}isStructMember(){return!!this._structName}updateFromPort4f(){this._value[0]=this._port.get();this._value[1]=this._port2.get();this._value[2]=this._port3.get();this._value[3]=this._port4.get();this.setValue(this._value)}updateFromPort3f(){this._value[0]=this._port.get();this._value[1]=this._port2.get();this._value[2]=this._port3.get();this.setValue(this._value)}updateFromPort2f(){this._value[0]=this._port.get();this._value[1]=this._port2.get();this.setValue(this._value)}updateFromPort(){this.setValue(this._port.get())}get port(){return this._port}}class c extends l{constructor(e,t,i,n,r,s,a,o,l,u){super(e,t,i,n,r,s,a,o,l,u);this._loc=-1;this._cgl=e._cgl}get name(){return this._name}copy(e){const t=new c(e,this._type,this._name,this._value,this._port2,this._port3,this._port4,this._structUniformName,this._structName,this._propertyName);t.shaderType=this.shaderType;return t}getGlslTypeString(){return c.glslTypeString(this._type)}_isValidLoc(){return this._loc!=-1}resetLoc(){this._loc=-1;this.needsUpdate=true}bindTextures(){}getLoc(){return this._loc}updateFromPort4f(){this._value[0]=this._port.get();this._value[1]=this._port2.get();this._value[2]=this._port3.get();this._value[3]=this._port4.get();this.setValue(this._value)}updateFromPort3f(){this._value[0]=this._port.get();this._value[1]=this._port2.get();this._value[2]=this._port3.get();this.setValue(this._value)}updateFromPort2f(){this._value[0]=this._port.get();this._value[1]=this._port2.get();this.setValue(this._value)}updateFromPort(){this.setValue(this._port.get())}updateValueF(){if(!this._isValidLoc())this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);else this.needsUpdate=false;this._shader.getCgl().gl.uniform1f(this._loc,this._value);this._cgl.profileData.profileUniformCount++}setValueF(e){if(e!=this._value){this.needsUpdate=true;this._value=e}}updateValueI(){if(!this._isValidLoc())this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);else this.needsUpdate=false;this._shader.getCgl().gl.uniform1i(this._loc,this._value);this._cgl.profileData.profileUniformCount++}updateValue2I(){if(!this._value)return;if(!this._isValidLoc()){this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);this._cgl.profileData.profileShaderGetUniform++;this._cgl.profileData.profileShaderGetUniformName=this._name}this._shader.getCgl().gl.uniform2i(this._loc,this._value[0],this._value[1]);this.needsUpdate=false;this._cgl.profileData.profileUniformCount++}updateValue3I(){if(!this._value)return;if(!this._isValidLoc()){this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);this._cgl.profileData.profileShaderGetUniform++;this._cgl.profileData.profileShaderGetUniformName=this._name}this._shader.getCgl().gl.uniform3i(this._loc,this._value[0],this._value[1],this._value[2]);this.needsUpdate=false;this._cgl.profileData.profileUniformCount++}updateValue4I(){if(!this._isValidLoc()){this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);this._cgl.profileData.profileShaderGetUniform++;this._cgl.profileData.profileShaderGetUniformName=this._name}this._shader.getCgl().gl.uniform4i(this._loc,this._value[0],this._value[1],this._value[2],this._value[3]);this._cgl.profileData.profileUniformCount++}setValueI(e){if(e!=this._value){this.needsUpdate=true;this._value=e}}setValue2I(e){if(!e)return;if(!this._oldValue){this._oldValue=[e[0]-1,1];this.needsUpdate=true}else if(e[0]!=this._oldValue[0]||e[1]!=this._oldValue[1]){this._oldValue[0]=e[0];this._oldValue[1]=e[1];this.needsUpdate=true}this._value=e}setValue3I(e){if(!e)return;if(!this._oldValue){this._oldValue=[e[0]-1,1,2];this.needsUpdate=true}else if(e[0]!=this._oldValue[0]||e[1]!=this._oldValue[1]||e[2]!=this._oldValue[2]){this._oldValue[0]=e[0];this._oldValue[1]=e[1];this._oldValue[2]=e[2];this.needsUpdate=true}this._value=e}setValue4I(e){this.needsUpdate=true;this._value=e||vec4.create()}updateValueBool(){if(!this._isValidLoc())this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);else this.needsUpdate=false;this._shader.getCgl().gl.uniform1i(this._loc,this._value?1:0);this._cgl.profileData.profileUniformCount++}setValueBool(e){if(e!=this._value){this.needsUpdate=true;this._value=e}}setValueArray4F(e){this.needsUpdate=true;this._value=e}updateValueArray4F(){if(!this._isValidLoc())this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);else this.needsUpdate=false;if(!this._value)return;this._shader.getCgl().gl.uniform4fv(this._loc,this._value);this._cgl.profileData.profileUniformCount++}setValueArray3F(e){this.needsUpdate=true;this._value=e}updateValueArray3F(){if(!this._isValidLoc())this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);else this.needsUpdate=false;if(!this._value)return;this._shader.getCgl().gl.uniform3fv(this._loc,this._value);this._cgl.profileData.profileUniformCount++}setValueArray2F(e){this.needsUpdate=true;this._value=e}updateValueArray2F(){if(!this._isValidLoc())this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);else this.needsUpdate=false;if(!this._value)return;this._shader.getCgl().gl.uniform2fv(this._loc,this._value);this._cgl.profileData.profileUniformCount++}setValueArrayF(e){this.needsUpdate=true;this._value=e}updateValueArrayF(){if(!this._isValidLoc())this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);else this.needsUpdate=false;if(!this._value)return;this._shader.getCgl().gl.uniform1fv(this._loc,this._value);this._cgl.profileData.profileUniformCount++}setValueArrayT(e){this.needsUpdate=true;this._value=e}updateValue3F(){if(!this._value)return;if(!this._isValidLoc()){this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);this._cgl.profileData.profileShaderGetUniform++;this._cgl.profileData.profileShaderGetUniformName=this._name}this._shader.getCgl().gl.uniform3f(this._loc,this._value[0],this._value[1],this._value[2]);this.needsUpdate=false;this._cgl.profileData.profileUniformCount++}setValue3F(e){if(!e)return;if(!this._oldValue){this._oldValue=[e[0]-1,1,2];this.needsUpdate=true}else if(e[0]!=this._oldValue[0]||e[1]!=this._oldValue[1]||e[2]!=this._oldValue[2]){this._oldValue[0]=e[0];this._oldValue[1]=e[1];this._oldValue[2]=e[2];this.needsUpdate=true}this._value=e}updateValue2F(){if(!this._value)return;if(!this._isValidLoc()){this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);this._cgl.profileData.profileShaderGetUniform++;this._cgl.profileData.profileShaderGetUniformName=this._name}this._shader.getCgl().gl.uniform2f(this._loc,this._value[0],this._value[1]);this.needsUpdate=false;this._cgl.profileData.profileUniformCount++}setValue2F(e){if(!e)return;if(!this._oldValue){this._oldValue=[e[0]-1,1];this.needsUpdate=true}else if(e[0]!=this._oldValue[0]||e[1]!=this._oldValue[1]){this._oldValue[0]=e[0];this._oldValue[1]=e[1];this.needsUpdate=true}this._value=e}updateValue4F(){if(!this._isValidLoc()){this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);this._cgl.profileData.profileShaderGetUniform++;this._cgl.profileData.profileShaderGetUniformName=this._name}if(!this._value){this._log.warn("no value for uniform",this._name,this);this._value=[0,0,0,0]}this.needsUpdate=false;this._shader.getCgl().gl.uniform4f(this._loc,this._value[0],this._value[1],this._value[2],this._value[3]);this._cgl.profileData.profileUniformCount++}setValue4F(e){if(typeof this.value=="number")this.value=vec4.create();if(!e)return;if(!this._oldValue){this._oldValue=[e[0]-1,1,2,3];this.needsUpdate=true}else if(e[0]!=this._oldValue[0]||e[1]!=this._oldValue[1]||e[2]!=this._oldValue[2]||e[3]!=this._oldValue[3]){this._oldValue[0]=e[0];this._oldValue[1]=e[1];this._oldValue[2]=e[2];this.needsUpdate=true}this._value=e}updateValueM4(){if(!this._isValidLoc()){this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);this._cgl.profileData.profileShaderGetUniform++;this._cgl.profileData.profileShaderGetUniformName=this._name}if(!this._value||this._value.length%16!=0)return console.log("this.name",this._name,this._value);this._shader.getCgl().gl.uniformMatrix4fv(this._loc,false,this._value);this._cgl.profileData.profileUniformCount++}setValueM4(e){this.needsUpdate=true;this._value=e||mat4.create()}updateValueArrayT(){if(!this._isValidLoc())this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);else this.needsUpdate=false;if(!this._value)return;this._shader.getCgl().gl.uniform1iv(this._loc,this._value);this._cgl.profileData.profileUniformCount++}updateValueT(){if(!this._isValidLoc()){this._loc=this._shader.getCgl().gl.getUniformLocation(this._shader.getProgram(),this._name);this._cgl.profileData.profileShaderGetUniform++;this._cgl.profileData.profileShaderGetUniformName=this._name}this._cgl.profileData.profileUniformCount++;this._shader.getCgl().gl.uniform1i(this._loc,this._value);this.needsUpdate=false}setValueT(e){this.needsUpdate=true;this._value=e}}c.glslTypeString=e=>{if(e=="f")return"float";if(e=="b")return"bool";if(e=="i")return"int";if(e=="2i")return"ivec2";if(e=="2f")return"vec2";if(e=="3f")return"vec3";if(e=="4f")return"vec4";if(e=="m4")return"mat4";if(e=="t")return"sampler2D";if(e=="tc")return"samplerCube";if(e=="3f[]")return null;if(e=="m4[]")return null;if(e=="f[]")return null;console.warn("[CGL UNIFORM] unknown glsl type string ",e)};const g={SHADERVAR_VERTEX_POSITION:"vPosition",SHADERVAR_VERTEX_NUMBER:"attrVertIndex",SHADERVAR_VERTEX_NORMAL:"attrVertNormal",SHADERVAR_VERTEX_TEXCOORD:"attrTexCoord",SHADERVAR_INSTANCE_MMATRIX:"instMat",SHADERVAR_VERTEX_COLOR:"attrVertColor",SHADERVAR_INSTANCE_INDEX:"instanceIndex",SHADERVAR_UNI_PROJMAT:"projMatrix",SHADERVAR_UNI_VIEWMAT:"viewMatrix",SHADERVAR_UNI_MODELMAT:"modelMatrix",SHADERVAR_UNI_NORMALMAT:"normalMatrix",SHADERVAR_UNI_INVVIEWMAT:"inverseViewMatrix",SHADERVAR_UNI_INVPROJMAT:"invProjMatrix",SHADERVAR_UNI_MATERIALID:"materialId",SHADERVAR_UNI_OBJECTID:"objectId",SHADERVAR_UNI_VIEWPOS:"camPos"};const f={BLEND_NONE:0,BLEND_NORMAL:1,BLEND_ADD:2,BLEND_SUB:3,BLEND_MUL:4};const d=180/Math.PI;const m=Math.PI/180;const p={MATH:{DEG2RAD:m,RAD2DEG:d},SHADER:g,BLEND_MODES:f};const A="\n";class _{_name="unknown";constructor(){}}const S={};S.lastMesh=null;class v extends _{#cgl=null;#geom=null;#bufVerticesIndizes=null;constructor(e,t,i={}){super();this.#cgl=e;let n=i||{};if(E.utils.isNumeric(n))n={glPrimitive:i};this._log=new h.Logger("cgl_mesh");this._bufVertexAttrib=null;this.#bufVerticesIndizes=this.#cgl.gl.createBuffer();this._indexType=this.#cgl.gl.UNSIGNED_SHORT;this._attributes=[];this._attribLocs={};this._lastShader=null;this._numInstances=0;this._glPrimitive=n.glPrimitive;this.opId=n.opId||"";this._preWireframeGeom=null;this.addVertexNumbers=false;this.feedBackAttributes=[];this.setGeom(t);this._feedBacks=[];this._feedBacksChanged=false;this._transformFeedBackLoc=-1;this._lastAttrUpdate=0;this.memFreed=false;this.#cgl.profileData.addHeavyEvent("mesh constructed",this._name);this._queryExt=null}get geom(){return this.#geom}get numInstances(){return this._numInstances}set numInstances(e){this.setNumInstances(e)}freeMem(){this.memFreed=true;for(let e=0;e<this._attributes.length;e++)this._attributes[e].floatArray=null}updateVertices(e){this.setAttribute(p.SHADER.SHADERVAR_VERTEX_POSITION,e.vertices,3);this._numVerts=e.vertices.length/3}setAttributePointer(t,i,n,r){for(let e=0;e<this._attributes.length;e++){if(this._attributes[e].name==t){if(!this._attributes[e].pointer)this._attributes[e].pointer=[];this._attributes[e].pointer.push({loc:-1,name:i,stride:n,offset:r,instanced:t==p.SHAD
30982ER.SHADERVAR_INSTANCE_MMATRIX})}}}getAttribute(t){for(let e=0;e<this._attributes.length;e++)if(this._attributes[e].name==t)return this._attributes[e]}setAttributeRange(e,t,i,n){if(!e)return;if(!i&&!n)return;if(!e.name)this._log.stack("no attrname?!");const r=this.#cgl.gl;r.bindBuffer(r.ARRAY_BUFFER,e.buffer);this.#cgl.profileData.profileMeshAttributes+=n-i||0;this.#cgl.profileData.profileSingleMeshAttribute[this._name]=this.#cgl.profileData.profileSingleMeshAttribute[this._name]||0;this.#cgl.profileData.profileSingleMeshAttribute[this._name]+=n-i||0;if(e.numItems<t.length/e.itemSize){this._resizeAttr(t,e)}if(n>t.length&&!this.warned){this.warned=true;this._log.warn(this.#cgl.canvas.id+" "+e.name+" buffersubdata out of bounds ?",t.length,n,i,e);return}r.bufferSubData(r.ARRAY_BUFFER,i*4,t,i,n-i)}_resizeAttr(e,t){const i=this.#cgl.gl;if(t.buffer)i.deleteBuffer(t.buffer);t.buffer=i.createBuffer();i.bindBuffer(i.ARRAY_BUFFER,t.buffer);this._bufferArray(e,t);t.numItems=e.length/t.itemSize}_bufferArray(e,t){let i=t.floatArray||null;if(!e)return;if(this.#cgl.debugOneFrame){console.log("_bufferArray",e.length,t.name)}if(!(e instanceof Float32Array)){if(t&&i&&i.length==e.length){i.set(e)}else{i=new Float32Array(e);if(this.#cgl.debugOneFrame){console.log("_bufferArray create new float32array",e.length,t.name)}if(e.length>1e4){this.#cgl.profileData.profileNonTypedAttrib++;this.#cgl.profileData.profileNonTypedAttribNames="("+this._name+":"+t.name+")"}}}else i=e;t.arrayLength=i.length;t.floatArray=null;this.#cgl.gl.bufferData(this.#cgl.gl.ARRAY_BUFFER,i,this.#cgl.gl.DYNAMIC_DRAW)}addAttribute(e,t,i,n){this.setAttribute(e,t,i,n)}setAttribute(e,t,i,n={}){if(!t){this._log.error("mesh addAttribute - no array given! "+e);throw new Error}let r=null;let s=false;let a=0;const o=t.length/i;this.#cgl.profileData.profileMeshAttributes+=o||0;if(typeof n=="function"){r=n}if(typeof n=="object"){if(n.cb)r=n.cb;if(n.instanced)s=n.instanced}if(e==p.SHADER.SHADERVAR_INSTANCE_MMATRIX)s=true;for(a=0;a<this._attributes.length;a++){const h=this._attributes[a];if(h.name==e){if(h.numItems===o){}else{this._resizeAttr(t,h)}this.#cgl.gl.bindBuffer(this.#cgl.gl.ARRAY_BUFFER,h.buffer);this._bufferArray(t,h);return h}}const l=this.#cgl.gl.createBuffer();this.#cgl.gl.bindBuffer(this.#cgl.gl.ARRAY_BUFFER,l);let u=this.#cgl.gl.FLOAT;if(n&&n.type)u=n.type;const h={buffer:l,name:e,cb:r,itemSize:i,numItems:o,startItem:0,instanced:s,type:u};this._bufferArray(t,h);if(e==p.SHADER.SHADERVAR_VERTEX_POSITION)this._bufVertexAttrib=h;this._attributes.push(h);this._attribLocs={};return h}getAttributes(){return this._attributes}updateTexCoords(e){if(e.texCoords&&e.texCoords.length>0){this.setAttribute(p.SHADER.SHADERVAR_VERTEX_TEXCOORD,e.texCoords,2)}else{const t=new Float32Array(Math.round(e.vertices.length/3*2));this.setAttribute(p.SHADER.SHADERVAR_VERTEX_TEXCOORD,t,2)}}updateNormals(e){if(e.vertexNormals&&e.vertexNormals.length>0){this.setAttribute(p.SHADER.SHADERVAR_VERTEX_NORMAL,e.vertexNormals,3)}else{const t=new Float32Array(Math.round(e.vertices.length));this.setAttribute(p.SHADER.SHADERVAR_VERTEX_NORMAL,t,3)}}_setVertexNumbers(e=null){if(!this._verticesNumbers||this._verticesNumbers.length!=this._numVerts||e){if(e)this._verticesNumbers=e;else{this._verticesNumbers=new Float32Array(this._numVerts);for(let e=0;e<this._numVerts;e++)this._verticesNumbers[e]=e}this.setAttribute(p.SHADER.SHADERVAR_VERTEX_NUMBER,this._verticesNumbers,1,(e,t,i)=>{if(!i.uniformNumVertices)i.uniformNumVertices=new c(i,"f","numVertices",this._numVerts);i.uniformNumVertices.setValue(this._numVerts)})}}setVertexIndices(t){if(!this.#bufVerticesIndizes){this._log.warn("no bufVerticesIndizes: "+this._name);return}if(t.length>0){if(t instanceof Float32Array)this._log.warn("vertIndices float32Array: "+this._name);for(let e=0;e<t.length;e++){if(t[e]>=this._numVerts){this._log.warn("invalid index in "+this._name,e,t[e]);return}}this.#cgl.gl.bindBuffer(this.#cgl.gl.ELEMENT_ARRAY_BUFFER,this.#bufVerticesIndizes);if(t.length>65535){this.vertIndicesTyped=new Uint32Array(t);this._indexType=this.#cgl.gl.UNSIGNED_INT}else if(t instanceof Uint32Array){this.vertIndicesTyped=t;this._indexType=this.#cgl.gl.UNSIGNED_INT}else if(!(t instanceof Uint16Array)){this.vertIndicesTyped=new Uint16Array(t);this._indexType=this.#cgl.gl.UNSIGNED_SHORT}else this.vertIndicesTyped=t;this.#cgl.gl.bufferData(this.#cgl.gl.ELEMENT_ARRAY_BUFFER,this.vertIndicesTyped,this.#cgl.gl.DYNAMIC_DRAW);this.#bufVerticesIndizes.itemSize=1;this.#bufVerticesIndizes.numItems=t.length}else this.#bufVerticesIndizes.numItems=0}setGeom(e,t=false){this.#geom=e;if(e.glPrimitive!=null)this._glPrimitive=e.glPrimitive;if(this.#geom&&this.#geom.name)this._name="mesh "+this.#geom.name;S.lastMesh=null;this.#cgl.profileData.profileMeshSetGeom++;this._disposeAttributes();this.updateVertices(this.#geom);this.setVertexIndices(this.#geom.verticesIndices);if(this.addVertexNumbers)this._setVertexNumbers();const i=this.#geom.getAttributes();const n={texCoords:p.SHADER.SHADERVAR_VERTEX_TEXCOORD,vertexNormals:p.SHADER.SHADERVAR_VERTEX_NORMAL,vertexColors:p.SHADER.SHADERVAR_VERTEX_COLOR,tangents:"attrTangent",biTangents:"attrBiTangent"};for(const r in i)if(i[r].data&&i[r].data.length)this.setAttribute(n[r]||r,i[r].data,i[r].itemSize);if(t){this.#geom=null}}_preBind(t){for(let e=0;e<this._attributes.length;e++)if(this._attributes[e].cb)this._attributes[e].cb(this._attributes[e],this.#geom,t)}_checkAttrLengths(){if(this.memFreed)return;for(let e=0;e<this._attributes.length;e++){if(this._attributes[e].arrayLength/this._attributes[e].itemSize<this._attributes[0].arrayLength/this._attributes[0].itemSize){let e="unknown";if(this.#geom)e=this.#geom.name}}}_bind(t){if(!t)return;if(!t.isValid())return;let i=[];if(this._attribLocs[t.id])i=this._attribLocs[t.id];else this._attribLocs[t.id]=i;this._lastShader=t;if(t.lastCompile>this._lastAttrUpdate||i.length!=this._attributes.length){this._lastAttrUpdate=t.lastCompile;for(let e=0;e<this._attributes.length;e++)i[e]=-1}for(let e=0;e<this._attributes.length;e++){const n=this._attributes[e];if(i[e]==-1){if(n._attrLocationLastShaderTime!=t.lastCompile){n._attrLocationLastShaderTime=t.lastCompile;i[e]=this.#cgl.glGetAttribLocation(t.getProgram(),n.name);this.#cgl.profileData.profileAttrLoc++}}if(i[e]!=-1){this.#cgl.gl.enableVertexAttribArray(i[e]);this.#cgl.gl.bindBuffer(this.#cgl.gl.ARRAY_BUFFER,n.buffer);if(n.instanced){if(n.itemSize<=4){if(!n.itemSize||n.itemSize==0)this._log.warn("instanced attrib itemsize error",this.#geom.name,n);this.#cgl.gl.vertexAttribPointer(i[e],n.itemSize,n.type,false,n.itemSize*4,0);this.#cgl.gl.vertexAttribDivisor(i[e],1)}else if(n.itemSize==16){const r=16*4;this.#cgl.gl.vertexAttribPointer(i[e],4,n.type,false,r,0);this.#cgl.gl.enableVertexAttribArray(i[e]+1);this.#cgl.gl.vertexAttribPointer(i[e]+1,4,n.type,false,r,4*4*1);this.#cgl.gl.enableVertexAttribArray(i[e]+2);this.#cgl.gl.vertexAttribPointer(i[e]+2,4,n.type,false,r,4*4*2);this.#cgl.gl.enableVertexAttribArray(i[e]+3);this.#cgl.gl.vertexAttribPointer(i[e]+3,4,n.type,false,r,4*4*3);this.#cgl.gl.vertexAttribDivisor(i[e],1);this.#cgl.gl.vertexAttribDivisor(i[e]+1,1);this.#cgl.gl.vertexAttribDivisor(i[e]+2,1);this.#cgl.gl.vertexAttribDivisor(i[e]+3,1)}else{this._log.warn("unknown instance attrib size",n.name)}}else{if(!n.itemSize||n.itemSize==0)this._log.warn("attrib itemsize error",this._name,n);this.#cgl.gl.vertexAttribPointer(i[e],n.itemSize,n.type,false,n.itemSize*4,0);if(n.pointer){for(let e=0;e<n.pointer.length;e++){const s=n.pointer[e];
30982if(s.loc==-1)s.loc=this.#cgl.glGetAttribLocation(t.getProgram(),s.name);this.#cgl.profileData.profileAttrLoc++;this.#cgl.gl.enableVertexAttribArray(s.loc);this.#cgl.gl.vertexAttribPointer(s.loc,n.itemSize,n.type,false,s.stride,s.offset)}}if(this.bindFeedback)this.bindFeedback(n)}}}if(this.#bufVerticesIndizes&&this.#bufVerticesIndizes.numItems!==0)this.#cgl.gl.bindBuffer(this.#cgl.gl.ELEMENT_ARRAY_BUFFER,this.#bufVerticesIndizes)}unBind(){const e=this._lastShader;this._lastShader=null;if(!e)return;let t=[];if(this._attribLocs[e.id])t=this._attribLocs[e.id];else this._attribLocs[e.id]=t;S.lastMesh=null;for(let e=0;e<this._attributes.length;e++){if(this._attributes[e].instanced){if(this._attributes[e].itemSize<=4){if(t[e]!=-1)this.#cgl.gl.vertexAttribDivisor(t[e],0);if(t[e]>=0)this.#cgl.gl.disableVertexAttribArray(t[e])}else{this.#cgl.gl.vertexAttribDivisor(t[e],0);this.#cgl.gl.vertexAttribDivisor(t[e]+1,0);this.#cgl.gl.vertexAttribDivisor(t[e]+2,0);this.#cgl.gl.vertexAttribDivisor(t[e]+3,0);this.#cgl.gl.disableVertexAttribArray(t[e]+1);this.#cgl.gl.disableVertexAttribArray(t[e]+2);this.#cgl.gl.disableVertexAttribArray(t[e]+3)}}if(t[e]!=-1)this.#cgl.gl.disableVertexAttribArray(t[e])}}meshChanged(){return this.#cgl.lastMesh&&this.#cgl.lastMesh!=this}printDebug(){console.log("--attributes");for(let e=0;e<this._attributes.length;e++){console.log("attribute "+e+" "+this._attributes[e].name)}}setNumVertices(e){this._bufVertexAttrib.numItems=e}getNumVertices(){return this._bufVertexAttrib.numItems}setNumIndices(e){this.#bufVerticesIndizes.numItems=e}getNumIndices(){return this.#bufVerticesIndizes.numItems}render(i){if(this.#cgl.aborted)return;i=i||this.#cgl.getShader();if(!i){return console.log("shader not valid")}if(!i.isValid()){i=this.#cgl.getErrorShader()}this._checkAttrLengths();if(this.#geom){if(this._preWireframeGeom&&!i.wireframe&&!this.#geom.isIndexed()){this.setGeom(this._preWireframeGeom);this._preWireframeGeom=null}if(i.wireframe){let e=false;if(this.#geom.isIndexed()){if(!this._preWireframeGeom){this._preWireframeGeom=this.#geom;this.#geom=this.#geom.copy()}this.#geom.unIndex();e=true}if(!this.#geom.getAttribute("attrBarycentric")){if(!this._preWireframeGeom){this._preWireframeGeom=this.#geom;this.#geom=this.#geom.copy()}e=true;this.#geom.calcBarycentric()}if(e)this.setGeom(this.#geom)}}let e=false;if(S.lastMesh!=this){if(S.lastMesh)S.lastMesh.unBind();e=true}if(e)this._preBind(i);if(!i.bind())return;this._bind(i);if(this.addVertexNumbers)this._setVertexNumbers();S.lastMesh=this;let t=this.#cgl.gl.TRIANGLES;if(this._glPrimitive!==undefined)t=this._glPrimitive;if(i.glPrimitive!==null)t=i.glPrimitive;let n=1;let r=this.#cgl.profileData.doProfileGlQuery;let s=false;if(r){let e=this._name+" - "+i.getName()+" #"+i.id;if(this._numInstances)e+=" instanced "+this._numInstances+"x";let t=this.#cgl.profileData.glQueryData[e];if(!t)t={id:e,num:0};if(i.opId)t.shaderOp=i.opId;if(this.opId)t.meshOp=this.opId;this.#cgl.profileData.glQueryData[e]=t;if(!this._queryExt&&this._queryExt!==false)this._queryExt=this.#cgl.enableExtension("EXT_disjoint_timer_query_webgl2")||false;if(this._queryExt){if(t._drawQuery){const a=this.#cgl.gl.getQueryParameter(t._drawQuery,this.#cgl.gl.QUERY_RESULT_AVAILABLE);if(a){const o=this.#cgl.gl.getQueryParameter(t._drawQuery,this.#cgl.gl.QUERY_RESULT);const l=o/1e6;t._times=t._times||0;t._times+=l;t._numcount++;t.when=performance.now();t._drawQuery=null;t.queryStarted=false}}if(!t.queryStarted){t._drawQuery=this.#cgl.gl.createQuery();this.#cgl.gl.beginQuery(this._queryExt.TIME_ELAPSED_EXT,t._drawQuery);s=t.queryStarted=true}}}if(this.hasFeedbacks&&this.hasFeedbacks())this.drawFeedbacks(i,t);else if(!this.#bufVerticesIndizes||this.#bufVerticesIndizes.numItems===0){if(t==this.#cgl.gl.TRIANGLES)n=3;if(this._numInstances===0)this.#cgl.gl.drawArrays(t,this._bufVertexAttrib.startItem,this._bufVertexAttrib.numItems-this._bufVertexAttrib.startItem);else this.#cgl.gl.drawArraysInstanced(t,this._bufVertexAttrib.startItem,this._bufVertexAttrib.numItems,this._numInstances)}else{if(t==this.#cgl.gl.TRIANGLES)n=3;if(this._numInstances===0){this.#cgl.gl.drawElements(t,this.#bufVerticesIndizes.numItems,this._indexType,0)}else{this.#cgl.gl.drawElementsInstanced(t,this.#bufVerticesIndizes.numItems,this._indexType,0,this._numInstances)}}if(this.#cgl.debugOneFrame&&this.#cgl.gl.getError()!=this.#cgl.gl.NO_ERROR){this._log.error("mesh draw gl error");this._log.error("mesh",this);this._log.error("shader",i);const u=[];for(let e=0;e<this.#cgl.gl.getProgramParameter(i.getProgram(),this.#cgl.gl.ACTIVE_ATTRIBUTES);e++){const h=this.#cgl.gl.getActiveAttrib(i.getProgram(),e).name;this._log.error("attrib ",h)}}this.#cgl.profileData.profileMeshNumElements+=this._bufVertexAttrib.numItems/n*(this._numInstances||1);this.#cgl.profileData.profileMeshDraw++;if(r&&s){this.#cgl.gl.endQuery(this._queryExt.TIME_ELAPSED_EXT)}this.#cgl.printError("mesh render "+this._name);this.unBind()}
30982setNumInstances(t){t=Math.max(0,t);if(this._numInstances!=t){this._numInstances=t;const i=new Float32Array(t);for(let e=0;e<t;e++)i[e]=e;this.setAttribute(p.SHADER.SHADERVAR_INSTANCE_INDEX,i,1,{instanced:true})}}_disposeAttributes(){if(!this._attributes)return;for(let e=0;e<this._attributes.length;e++){if(this._attributes[e].buffer){this.#cgl.gl.deleteBuffer(this._attributes[e].buffer);this._attributes[e].buffer=null}}this._attributes.length=0}dispose(){if(this.#cgl.aborted)return;if(this._bufVertexAttrib&&this._bufVertexAttrib.buffer)this.#cgl.gl.deleteBuffer(this._bufVertexAttrib.buffer);if(this.#bufVerticesIndizes)this.#cgl.gl.deleteBuffer(this.#bufVerticesIndizes);this.#bufVerticesIndizes=null;this._disposeAttributes()}}const w=CABLES.GLMatrix;class x{constructor(e){this._init();this._first=true;this._wireMesh=null;if(e)this.applyGeom(e)}_init(){this._max=[-0,-0,-0];this._min=[0,0,0];this._center=[0,0,0];this._size=[0,0,0];this._maxAxis=0;this._first=true}get maxAxis(){return this._maxAxis||1}get size(){return this._size}get center(){return this._center}get x(){return this._center[0]}get y(){return this._center[1]}get z(){return this._center[2]}get minX(){return this._min[0]}get minY(){return this._min[1]}get minZ(){return this._min[2]}get maxX(){return this._max[0]}get maxY(){return this._max[1]}get maxZ(){return this._max[2]}apply(e){return this.applyGeom(e)}applyGeom(t){if(!t)return;if(t instanceof x){const e=t;this.applyPos(e.maxX,e.maxY,e.maxZ);this.applyPos(e.minX,e.minY,e.minZ)}else{if(t.isGeometry)for(let e=0;e<t.vertices.length;e+=3)this.applyPos(t.vertices[e],t.vertices[e+1],t.vertices[e+2])}this.calcCenterSize()}copy(){return new x(this)}get changed(){return!(this._max[0]==-Number.MAX_VALUE&&this._max[1]==-Number.MAX_VALUE&&this._max[2]==-Number.MAX_VALUE)}applyPos(e,t,i){if(e==Number.MAX_VALUE||e==-Number.MAX_VALUE||t==Number.MAX_VALUE||t==-Number.MAX_VALUE||i==Number.MAX_VALUE||i==-Number.MAX_VALUE)return;if(!E.utils.isNumeric(e)||!E.utils.isNumeric(t)||!E.utils.isNumeric(i))return;if(this._first){this._max[0]=e;this._max[1]=t;this._max[2]=i;this._min[0]=e;this._min[1]=t;this._min[2]=i;this._first=false;return}this._max[0]=Math.max(this._max[0],e);this._max[1]=Math.max(this._max[1],t);this._max[2]=Math.max(this._max[2],i);this._min[0]=Math.min(this._min[0],e);this._min[1]=Math.min(this._min[1],t);this._min[2]=Math.min(this._min[2],i)}calcCenterSize(){if(this._first)return;this._size[0]=this._max[0]-this._min[0];this._size[1]=this._max[1]-this._min[1];this._size[2]=this._max[2]-this._min[2];this._center[0]=(this._min[0]+this._max[0])/2;this._center[1]=(this._min[1]+this._max[1])/2;this._center[2]=(this._min[2]+this._max[2])/2;this._maxAxis=Math.max(this._size[2],Math.max(this._size[0],this._size[1]))}mulMat4(e){if(this._first){this._max[0]=0;this._max[1]=0;this._max[2]=0;this._min[0]=0;this._min[1]=0;this._min[2]=0;this._first=false}w.vec3.transformMat4(this._max,this._max,e);w.vec3.transformMat4(this._min,this._min,e);this.calcCenterSize()}render(e,t,i){if(!this._wireMesh)this._wireMesh=new CGL.WireCube(e);e.pushModelMatrix();w.mat4.translate(e.mMatrix,e.mMatrix,this._center);if(CABLES.UI&&i){CABLES.UI.OverlayMeshes.drawCube(i,this._size[0]/2,this._size[1]/2,this._size[2]/2)}e.popModelMatrix()}}class b{isGeometry=true;constructor(e){this.name=e||"unknown";this._log=new h.Logger("cgl_geometry");this.faceVertCount=3;this.glPrimitive=null;this._attributes={};this._vertices=[];this.verticesIndices=[];this.morphTargets=[]}get vertices(){return this._vertices}set vertices(e){this.setVertices(e)}get texCoords(){const e=this.getAttribute("texCoords");if(!e)return[];return e.data}set texCoords(e){this.setAttribute("texCoords",e,2)}get vertexNormals(){const e=this.getAttribute("vertexNormals");if(!e)return[];return e.data}set vertexNormals(e){this.setAttribute("vertexNormals",e,3)}get tangents(){const e=this.getAttribute("tangents");if(!e)return[];return e.data}set tangents(e){this.setAttribute("tangents",e,3)}get biTangents(){const e=this.getAttribute("biTangents");if(!e)return[];return e.data}set biTangents(e){this.setAttribute("biTangents",e,3)}get vertexColors(){const e=this.getAttribute("vertexColors");if(!e)return[];return e.data}set vertexColors(e){this.setAttribute("vertexColors",e,4)}clear(){this._vertices=new Float32Array([]);this.verticesIndices=[];this.texCoords=new Float32Array([]);this.vertexNormals=new Float32Array([]);this.tangents=[];this.biTangents=[];this._attributes={}}getAttributes(){return this._attributes}
30982getAttribute(t){for(const e in this._attributes){if(this._attributes[e].name==t)return this._attributes[e]}return null}setAttribute(e,t,i){let n="";if(!i||i>4){this._log.warn("itemsize wrong?",i,e);this._log.stack("itemsize");i=3}if(i==1)n="float";else if(i==2)n="vec2";else if(i==3)n="vec3";else if(i==4)n="vec4";const r={name:e,data:t,itemSize:i,type:n};this._attributes[e]=r}copyAttribute(e,t){const i=this.getAttribute(e);t.setAttribute(e,new Float32Array(i.data),i.itemSize)}setVertices(e){if(e instanceof Float32Array)this._vertices=e;else this._vertices=new Float32Array(e)}setTexCoords(e){if(e instanceof Float32Array)this.texCoords=e;else this.texCoords=new Float32Array(e)}calcNormals(e){const t={smooth:e};this.calculateNormals(t)}flipNormals(t,i,n){let r=w.vec3.create();if(t==undefined)t=1;if(i==undefined)i=1;if(n==undefined)n=1;for(let e=0;e<this.vertexNormals.length;e+=3){w.vec3.set(r,this.vertexNormals[e+0],this.vertexNormals[e+1],this.vertexNormals[e+2]);r[0]*=-t;r[1]*=-i;r[2]*=-n;w.vec3.normalize(r,r);this.vertexNormals[e+0]=r[0];this.vertexNormals[e+1]=r[1];this.vertexNormals[e+2]=r[2]}}getNumTriangles(){if(this.verticesIndices&&this.verticesIndices.length)return this.verticesIndices.length/3;return this.vertices.length/3}flipVertDir(){const t=[];t.length=this.verticesIndices.length;for(let e=0;e<this.verticesIndices.length;e+=3){t[e]=this.verticesIndices[e+2];t[e+1]=this.verticesIndices[e+1];t[e+2]=this.verticesIndices[e]}this.verticesIndices=t}setPointVertices(t){if(t.length%3!==0){this._log.error("SetPointVertices: Array must be multiple of three.");return}if(!(t instanceof Float32Array))this.vertices=new Float32Array(t);else this.vertices=t;if(!(this.texCoords instanceof Float32Array))this.texCoords=new Float32Array(t.length/3*2);this.verticesIndices.length=t.length/3;for(let e=0;e<t.length/3;e++){this.verticesIndices[e]=e;this.texCoords[e*2]=0;this.texCoords[e*2+1]=0}}merge(t){if(!t)return;if(this.isIndexed()!=t.isIndexed()){if(this.isIndexed()){this.unIndex(false,true)}if(t.isIndexed()){const e=t.copy();e.unIndex(false,true);t=e}}const i=this.verticesIndices.length;const n=this._vertices.length/3;this.verticesIndices.length+=t.verticesIndices.length;for(let e=0;e<t.verticesIndices.length;e++)this.verticesIndices[i+e]=t.verticesIndices[e]+n;this.vertices=E.utils.float32Concat(this._vertices,t.vertices);this.texCoords=E.utils.float32Concat(this.texCoords,t.texCoords);this.vertexNormals=E.utils.float32Concat(this.vertexNormals,t.vertexNormals);this.tangents=E.utils.float32Concat(this.tangents,t.tangents);this.biTangents=E.utils.float32Concat(this.biTangents,t.biTangents)}copy(){const t=new b(this.name+" copy");t.faceVertCount=this.faceVertCount;t.glPrimitive=this.glPrimitive;t.setVertices(this._vertices.slice(0));if(this.verticesIndices){t.verticesIndices.length=this.verticesIndices.length;for(let e=0;e<this.verticesIndices.length;e++)t.verticesIndices[e]=this.verticesIndices[e]}for(let e in this._attributes)this.copyAttribute(e,t);t.morphTargets.length=this.morphTargets.length;for(let e=0;e<this.morphTargets.length;e++)t.morphTargets[e]=this.morphTargets[e];return t}calculateNormals(t=null){t=t||{};if(t.smooth===false)this.unIndex();const i=w.vec3.create();const n=w.vec3.create();const r=w.vec3.create();function s(e){w.vec3.subtract(i,e[0],e[1]);w.vec3.subtract(n,e[0],e[2]);w.vec3.cross(r,i,n);w.vec3.normalize(r,r);if(t&&t.forceZUp){if(r[2]<0){r[0]*=-1;r[1]*=-1;r[2]*=-1}}return r}this.getVertexVec=function(e){const t=[0,0,0];t[0]=this.vertices[e*3+0];t[1]=this.vertices[e*3+1];t[2]=this.vertices[e*3+2];return t};if(!(this.vertexNormals instanceof Float32Array)||this.vertexNormals.length!=this.vertices.length)this.vertexNormals=new Float32Array(this.vertices.length);for(let e=0;e<this.vertices.length;e++){this.vertexNormals[e]=0}if(!this.isIndexed()){const a=[];for(let e=0;e<this.vertices.length;e+=9){const o=[[this.vertices[e+0],this.vertices[e+1],this.vertices[e+2]],[this.vertices[e+3],this.vertices[e+4],this.vertices[e+5]],[this.vertices[e+6],this.vertices[e+7],this.vertices[e+8]]];const l=s(o);a.push(l[0],l[1],l[2],l[0],l[1],l[2],l[0],l[1],l[2])}this.vertexNormals=a}else{const u=[];u.length=Math.floor(this.verticesIndices.length/3);for(let e=0;e<this.verticesIndices.length;e+=3){const o=[this.getVertexVec(this.verticesIndices[e+0]),this.getVertexVec(this.verticesIndices[e+1]),this.getVertexVec(this.verticesIndices[e+2])];u[e/3]=s(o);this.vertexNormals[this.verticesIndices[e+0]*3+0]+=u[e/3][0];this.vertexNormals[this.verticesIndices[e+0]*3+1]+=u[e/3][1];this.vertexNormals[this.verticesIndices[e+0]*3+2]+=u[e/3][2];this.vertexNormals[this.verticesIndices[e+1]*3+0]+=u[e/3][0];this.vertexNormals[this.verticesIndices[e+1]*3+1]+=u[e/3][1];this.vertexNormals[this.verticesIndices[e+1]*3+2]+=u[e/3][2];this.vertexNormals[this.verticesIndices[e+2]*3+0]+=u[e/3][0];this.vertexNormals[this.verticesIndices[e+2]*3+1]+=u[e/3][1];this.vertexNormals[this.verticesIndices[e+2]*3+2]+=u[e/3][2]}for(let t=0;t<this.verticesIndices.length;t+=3){for(let e=0;e<3;e++){const h=[this.vertexNormals[this.verticesIndices[t+e]*3+0],this.vertexNormals[this.verticesIndices[t+e]*3+1],this.vertexNormals[this.verticesIndices[t+e]*3+2]];w.vec3.normalize(h,h);this.vertexNormals[this.verticesIndices[t+e]*3+0]=h[0];this.vertexNormals[this.verticesIndices[t+e]*3+1]=h[1];this.vertexNormals[this.verticesIndices[t+e]*3+2]=h[2]}}}}calcTangentsBitangents(){if(!this.vertices.length){return}if(!this.vertexNormals.length){return}if(!this.texCoords.length){const b=this.vertices.length/3*2;this.texCoords=new Float32Array(b);for(let e=0;e<b;e+=1)this.texCoords[e]=0}if(!this.verticesIndices||!this.verticesIndices.length){return}if(this.verticesIndices.length%3!==0){this._log.error("Vertex indices mismatch!");return}const t=this.verticesIndices.length/3;const i=this.vertices.length/3;this.tangents=new Float32Array(this.vertexNormals.length);this.biTangents=new Float32Array(this.vertexNormals.length);const n=[];n.length=i*2;const r=w.vec3.create();const s=w.vec3.create();const a=w.vec3.create();const o=w.vec2.create();const l=w.vec2.create();const u=w.vec2.create();const h=w.vec3.create();const c=w.vec3.create();for(let e=0;e<t;e+=1){const T=this.verticesIndices[e*3];const E=this.verticesIndices[e*3+1];const A=this.verticesIndices[e*3+2];w.vec3.set(r,this.vertices[T*3],this.vertices[T*3+1],this.vertices[T*3+2]);w.vec3.set(s,this.vertices[E*3],this.vertices[E*3+1],this.vertices[E*3+2]);w.vec3.set(a,this.vertices[A*3],this.vertices[A*3+1],this.vertices[A*3+2]);w.vec2.set(o,this.texCoords[T*2],this.texCoords[T*2+1]);w.vec2.set(l,this.texCoords[E*2],this.texCoords[E*2+1]);w.vec2.set(u,this.texCoords[A*2],this.texCoords[A*2+1]);const S=s[0]-r[0];const O=a[0]-r[0];const C=s[1]-r[1];const R=a[1]-r[1];const I=s[2]-r[2];const F=a[2]-r[2];const M=l[0]-o[0];const y=u[0]-o[0];const N=l[1]-o[1];const P=u[1]-o[1];const L=1/(M*P-y*N);w.vec3.set(h,(P*S-N*O)*L,(P*C-N*R)*L,(P*I-N*F)*L);w.vec3.set(c,(M*O-y*S)*L,(M*R-y*C)*L,(M*F-y*I)*L);n[T]=h;n[E]=h;n[A]=h;n[T+i]=c;n[E+i]=c;n[A+i]=c}const g=w.vec3.create();const f=w.vec3.create();const d=w.vec3.create();const m=w.vec3.create();const p=w.vec3.create();const _=w.vec3.create();const v=w.vec3.create();const x=w.vec3.create();for(let e=0;e<i;e+=1){if(!n[e])continue;w.vec3.set(g,this.vertexNormals[e*3],this.vertexNormals[e*3+1],this.vertexNormals[e*3+2]);w.vec3.set(f,n[e][0],n[e][1],n[e][2]);const D=w.vec3.dot(g,f);w.vec3.scale(p,g,D);w.vec3.subtract(_,f,p);w.vec3.normalize(x,_);w.vec3.cross(v,g,f);const B=1;
30982w.vec3.scale(d,x,1/B);w.vec3.cross(m,g,d);this.tangents[e*3+0]=d[0];this.tangents[e*3+1]=d[1];this.tangents[e*3+2]=d[2];this.biTangents[e*3+0]=m[0];this.biTangents[e*3+1]=m[1];this.biTangents[e*3+2]=m[2]}}isIndexed(){if(this._vertices.length==0)return true;return this.verticesIndices.length!=0}unIndex(e=false,t=false){const i=[];const n=[];let r=0;for(let e in this._attributes){const s=this._attributes[e];let i=[];for(let t=0;t<this.verticesIndices.length;t+=3){for(let e=0;e<3;e++){if(s.itemSize==3)i.push(s.data[this.verticesIndices[t+e]*3+0],s.data[this.verticesIndices[t+e]*3+1],s.data[this.verticesIndices[t+e]*3+2]);else if(s.itemSize==4)i.push(s.data[this.verticesIndices[t+e]*4+0],s.data[this.verticesIndices[t+e]*4+1],s.data[this.verticesIndices[t+e]*4+2],s.data[this.verticesIndices[t+e]*4+3]);else if(s.itemSize==2)i.push(s.data[this.verticesIndices[t+e]*2+0],s.data[this.verticesIndices[t+e]*2+1]);else if(s.itemSize==1)i.push(s.data[this.verticesIndices[t+e]]);else this._log.warn("unknown attr",s)}}this.setAttribute(s.name,i,s.itemSize)}for(let e=0;e<this.verticesIndices.length;e+=3){i.push(this.vertices[this.verticesIndices[e+0]*3+0],this.vertices[this.verticesIndices[e+0]*3+1],this.vertices[this.verticesIndices[e+0]*3+2]);n.push(r);r++;i.push(this.vertices[this.verticesIndices[e+1]*3+0],this.vertices[this.verticesIndices[e+1]*3+1],this.vertices[this.verticesIndices[e+1]*3+2]);n.push(r);r++;i.push(this.vertices[this.verticesIndices[e+2]*3+0],this.vertices[this.verticesIndices[e+2]*3+1],this.vertices[this.verticesIndices[e+2]*3+2]);n.push(r);r++}this.vertices=i;this.verticesIndices=[];if(e)this.verticesIndices=n;if(!t)this.calculateNormals()}calcBarycentric(){let t=[];t.length=this.vertices.length;for(let e=0;e<this.vertices.length;e++)t[e]=0;let i=0;for(let e=0;e<this.vertices.length;e+=3){t[e+i]=1;i++;if(i==3)i=0}this.setAttribute("attrBarycentric",t,3)}getBounds(){return new x(this)}center(e,t,i){if(e===undefined){e=true;t=true;i=true}let n=0;const r=this.getBounds();const s=[r.minX+(r.maxX-r.minX)/2,r.minY+(r.maxY-r.minY)/2,r.minZ+(r.maxZ-r.minZ)/2];for(n=0;n<this.vertices.length;n+=3){if(this.vertices[n+0]==this.vertices[n+0]){if(e)this.vertices[n+0]-=s[0];if(t)this.vertices[n+1]-=s[1];if(i)this.vertices[n+2]-=s[2]}}return s}mapTexCoords2d(){const t=this.getBounds();const i=this.vertices.length/3;this.texCoords=new Float32Array(i*2);for(let e=0;e<i;e++){const n=this.vertices[e*3+0];const r=this.vertices[e*3+1];this.texCoords[e*2+0]=n/(t.maxX-t.minX)+.5;this.texCoords[e*2+1]=1-r/(t.maxY-t.minY)+.5}}getInfoOneLine(){let e="";if(this.faceVertCount==3&&this.verticesIndices)e+=this.verticesIndices.length/3;else e+=0;e+=" tris ";if(this.vertices)e+=this.vertices.length/3;else e+=0;e+=" verts";return e}getInfo(){const e={};e.name=this.name;e.class=this.constructor.name;if(this.faceVertCount==3&&this.verticesIndices)e.numFaces=this.verticesIndices.length/3;else e.numFaces=0;if(this.verticesIndices&&this.verticesIndices.length)e.indices=this.verticesIndices.length;if(this.vertices)e.numVerts=this.vertices.length/3;else e.numVerts=0;if(this.vertexNormals)e.numNormals=this.vertexNormals.length/3;else e.numNormals=0;if(this.texCoords)e.numTexCoords=this.texCoords.length/2;else e.numTexCoords=0;if(this.tangents)e.numTangents=this.tangents.length/3;else e.numTangents=0;if(this.biTangents)e.numBiTangents=this.biTangents.length/3;else e.numBiTangents=0;if(this.biTangents)e.numBiTangents=this.biTangents.length/3;else e.numBiTangents=0;if(this.vertexColors)e.numVertexColors=this.vertexColors.length/4;else e.numVertexColors=0;if(this.getAttributes())e.numAttribs=Object.keys(this.getAttributes()).length;else e.numAttribs=0;e.isIndexed=this.isIndexed();return e}}b.buildFromFaces=function(t,e,i){const n=[];const r=[];for(let e=0;e<t.length;e+=3){const a=t[e+0];const o=t[e+1];const l=t[e+2];const u=[-1,-1,-1];if(i)for(let e=0;e<n.length;e+=3){if(n[e+0]==a[0]&&n[e+1]==a[1]&&n[e+2]==a[2])u[0]=e/3;if(n[e+0]==o[0]&&n[e+1]==o[1]&&n[e+2]==o[2])u[1]=e/3;if(n[e+0]==l[0]&&n[e+1]==l[1]&&n[e+2]==l[2])u[2]=e/3}if(u[0]==-1){n.push(a[0],a[1],a[2]);u[0]=(n.length-1)/3}if(u[1]==-1){n.push(o[0],o[1],o[2]);u[1]=(n.length-1)/3}if(u[2]==-1){n.push(l[0],l[1],l[2]);u[2]=(n.length-1)/3}r.push(u[0]);r.push(u[1]);r.push(u[2])}const s=new b(e);s.name=e;s.vertices=n;s.verticesIndices=r;return s};const T={};T.getSimpleRect=function(e,t,i=1){const n=new b(t);n.vertices=[1*i,1*i,0,-1*i,1*i,0,1*i,-1*i,0,-1*i,-1*i,0];n.texCoords=[1,1,0,1,1,0,0,0];n.verticesIndices=[0,1,2,2,1,3];n.vertexNormals=[0,0,0,0,0,0,0,0,0,0,0,0];return e.createMesh(n)};T.getSimpleCube=function(e,t){const i=new b(t);i.vertices=[-1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,1,-1,1,1,-1,1,1,1,-1,1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1];i.setTexCoords([0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,0,0,0,1,1,1,1,0,1,0,0,0,0,1,1,1,1,1,1,0,0,0,0,1,0,1,1,1,1,0,0,0]);i.verticesIndices=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];i.vertexNormals=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0]);i.tangents=new Float32Array([0,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,1,0,0,1,0,0,1,0,0,1]);i.biTangents=new Float32Array([-1,0,0,-1,0,0,-1,0,0,-1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1]);return new v(e,i)};class O{constructor(e,t){this._cgl=e;this._log=new h.Logger("cgl_TextureEffect");if(!e.TextureEffectMesh)this.createMesh();this._textureSource=null;this._options=t;this.name=t.name||"unknown";this.imgCompVer=0;this.aspectRatio=1;this._textureTarget=null;this._frameBuf=this._cgl.gl.createFramebuffer();this._frameBuf2=this._cgl.gl.createFramebuffer();this._renderbuffer=this._cgl.gl.createRenderbuffer();this._renderbuffer2=this._cgl.gl.createRenderbuffer();this.switched=false;this.depth=false}dispose(){if(this._renderbuffer)this._cgl.gl.deleteRenderbuffer(this._renderbuffer);if(this._frameBuf)this._cgl.gl.deleteFramebuffer(this._frameBuf);if(this._renderbuffer2)this._cgl.gl.deleteRenderbuffer(this._renderbuffer2);if(this._frameBuf2)this._cgl.gl.deleteFramebuffer(this._frameBuf2)}getWidth(){return this._textureSource.width}
30982getHeight(){return this._textureSource.height}setSourceTexture(e){if(e===null){this._textureSource=new u(this._cgl);this._textureSource.setSize(16,16)}else{this._textureSource=e}if(!this._textureSource.compareSettings(this._textureTarget)){if(this._textureTarget)this._textureTarget.delete();this._textureTarget=this._textureSource.clone();this._cgl.profileData.profileEffectBuffercreate++;this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._frameBuf);this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER,this._renderbuffer);if(this.depth)this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER,this._cgl.gl.DEPTH_COMPONENT16,this._textureSource.width,this._textureSource.height);this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.COLOR_ATTACHMENT0,this._cgl.gl.TEXTURE_2D,this._textureTarget.tex,0);if(this.depth)this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.DEPTH_ATTACHMENT,this._cgl.gl.RENDERBUFFER,this._renderbuffer);this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D,null);this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER,null);this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,null);this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._frameBuf2);this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER,this._renderbuffer2);if(this.depth)this._cgl.gl.renderbufferStorage(this._cgl.gl.RENDERBUFFER,this._cgl.gl.DEPTH_COMPONENT16,this._textureSource.width,this._textureSource.height);this._cgl.gl.framebufferTexture2D(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.COLOR_ATTACHMENT0,this._cgl.gl.TEXTURE_2D,this._textureSource.tex,0);if(this.depth)this._cgl.gl.framebufferRenderbuffer(this._cgl.gl.FRAMEBUFFER,this._cgl.gl.DEPTH_ATTACHMENT,this._cgl.gl.RENDERBUFFER,this._renderbuffer2);this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D,null);this._cgl.gl.bindRenderbuffer(this._cgl.gl.RENDERBUFFER,null);this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,null)}this.aspectRatio=this._textureSource.width/this._textureSource.height}continueEffect(){this._cgl.pushDepthTest(false);this._cgl.pushModelMatrix();this._cgl.pushPMatrix();this._cgl.pushViewPort(0,0,this.getCurrentTargetTexture().width,this.getCurrentTargetTexture().height);mat4.perspective(this._cgl.pMatrix,45,this.getCurrentTargetTexture().width/this.getCurrentTargetTexture().height,.1,1100);this._cgl.pushPMatrix();mat4.identity(this._cgl.pMatrix);this._cgl.pushViewMatrix();mat4.identity(this._cgl.vMatrix);this._cgl.pushModelMatrix();mat4.identity(this._cgl.mMatrix)}startEffect(e){if(!this._textureTarget){this._log.warn("effect has no target");return}this.switched=false;this.continueEffect();if(e){this._bgTex=e}this._countEffects=0}endEffect(){this._cgl.popDepthTest();this._cgl.popModelMatrix();this._cgl.popPMatrix();this._cgl.popModelMatrix();this._cgl.popViewMatrix();this._cgl.popPMatrix();this._cgl.popViewPort()}bind(){if(this._textureSource===null){this._log.warn("no base texture set!");return}if(!this.switched){this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._frameBuf);this._cgl.pushGlFrameBuffer(this._frameBuf)}else{this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._frameBuf2);this._cgl.pushGlFrameBuffer(this._frameBuf2)}}finish(){if(this._textureSource===null){this._log.warn("no base texture set!");return}this._cgl.TextureEffectMesh.render(this._cgl.getShader());this._cgl.gl.bindFramebuffer(this._cgl.gl.FRAMEBUFFER,this._cgl.popGlFrameBuffer());this._cgl.profileData.profileTextureEffect++;if(this._textureTarget.filter==u.FILTER_MIPMAP){if(!this.switched){this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D,this._textureTarget.tex);this._textureTarget.updateMipMap()}else{this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D,this._textureSource.tex);this._textureSource.updateMipMap()}this._cgl.gl.bindTexture(this._cgl.gl.TEXTURE_2D,null)}this.switched=!this.switched;this._countEffects++}getCurrentTargetTexture(){if(this.switched)return this._textureSource;return this._textureTarget}getCurrentSourceTexture(){if(this._countEffects==0&&this._bgTex)return this._bgTex;if(this.switched)return this._textureTarget;return this._textureSource}delete(){if(this._textureTarget)this._textureTarget.delete();if(this._textureSource)this._textureSource.delete();this._cgl.gl.deleteRenderbuffer(this._renderbuffer);this._cgl.gl.deleteFramebuffer(this._frameBuf)}createMesh(){this._cgl.TextureEffectMesh=T.getSimpleRect(this._cgl,"texEffectRect")}}O.checkOpNotInTextureEffect=function(e){if(!e.patch.cgl)return true;if(e.uiAttribs.error&&!e.patch.cgl.currentTextureEffect){e.setUiError("textureeffect",null);return true}if(!e.patch.cgl.currentTextureEffect)return true;if(e.patch.cgl.currentTextureEffect&&!e.uiAttribs.error){e.setUiError("textureeffect","This op can not be a child of a ImageCompose/texture effect! imagecompose should only have textureeffect childs.",0);return false}if(e.patch.cgl.currentTextureEffect)return false;return true};O.checkOpInEffect=function(e,t){t=t||0;if(e.patch.cgl.currentTextureEffect){if(e.uiAttribs.uierrors&&e.patch.cgl.currentTextureEffect.imgCompVer>=t){e.setUiError("texeffect",null);return true}if(t&&e.patch.cgl.currentTextureEffect.imgCompVer<t){e.setUiError("texeffect","This op must be a child of an ImageCompose op with version >="+t+' <span class="button-small" onclick="gui.patchView.downGradeOp(\''+e.id+"','"+e.name+"')\">Downgrade</span> to previous version",1)}}if(e.patch.cgl.currentTextureEffect)return true;if(!e.patch.cgl.currentTextureEffect&&(!e.uiAttribs.uierrors||e.uiAttribs.uierrors.length==0)){e.setUiError("texeffect",'This op must be a child of an ImageCompose op! More infos <a href="https://cables.gl/docs/image_composition/image_composition.html" target="_blank">here</a>. ',1);return false}if(!e.patch.cgl.currentTextureEffect)return false;return true};O.getBlendCode=function(e){let t="".endl()+"vec3 _blend(vec3 base,vec3 blend)".endl()+"{".endl()+" vec3 colNew=blend;".endl()+" #ifdef BM_MULTIPLY".endl()+" colNew=base*blend;".endl()+" #endif".endl()+" #ifdef BM_MULTIPLY_INV".endl()+" colNew=base* vec3(1.0)-blend;".endl()+" #endif".endl()+" #ifdef BM_AVERAGE".endl()+" colNew=((base + blend) / 2.0);".endl()+" #endif".endl()+" #ifdef BM_ADD".endl()+" colNew=min(base + blend, vec3(1.0));".endl()+" #endif".endl()+" #ifdef BM_SUBTRACT_ONE".endl()+" colNew=max(base + blend - vec3(1.0), vec3(0.0));".endl()+" #endif".endl()+" #ifdef BM_SUBTRACT".endl()+" colNew=base - blend;".endl()+" #endif".endl()+" #ifdef BM_DIFFERENCE".endl()+" colNew=abs(base - blend);".endl()+" #endif".endl()+" #ifdef BM_NEGATION".endl()+" colNew=(vec3(1.0) - abs(vec3(1.0) - base - blend));".endl()+" #endif".endl()+" #ifdef BM_EXCLUSION".endl()+" colNew=(base + blend - 2.0 * base * blend);".endl()+" #endif".endl()+" #ifdef BM_LIGHTEN".endl()+" colNew=max(blend, base);".endl()+" #endif".endl()+" #ifdef BM_DARKEN".endl()+" colNew=min(blend, base);".endl()+" #endif".endl()+" #ifdef BM_OVERLAY".endl()+" #define BlendOverlayf(base, blend) (base < 0.5 ? (2.0 * base * blend) : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend)))".endl()+" colNew=vec3(BlendOverlayf(base.r, blend.r),BlendOverlayf(base.g, blend.g),BlendOverlayf(base.b, blend.b));".endl()+" #endif".endl()+" #ifdef BM_SCREEN".endl()+" #define BlendScreenf(base, blend) (1.0 - ((1.0 - base) * (1.0 - blend)))".endl()+" colNew=vec3(BlendScreenf(base.r, blend.r),BlendScreenf(base.g, blend.g),BlendScreenf(base.b, blend.b));".endl()+" #endif".endl()+" #ifdef BM_SOFTLIGHT".endl()+" #define BlendSoftLightf(base, blend) ((blend < 0.5) ? (2.0 * base * blend + base * base * (1.0 - 2.0 * blend)) : (sqrt(base) * (2.0 * blend - 1.0) + 2.0 * base * (1.0 - blend)))".endl()+" colNew=vec3(BlendSoftLightf(base.r, blend.r),BlendSoftLightf(base.g, blend.g),BlendSoftLightf(base.b, blend.b));".endl()+" #endif".endl()+" #ifdef BM_HARDLIGHT".endl()+" #define BlendOverlayf(base, blend) (base < 0.5 ? (2.0 * base * blend) : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend)))".endl()+" colNew=vec3(BlendOverlayf(base.r, blend.r),BlendOverlayf(base.g, blend.g),BlendOverlayf(base.b, blend.b));".endl()+" #endif".endl()+" #ifdef BM_COLORDODGE".endl()+" #define BlendColorDodgef(base, blend) ((blend == 1.0) ? blend : min(base / (1.0 - blend), 1.0))".endl()+" colNew=vec3(BlendColorDodgef(base.r, blend.r),BlendColorDodgef(base.g, blend.g),BlendColorDodgef(base.b, blend.b));".endl()+" #endif".endl()+" #ifdef BM_COLORBURN".endl()+" #define BlendColorBurnf(base, blend) ((blend == 0.0) ? blend : max((1.0 - ((1.0 - base) / blend)), 0.0))".endl()+" colNew=vec3(BlendColorBurnf(base.r, blend.r),BlendColorBurnf(base.g, blend.g),BlendColorBurnf(base.b, blend.b));
30982".endl()+" #endif".endl()+" return colNew;".endl()+"}".endl();if(!e)t+="vec4 cgl_blend(vec4 oldColor,vec4 newColor,float amount)".endl()+"{".endl()+"vec4 col=vec4( _blend(oldColor.rgb,newColor.rgb) ,1.0);".endl()+"col=vec4( mix( col.rgb, oldColor.rgb ,1.0-oldColor.a*amount),1.0);".endl()+"return col;".endl()+"}".endl();if(e>=3)t+="vec4 cgl_blendPixel(vec4 base,vec4 col,float amount)".endl()+"{".endl()+"#ifdef BM_MATH_ADD".endl()+" return vec4(base.rgb+col.rgb*amount,1.0);".endl()+"#endif".endl()+"#ifdef BM_MATH_SUB".endl()+" return vec4(base.rgb-col.rgb*amount,1.0);".endl()+"#endif".endl()+"#ifdef BM_MATH_MUL".endl()+" return vec4(base.rgb*col.rgb*amount,1.0);".endl()+"#endif".endl()+"#ifdef BM_MATH_DIV".endl()+" return vec4(base.rgb/col.rgb*amount,1.0);".endl()+"#endif".endl()+"#ifndef BM_MATH".endl()+"vec3 colNew=_blend(base.rgb,col.rgb);".endl()+"float newA=clamp(base.a+(col.a*amount),0.,1.);".endl()+"#ifdef BM_ALPHAMASKED".endl()+"newA=base.a;".endl()+"#endif".endl()+"return vec4(".endl()+"mix(colNew,base.rgb,1.0-(amount*col.a)),".endl()+"newA);".endl()+"#endif".endl()+"}".endl();return t};O.onChangeBlendSelect=function(e,t,i=false){t=String(t);e.toggleDefine("BM_NORMAL",t=="normal");e.toggleDefine("BM_MULTIPLY",t=="multiply");e.toggleDefine("BM_MULTIPLY_INV",t=="multiply invert");e.toggleDefine("BM_AVERAGE",t=="average");e.toggleDefine("BM_ADD",t=="add");e.toggleDefine("BM_SUBTRACT_ONE",t=="subtract one");e.toggleDefine("BM_SUBTRACT",t=="subtract");e.toggleDefine("BM_DIFFERENCE",t=="difference");e.toggleDefine("BM_NEGATION",t=="negation");e.toggleDefine("BM_EXCLUSION",t=="exclusion");e.toggleDefine("BM_LIGHTEN",t=="lighten");e.toggleDefine("BM_DARKEN",t=="darken");e.toggleDefine("BM_OVERLAY",t=="overlay");e.toggleDefine("BM_SCREEN",t=="screen");e.toggleDefine("BM_SOFTLIGHT",t=="softlight");e.toggleDefine("BM_HARDLIGHT",t=="hardlight");e.toggleDefine("BM_COLORDODGE",t=="color dodge");e.toggleDefine("BM_COLORBURN",t=="color burn");e.toggleDefine("BM_MATH_ADD",t=="Math Add");e.toggleDefine("BM_MATH_SUB",t=="Math Subtract");e.toggleDefine("BM_MATH_MUL",t=="Math Multiply");e.toggleDefine("BM_MATH_DIV",t=="Math Divide");e.toggleDefine("BM_MATH",t.indexOf("Math ")==0);e.toggleDefine("BM_ALPHAMASKED",i)};O.AddBlendSelect=function(e,t,i){const n=e.inValueSelect(t||"Blend Mode",["normal","lighten","darken","multiply","multiply invert","average","add","subtract","difference","negation","exclusion","overlay","screen","color dodge","color burn","softlight","hardlight","subtract one","Math Add","Math Subtract","Math Multiply","Math Divide"],i||"normal");return n};O.AddBlendAlphaMask=function(e,t,i){const n=e.inSwitch(t||"Alpha Mask",["Off","On"],i||"Off");return n};O.setupBlending=function(i,n,r,e,s){const t=()=>{let e=false;if(s)e=s.get()=="On";O.onChangeBlendSelect(n,r.get(),e);let t=r.get();if(t=="normal")t=null;else if(t=="multiply")t="mul";else if(t=="multiply invert")t="mulinv";else if(t=="lighten")t="light";else if(t=="darken")t="darken";else if(t=="average")t="avg";else if(t=="subtract one")t="sub one";else if(t=="subtract")t="sub";else if(t=="difference")t="diff";else if(t=="negation")t="neg";else if(t=="exclusion")t="exc";else if(t=="overlay")t="ovl";else if(t=="color dodge")t="dodge";else if(t=="color burn")t="burn";else if(t=="softlight")t="soft";else if(t=="hardlight")t="hard";else if(t=="Math Add")t="+";else if(t=="Math Subtract")t="-";else if(t=="Math Multiply")t="*";else if(t=="Math Divide")t="/";i.setUiAttrib({extendTitle:t})};i.setPortGroup("Blending",[r,e,s]);let a=false;r.onChange=t;if(s){s.onChange=t;a=s.get()=="On"}O.onChangeBlendSelect(n,r.get(),a)};const C={"CGL.BLENDMODES":function(){this.name="blendmodes";this.srcHeadFrag=O.getBlendCode()},"CGL.BLENDMODES3":function(){this.name="blendmodes3";this.srcHeadFrag=O.getBlendCode(3)},"CGL.LUMINANCE":function(){this.name="luminance";this.srcHeadFrag="".endl()+"float cgl_luminance(vec3 c)".endl()+"{".endl()+" return dot(vec3(0.2126,0.7152,0.0722),c);".endl()+"}".endl()},"CGL.RANDOM_OLD":function(){this.name="randomNumber";this.srcHeadFrag="".endl()+"float cgl_random(vec2 co)".endl()+"{".endl()+" return fract(sin(dot(co.xy ,vec2(12.9898,4.1414))) * 432758.5453);".endl()+"}".endl()+"vec3 cgl_random3(vec2 co)".endl()+"{".endl()+" return vec3( cgl_random(co),cgl_random(co+0.5711),cgl_random(co+1.5711));".endl()+"}"},"CGL.RANDOM_LOW":function(){this.name="randomNumber";this.srcHeadFrag="".endl()+"float cgl_random(vec2 co)".endl()+"{".endl()+" return fract(sin(dot(co.xy ,vec2(12.9898,4.1414))) * 358.5453);".endl()+"}".endl()+"vec3 cgl_random3(vec2 co)".endl()+"{".endl()+" return vec3( cgl_random(co),cgl_random(co+0.5711),cgl_random(co+1.5711));".endl()+"}"},"CGL.RANDOM_TEX":function(){this.name="randomNumbertex";this.srcHeadFrag="".endl()+"UNI sampler2D CGLRNDTEX;".endl()+"float cgl_random(vec2 co)".endl()+"{".endl()+" return texture(CGLRNDTEX,co*5711.0).r;".endl()+"}".endl()+"vec3 cgl_random3(vec2 co)".endl()+"{".endl()+" return texture(CGLRNDTEX,co*5711.0).rgb;".endl()+"}";this.initUniforms=function(e){return[new c(e,"t","CGLRNDTEX",7)]};this.onBind=function(e,t){u.getRandomTexture(e);e.setTexture(7,u.getRandomTexture(e).tex)}}};class D{constructor(e){this.shader=new CGL.Shader(e,"markermaterial");const t="".endl()+"void main()".endl()+"{".endl()+" outColor = vec4(color.rgb,1.0);".endl()+"}";const i="".endl()+"IN vec3 vPosition;".endl()+"UNI mat4 projMatrix;".endl()+"UNI mat4 mvMatrix;".endl()+"void main()".endl()+"{".endl()+" gl_Position = projMatrix * mvMatrix * vec4(vPosition,1.0);".endl()+"}";this.shader.setSource(i,t);this.coloruni=this.shader.addUniformFrag("4f","color",[1,.777,1,1])}setColor(e,t,i,n){this.coloruni.set(e,t,i,n)}}class B extends h.Events{id=E.utils.simpleId();_isValid=true;_defines=[];_moduleNames=[];_moduleNumId=0;_needsRecompile=true;_compileReason="initial";_modules=[];_compileCount=0;logError=true;num=-1;lastCompile=0;constructor(){super()}setWhyCompile(e){this._compileReason=e;this._needsRecompile=true}getWhyCompile(){return this._compileReason}needsRecompile(){return this._needsRecompile}removeUniform(t){for(let e=0;e<this._uniforms.length;e++){if(this._uniforms[e].getName()==t){this._uniforms.splice(e,1)}}this.setWhyCompile("remove uniform "+t)}hasUniformInStage(t,e){let i=this.defaultUniBindingFrag;if(e==GPUShaderStage.VERTEX)i=this.defaultUniBindingVert;if(e==GPUShaderStage.COMPUTE)i=this.defaultUniBindingCompute;for(let e=0;e<this._uniforms.length;e++){console.log("hasuniiiiiiiiiiiiiii",this._uniforms[e].getName(),t);if(this._uniforms[e].getName()==t)return true}return false}hasUniform(e){}toggleDefine(t,e){if(e&&typeof e=="object"&&e.addEventListener){if(e.changeListener)e.off(e.changeListener);e.onToggleDefine=e=>{this.toggleDefine(t,e)};e.changeListener=e.on("change",e.onToggleDefine);e=e.get()}if(e)this.define(t);else this.removeDefine(t)}
30982define(t,i=""){if(i===null||i===undefined)i="";if(typeof i=="object"){i.removeEventListener("change",i.onDefineChange);i.onDefineChange=e=>{this.define(t,e)};i.on("change",i.onDefineChange);i=i.get()}for(let e=0;e<this._defines.length;e++){if(this._defines[e][0]==t&&this._defines[e][1]==i)return;if(this._defines[e][0]==t){this._defines[e][1]=i;this.setWhyCompile("define "+t+" "+i);return}}this.setWhyCompile("define "+t+" "+i);this._defines.push([t,i])}getDefines(){return this._defines}getDefine(t){for(let e=0;e<this._defines.length;e++)if(this._defines[e][0]==t)return this._defines[e][1];return null}hasDefine(t){for(let e=0;e<this._defines.length;e++)if(this._defines[e][0]==t)return true}removeDefine(t){for(let e=0;e<this._defines.length;e++){if(this._defines[e][0]==t){this._defines.splice(e,1);this.setWhyCompile("define removed:"+t);return}}}hasModule(t){for(let e=0;e<this._modules.length;e++)if(this._modules[e].id==t)return true;return false}setModules(e){this._moduleNames=e}removeModule(i){for(let e=0;e<this._modules.length;e++){if(i&&i.id){if(this._modules[e].id==i.id||!this._modules[e]){let t=true;while(t){t=false;for(let e=0;e<this._uniforms.length;e++){if(this._uniforms[e].getName().startsWith(i.prefix)){this._uniforms.splice(e,1);t=true;continue}}}this.setWhyCompile("remove module "+i.title);this._modules.splice(e,1);break}}}}getNumModules(){return this._modules.length}getCurrentModules(){return this._modules}addModule(e,t){if(this.hasModule(e.id))return;if(!e.id)e.id=E.utils.simpleId();if(!e.numId)e.numId=this._moduleNumId;if(!e.num)e.num=this._modules.length;if(t&&!t.group)t.group=E.utils.simpleId();if(!e.group)if(t)e.group=t.group;else e.group=E.utils.simpleId();e.prefix="mod"+e.group+"_";this._modules.push(e);this.setWhyCompile("add module "+e.title);this._moduleNumId++;return e}isValid(){return this._isValid}}const U=` 30983{{MODULES_HEAD}} 30984IN vec3 vPosition; //!@ 30985IN vec2 attrTexCoord; 30986IN vec3 attrVertNormal; 30987IN vec3 attrTangent,attrBiTangent; 30988 30989IN float attrVertIndex; 30990 30991OUT vec2 texCoord; 30992OUT vec3 norm; 30993UNI mat4 projMatrix; 30994UNI mat4 viewMatrix; 30995UNI mat4 modelMatrix; 30996 30997void main() 30998{ 30999 texCoord=attrTexCoord; 31000 norm=attrVertNormal; 31001 vec4 pos=vec4(vPosition, 1.0); 31002 vec3 tangent=attrTangent; 31003 vec3 bitangent=attrBiTangent; 31004 mat4 mMatrix=modelMatrix; 31005 gl_PointSize=10.0; 31006 31007 {{MODULE_VERTEX_POSITION}} 31008 31009 mat4 modelViewMatrix=viewMatrix*mMatrix; 31010 {{MODULE_VERTEX_MODELVIEW}} 31011 31012 gl_Position = projMatrix * modelViewMatrix * pos; 31013} 31014`;let V=0;function R(){return U}function I(e,t,i){if(e==undefined){e=.5;t=.5;i=.5}return""+A+"IN vec2 texCoord;"+A+"{{MODULES_HEAD}}"+A+"void main()"+A+"{"+A+" vec4 col=vec4("+e+","+t+","+i+",1.0);"+A+" {{MODULE_COLOR}}"+A+" outColor = col;"+A+"}"}class F extends B{_uniforms=[];constructor(e,t,i){super();if(!e)throw new Error("shader constructed without cgl "+t);this._log=new h.Logger("cgl_shader");this._cgl=e;if(!t)this._log.stack("no shader name given");this._name=t||"unknown";if(i)this.opId=i.id;this.glslVersion=0;if(e.glVersion>1)this.glslVersion=300;this._materialId=++V;this._program=null;this._drawBuffers=[true];this.error=null;this.ignoreMissingUniforms=false;this._projMatrixUniform=null;this._mvMatrixUniform=null;this._mMatrixUniform=null;this._vMatrixUniform=null;this._camPosUniform=null;this._normalMatrixUniform=null;this._inverseViewMatrixUniform=null;this._fromUserInteraction=false;this._attrVertexPos=-1;this.precision=e.patch.config.glslPrecision||"highp";this._pMatrixState=-1;this._vMatrixState=-1;this._countMissingUniforms=0;this._modGroupCount=0;this._feedBackNames=[];this._attributes=[];this.glPrimitive=null;this.offScreenPass=false;this._extensions=[];this.srcVert=R();this.srcFrag=I();this.lastCompile=0;this._libs=[];this._structNames=[];this._structUniformNames=[];this._textureStackUni=[];this._textureStackTex=[];this._textureStackType=[];this._textureStackTexCgl=[];this._tempNormalMatrix=w.mat4.create();this._tempCamPosMatrix=w.mat4.create();this._tempInverseViewMatrix=w.mat4.create();this._tempInverseProjMatrix=w.mat4.create();this.setModules(["MODULE_VERTEX_POSITION","MODULE_COLOR","MODULE_NORMAL","MODULE_BEGIN_FRAG","MODULE_VERTEX_MODELVIEW"])}isValid(){return this._isValid}getCgl(){return this._cgl}getName(){return this._name}
31014enableExtension(e){this.setWhyCompile("enable extension "+e);this._extensions.push(e)}getAttrVertexPos(){return this._attrVertexPos}hasTextureUniforms(){for(let e=0;e<this._uniforms.length;e++)if(this._uniforms[e].getType()=="t")return true;return false}copyUniformValues(t){for(let e=0;e<t._uniforms.length;e++){if(!this._uniforms[e]){this._log.log("unknown uniform?!");continue}this.getUniform(t._uniforms[e].getName()).set(t._uniforms[e].getValue())}this.popTextures();for(let e=0;e<t._textureStackUni.length;e++){this._textureStackUni[e]=t._textureStackUni[e];this._textureStackTex[e]=t._textureStackTex[e];this._textureStackType[e]=t._textureStackType[e];this._textureStackTexCgl[e]=t._textureStackTexCgl[e]}}copy(){const t=new F(this._cgl,this._name+" copy");t.setSource(this.srcVert,this.srcFrag);t._modules=JSON.parse(JSON.stringify(this._modules));t._defines=JSON.parse(JSON.stringify(this._defines));t._modGroupCount=this._modGroupCount;t._moduleNames=this._moduleNames;t.glPrimitive=this.glPrimitive;t.offScreenPass=this.offScreenPass;t._extensions=this._extensions;t.wireframe=this.wireframe;t._attributes=this._attributes;for(let e=0;e<this._uniforms.length;e++){const i=this._uniforms[e].copy(t);i.resetLoc()}t.setWhyCompile("copy");return t}setSource(e,t,i=false){this._fromUserInteraction=i;this.srcVert=e;this.srcFrag=t;this.setWhyCompile("Source changed");this._isValid=true}_addLibs(e){for(const t in C){if(e.includes(t)){const i=new C[t];e=e.replace("{{"+t+"}}",i.srcHeadFrag);this._libs.push(i);if(i.initUniforms)i.initUniforms(this)}}return e}createStructUniforms(){let n="";let r="";this._structNames=[];this._injectedStringsFrag={};this._injectedStringsVert={};this._structUniformNamesIndicesFrag=[];this._structUniformNamesIndicesVert=[];for(let i=0;i<this._uniforms.length;i++){if(this._uniforms[i].isStructMember()){const s="{{INJECTION_POINT_STRUCT_"+this._uniforms[i]._structName+"}}";if(!this._structNames.includes(this._uniforms[i]._structName)){const a="struct "+this._uniforms[i]._structName+" {"+A+s+"};"+A+A;if(this._uniforms[i].getShaderType()==="both"||this._uniforms[i].getShaderType()==="frag")n=n.concat(a);if(this._uniforms[i].getShaderType()==="both"||this._uniforms[i].getShaderType()==="vert")r=r.concat(a);this._structNames.push(this._uniforms[i]._structName);this._injectedStringsFrag[this._uniforms[i]._structName]=[];this._injectedStringsVert[this._uniforms[i]._structName]=[]}let e="";if(this._uniforms[i].comment)e=" // "+this._uniforms[i].comment;let t="";if(this._uniforms[i].getGlslTypeString()==undefined)t+="//";t+=" "+this._uniforms[i].getGlslTypeString()+" "+this._uniforms[i]._propertyName+";"+e;if(this._uniforms[i].getShaderType()==="both"){if(!this._injectedStringsFrag[this._uniforms[i]._structName].includes(t)&&!this._injectedStringsVert[this._uniforms[i]._structName].includes(t)){const o=n.lastIndexOf(s);const l=r.lastIndexOf(s);n=n.slice(0,o)+t+n.slice(o-1);r=r.slice(0,l)+t+r.slice(l-1);this._injectedStringsFrag[this._uniforms[i]._structName].push(t);this._injectedStringsVert[this._uniforms[i]._structName].push(t)}if(!this._structUniformNamesIndicesFrag.includes(i))this._structUniformNamesIndicesFrag.push(i);if(!this._structUniformNamesIndicesVert.includes(i))this._structUniformNamesIndicesVert.push(i)}else if(this._uniforms[i].getShaderType()==="frag"){if(!this._injectedStringsFrag[this._uniforms[i]._structName].includes(t)){const o=n.lastIndexOf(s);n=n.slice(0,o)+t+n.slice(o-1);this._injectedStringsFrag[this._uniforms[i]._structName].push(t)}if(!this._structUniformNamesIndicesFrag.includes(i))this._structUniformNamesIndicesFrag.push(i)}else if(this._uniforms[i].getShaderType()==="vert"){if(!this._injectedStringsVert[this._uniforms[i]._structName].includes(t)){const l=r.lastIndexOf(s);r=r.slice(0,l)+t+r.slice(l-1);this._injectedStringsVert[this._uniforms[i]._structName].push(t)}if(!this._structUniformNamesIndicesVert.includes(i))this._structUniformNamesIndicesVert.push(i)}}}this._uniDeclarationsFrag=[];this._uniDeclarationsVert=[];for(let e=0;e<this._structUniformNamesIndicesFrag.length;e+=1){const t=this._structUniformNamesIndicesFrag[e];const i="UNI "+this._uniforms[t]._structName+" "+this._uniforms[t]._structUniformName+";"+A;if(!this._uniDeclarationsFrag.includes(i)){const s="{{INJECTION_POINT_STRUCT_"+this._uniforms[t]._structName+"}}";n=n.replace(s,"");n+=i;this._uniDeclarationsFrag.push(i)}}for(let e=0;e<this._structUniformNamesIndicesVert.length;e+=1){const t=this._structUniformNamesIndicesVert[e];const i="UNI "+this._uniforms[t]._structName+" "+this._uniforms[t]._structUniformName+";"+A;if(!this._uniDeclarationsVert.includes(i)){const s="{{INJECTION_POINT_STRUCT_"+this._uniforms[t]._structName+"}}";r=r.replace(s,"");r+=i;this._uniDeclarationsVert.push(i)}}return[r,n]}_getAttrSrc(e,t){const i={};if(e.name&&e.type){i.srcHeadVert="";
31014if(!t)i.srcHeadVert+="#ifndef ATTRIB_"+e.name+A;i.srcHeadVert+="#define ATTRIB_"+e.name+A;i.srcHeadVert+="IN "+e.type+" "+e.name+";"+A;if(!t)i.srcHeadVert+="#endif"+A;if(e.nameFrag){i.srcHeadVert+="";if(!t)i.srcHeadVert+="#ifndef ATTRIB_"+e.nameFrag+A;i.srcHeadVert+="#define ATTRIB_"+e.nameFrag+A;i.srcHeadVert+="OUT "+e.type+" "+e.nameFrag+";"+A;if(!t)i.srcHeadVert+="#endif"+A;i.srcVert=""+A+e.nameFrag+"="+e.name+";";i.srcHeadFrag="";if(!t)i.srcHeadFrag+="#ifndef ATTRIB_"+e.nameFrag+A;i.srcHeadFrag+="#define ATTRIB_"+e.nameFrag+A;i.srcHeadFrag+="IN "+e.type+" "+e.nameFrag+";"+A;if(!t)i.srcHeadFrag+="#endif"+A}}return i}compile(){if(this._cgl.aborted)return;const e=performance.now();this._cgl.profileData.profileShaderCompiles++;this._cgl.profileData.profileShaderCompileName=this._name+" ["+this._compileReason+"]";let t="";if(this._extensions)for(let e=0;e<this._extensions.length;e++)t+="#extension "+this._extensions[e]+" : enable"+A;let i="";if(this._defines.length)i="\n// cgl generated"+A;for(let e=0;e<this._defines.length;e++)i+="#define "+this._defines[e][0]+" "+this._defines[e][1]+""+A;const n=this.createStructUniforms();this._cgl.profileData.addHeavyEvent("shader compile",this._name+" ["+this._compileReason+"]");this._compileReason="";if(this._uniforms){const p=this._uniforms.map(e=>{return e._name});const _=[];for(let e=0;e<this._uniforms.length;e++){const v=this._uniforms[e];const x=p.indexOf(v._name,e+1);if(x>-1)_.push(e)}for(let e=this._uniforms.length-1;e>=0;e-=1){if(_.includes(e))this._uniforms.splice(e,1);else this._uniforms[e].resetLoc()}}this._cgl.printError("uniform resets");this._compileCount++;if(this.hasTextureUniforms())i+="#define HAS_TEXTURES"+A;let r="";let s="";if(!this.srcFrag){this._log.warn("[cgl shader] has no fragment source!",this._name,this);this.srcVert=R();this.srcFrag=I()}r="#version 300 es"+A+"// "+A+"// vertex shader "+this._name+A+"// "+A+"precision "+this.precision+" float;"+A+"precision "+this.precision+" sampler2D;"+A+""+A+"#define WEBGL2"+A+"#define texture2D texture"+A+"#define UNI uniform"+A+"#define IN in"+A+"#define OUT out"+A;s="#version 300 es"+A+"// "+A+"// fragment shader "+this._name+A+"// "+A+"precision "+this.precision+" float;"+A+"precision "+this.precision+" sampler2D;"+A+""+A+"#define WEBGL2"+A+"#define texture2D texture"+A+"#define IN in"+A+"#define OUT out"+A+"#define UNI uniform"+A+"{{DRAWBUFFER}}"+A;let a="\n// cgl generated"+A;let o="\n// cgl generated"+A;s+="\n// active mods: --------------- ";r+="\n// active mods: --------------- ";let l=false;let u=false;for(let t=0;t<this._moduleNames.length;t++){for(let e=0;e<this._modules.length;e++){if(this._modules[e].name==this._moduleNames[t]){if(this._modules[e].srcBodyFrag||this._modules[e].srcHeadFrag){l=true;s+="\n// "+t+"."+e+". "+this._modules[e].title+" ("+this._modules[e].name+")"}if(this._modules[e].srcBodyVert||this._modules[e].srcHeadVert){r+="\n// "+t+"."+e+". "+this._modules[e].title+" ("+this._modules[e].name+")";u=true}}}}if(!u)s+="\n// no mods used...";if(!l)s+="\n// no mods used...";s+="\n";r+="\n";for(let i=0;i<this._uniforms.length;i++){if(this._uniforms[i].shaderType&&!this._uniforms[i].isStructMember()){let e="";if(!this._uniforms[i].getGlslTypeString())e+="// ";e+="UNI "+this._uniforms[i].getGlslTypeString()+" "+this._uniforms[i].getName();let t="";if(this._uniforms[i].comment)t=" // "+this._uniforms[i].comment;if(this._uniforms[i].shaderType=="vert"||this._uniforms[i].shaderType=="both")if(!this.srcVert.includes(e)&&!this.srcVert.includes("uniform "+this._uniforms[i].getGlslTypeString()+" "+this._uniforms[i].getName()))a+=e+";"+t+A;if(this._uniforms[i].shaderType=="frag"||this._uniforms[i].shaderType=="both")if(!this.srcFrag.includes(e)&&!this.srcFrag.includes("uniform "+this._uniforms[i].getGlslTypeString()+" "+this._uniforms[i].getName()))o+=e+";"+t+A}}let h=0;let c=0;for(let e=0;e<this._uniforms.length;e++){if(this._uniforms[e].shaderType&&!this._uniforms[e].isStructMember()){if(this._uniforms[e].shaderType=="vert"||this._uniforms[e].shaderType=="both")c++;if(this._uniforms[e].shaderType=="frag"||this._uniforms[e].shaderType=="both")h++}}if(h>=this._cgl.maxUniformsFrag)this._log.warn("[cgl_shader] num uniforms frag: "+h+" / "+this._cgl.maxUniformsFrag);if(c>=this._cgl.maxUniformsVert)this._log.warn("[cgl_shader] num uniforms vert: "+c+" / "+this._cgl.maxUniformsVert);if(!s.includes("precision"))s="precision "+this.precision+" float;"+A+s;if(!r.includes("precision"))r="precision "+this.precision+" float;"+A+r;if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){s+="#define MOBILE"+A;r+="#define MOBILE"+A}
31014r=t+r+i+n[0]+a+"\n// -- \n"+this.srcVert;s=t+s+i+n[1]+o+"\n// -- \n"+this.srcFrag;let g="";let f="";this._modules.sort(function(e,t){return e.priority||0-t.priority||0});let d=false;for(let n=0;n<this._moduleNames.length;n++){let t="";let i="";if(!d){d=true;for(let e=0;e<this._attributes.length;e++){const b=this._getAttrSrc(this._attributes[e],true);if(b.srcHeadVert)g+=b.srcHeadVert;if(b.srcVert)t+=b.srcVert;if(b.srcHeadFrag)f+=b.srcHeadFrag}}for(let e=0;e<this._modules.length;e++){const T=this._modules[e];if(T.name==this._moduleNames[n]){g+="\n//---- MOD: group:"+T.group+": idx:"+e+" - prfx:"+T.prefix+" - "+T.title+" ------\n";f+="\n//---- MOD: group:"+T.group+": idx:"+e+" - prfx:"+T.prefix+" - "+T.title+" ------\n";t+="\n\n//---- MOD: "+T.title+" / "+T.priority+" ------\n";i+="\n\n//---- MOD: "+T.title+" / "+T.priority+" ------\n";if(T.attributes)for(let e=0;e<T.attributes.length;e++){const b=this._getAttrSrc(T.attributes[e],false);if(b.srcHeadVert)g+=b.srcHeadVert;if(b.srcVert)t+=b.srcVert;if(b.srcHeadFrag)f+=b.srcHeadFrag}g+=T.srcHeadVert||"";f+=T.srcHeadFrag||"";t+=T.srcBodyVert||"";i+=T.srcBodyFrag||"";g+="\n//---- end mod ------\n";f+="\n//---- end mod ------\n";t+="\n//---- end mod ------\n";i+="\n//---- end mod ------\n";t=t.replace(/{{mod}}/g,T.prefix);i=i.replace(/{{mod}}/g,T.prefix);g=g.replace(/{{mod}}/g,T.prefix);f=f.replace(/{{mod}}/g,T.prefix);t=t.replace(/MOD_/g,T.prefix);i=i.replace(/MOD_/g,T.prefix);g=g.replace(/MOD_/g,T.prefix);f=f.replace(/MOD_/g,T.prefix)}}r=r.replace("{{"+this._moduleNames[n]+"}}",t);s=s.replace("{{"+this._moduleNames[n]+"}}",i)}r=r.replace("{{MODULES_HEAD}}",g);s=s.replace("{{MODULES_HEAD}}",f);r=this._addLibs(r);s=this._addLibs(s);let m="";for(let e=0;e<16;e++)if(s.includes("outColor"+e))this._drawBuffers[e]=true;if(this._drawBuffers.length==1){m="out vec4 outColor;"+A;m+="#define gl_FragColor outColor"+A}else{m+="#define MULTI_COLORTARGETS"+A;m+="vec4 outColor;"+A;let t=0;for(let e=0;e<this._drawBuffers.length;e++){if(t==0)m+="#define gl_FragColor outColor"+e+""+A;m+="layout(location = "+e+") out vec4 outColor"+e+";"+A;t++}}s=s.replace("{{DRAWBUFFER}}",m);if(!this._program){this._program=this._createProgram(r,s)}else{this._program=this._createProgram(r,s);this._projMatrixUniform=null;for(let e=0;e<this._uniforms.length;e++)this._uniforms[e].resetLoc()}this.finalShaderFrag=s;this.finalShaderVert=r;S.lastMesh=null;S.lastShader=null;this._countMissingUniforms=0;this._needsRecompile=false;this.lastCompile=(0,E.now)();this._cgl.profileData.shaderCompileTime+=performance.now()-e}bind(){if(!this._isValid||this._cgl.aborted)return;S.lastShader=this;if(!this._program||this.needsRecompile())this.compile();if(!this._isValid)return;if(!this._projMatrixUniform&&!this.ignoreMissingUniforms){this._countMissingUniforms++;if(this._countMissingUniforms<10){this._projMatrixUniform=this._cgl.gl.getUniformLocation(this._program,p.SHADER.SHADERVAR_UNI_PROJMAT);this._attrVertexPos=this._cgl.glGetAttribLocation(this._program,p.SHADER.SHADERVAR_VERTEX_POSITION);this._mvMatrixUniform=this._cgl.gl.getUniformLocation(this._program,"mvMatrix");this._vMatrixUniform=this._cgl.gl.getUniformLocation(this._program,p.SHADER.SHADERVAR_UNI_VIEWMAT);this._mMatrixUniform=this._cgl.gl.getUniformLocation(this._program,p.SHADER.SHADERVAR_UNI_MODELMAT);this._camPosUniform=this._cgl.gl.getUniformLocation(this._program,p.SHADER.SHADERVAR_UNI_VIEWPOS);this._normalMatrixUniform=this._cgl.gl.getUniformLocation(this._program,p.SHADER.SHADERVAR_UNI_NORMALMAT);this._inverseViewMatrixUniform=this._cgl.gl.getUniformLocation(this._program,p.SHADER.SHADERVAR_UNI_INVVIEWMAT);this._inverseProjMatrixUniform=this._cgl.gl.getUniformLocation(this._program,p.SHADER.SHADERVAR_UNI_INVPROJMAT);this._materialIdUniform=this._cgl.gl.getUniformLocation(this._program,p.SHADER.SHADERVAR_UNI_MATERIALID);this._objectIdUniform=this._cgl.gl.getUniformLocation(this._program,p.SHADER.SHADERVAR_UNI_OBJECTID);for(let e=0;e<this._uniforms.length;e++)this._uniforms[e].needsUpdate=true}}if(this._cgl.currentProgram!=this._program){this._cgl.profileData.profileShaderBinds++;this._cgl.gl.useProgram(this._program);this._cgl.currentProgram=this._program}for(let e=0;e<this._uniforms.length;
31014e++)if(this._uniforms[e].needsUpdate)this._uniforms[e].updateValue();if(this._pMatrixState!=this._cgl.getProjectionMatrixStateCount()){this._pMatrixState=this._cgl.getProjectionMatrixStateCount();this._cgl.gl.uniformMatrix4fv(this._projMatrixUniform,false,this._cgl.pMatrix);this._cgl.profileData.profileMVPMatrixCount++}if(this._objectIdUniform)this._cgl.gl.uniform1f(this._objectIdUniform,++this._cgl.tempData.objectIdCounter);if(this._materialIdUniform)this._cgl.gl.uniform1f(this._materialIdUniform,this._materialId);if(this._vMatrixUniform){if(this._vMatrixState!=this._cgl.getViewMatrixStateCount()){this._cgl.gl.uniformMatrix4fv(this._vMatrixUniform,false,this._cgl.vMatrix);this._cgl.profileData.profileMVPMatrixCount++;this._vMatrixState=this._cgl.getViewMatrixStateCount();if(this._inverseViewMatrixUniform){w.mat4.invert(this._tempInverseViewMatrix,this._cgl.vMatrix);this._cgl.gl.uniformMatrix4fv(this._inverseViewMatrixUniform,false,this._tempInverseViewMatrix);this._cgl.profileData.profileMVPMatrixCount++}if(this._inverseProjMatrixUniform){w.mat4.invert(this._tempInverseProjMatrix,this._cgl.pMatrix);this._cgl.gl.uniformMatrix4fv(this._inverseProjMatrixUniform,false,this._tempInverseProjMatrix);this._cgl.profileData.profileMVPMatrixCount++}}this._cgl.gl.uniformMatrix4fv(this._mMatrixUniform,false,this._cgl.mMatrix);this._cgl.profileData.profileMVPMatrixCount++;if(this._camPosUniform){w.mat4.invert(this._tempCamPosMatrix,this._cgl.vMatrix);this._cgl.gl.uniform3f(this._camPosUniform,this._tempCamPosMatrix[12],this._tempCamPosMatrix[13],this._tempCamPosMatrix[14]);this._cgl.profileData.profileMVPMatrixCount++}}else{const e=w.mat4.create();w.mat4.mul(e,this._cgl.vMatrix,this._cgl.mMatrix);this._cgl.gl.uniformMatrix4fv(this._mvMatrixUniform,false,e);this._cgl.profileData.profileMVPMatrixCount++}if(this._normalMatrixUniform){w.mat4.invert(this._tempNormalMatrix,this._cgl.mMatrix);w.mat4.transpose(this._tempNormalMatrix,this._tempNormalMatrix);this._cgl.gl.uniformMatrix4fv(this._normalMatrixUniform,false,this._tempNormalMatrix);this._cgl.profileData.profileMVPMatrixCount++}for(let e=0;e<this._libs.length;e++){if(this._libs[e].onBind)this._libs[e].onBind.bind(this._libs[e])(this._cgl,this)}this._bindTextures();return this._isValid}unBind(){}dispose(){if(this._program&&this._cgl&&this._cgl.gl)this._cgl.gl.deleteProgram(this._program);this._program=null}setDrawBuffers(e){this._log.warn("useless drawbuffers...?!")}getUniforms(){return this._uniforms}getUniform(t){for(let e=0;e<this._uniforms.length;e++)if(this._uniforms[e].getName()==t)return this._uniforms[e];return null}removeAllUniforms(){this._uniforms=[]}_addUniform(e){this._uniforms.push(e);this.setWhyCompile("add uniform "+name)}addUniformFrag(e,t,i,n,r,s){const a=new c(this,e,t,i,n,r,s);a.shaderType="frag";return a}addUniformVert(e,t,i,n,r,s){const a=new c(this,e,t,i,n,r,s);a.shaderType="vert";return a}addUniformBoth(e,t,i,n,r,s){const a=new c(this,e,t,i,n,r,s);a.shaderType="both";return a}addUniformStructFrag(t,i,n){const r={};if(!n)return r;for(let e=0;e<n.length;e+=1){const s=n[e];if(!this.hasUniform(i+"."+s.name)){const a=new c(this,s.type,i+"."+s.name,s.v1,s.v2,s.v3,s.v4,i,t,s.name);a.shaderType="frag";r[i+"."+s.name]=a}}return r}addUniformStructVert(t,i,n){const r={};if(!n)return r;for(let e=0;e<n.length;e+=1){const s=n[e];if(!this.hasUniform(i+"."+s.name)){const a=new c(this,s.type,i+"."+s.name,s.v1,s.v2,s.v3,s.v4,i,t,s.name);a.shaderType="vert";r[i+"."+s.name]=a}}return r}addUniformStructBoth(t,i,n){const r={};if(!n)return r;for(let e=0;e<n.length;e+=1){const s=n[e];if(s.type==="2i"||s.type==="i"||s.type==="3i")this._log.error("Adding an integer struct member to both shaders can potentially error. Please use different structs for each shader. Error occured in struct:",t," with member:",s.name," of type:",s.type,".");if(!this.hasUniform(i+"."+s.name)){const a=new c(this,s.type,i+"."+s.name,s.v1,s.v2,s.v3,s.v4,i,t,s.name);a.shaderType="both";r[i+"."+s.name]=a}}return r}_createProgram(e,t){this._cgl.printError("before _createprogram");const i=this._cgl.gl.createProgram();this.vshader=F.createShader(this._cgl,e,this._cgl.gl.VERTEX_SHADER,this);this.fshader=F.createShader(this._cgl,t,this._cgl.gl.FRAGMENT_SHADER,this);if(this.vshader&&this.fshader){this._cgl.gl.attachShader(i,this.vshader);this._cgl.gl.attachShader(i,this.fshader);this._linkProgram(i,e,t)}else{this._isValid=false;this._cgl.printError("shader _createProgram");this._log.error("could not link shaderprogram");return null}this._cgl.printError("shader _createProgram");return i}hasErrors(){return this._hasErrors}_linkProgram(e,t,i){this._cgl.printError("before _linkprogram");if(this._feedBackNames.length>0){this._cgl.gl.transformFeedbackVaryings(e,this._feedBackNames,this._cgl.gl.SEPARATE_ATTRIBS)}this._cgl.gl.linkProgram(e);this._cgl.printError("gl.linkprogram");this._isValid=true;this._hasErrors=false;if(this._cgl.patch.config.glValidateShader!==false){this._cgl.gl.validateProgram(e);if(!this._cgl.gl.getProgramParameter(e,this._cgl.gl.VALIDATE_STATUS)){this._log.log("shaderprogram validation failed...");this._cgl.gl.getProgramInfoLog(e)}if(!this._cgl.gl.getProgramParameter(e,this._cgl.gl.LINK_STATUS)){this._hasErrors=true;const n=this._cgl.gl.getShaderInfoLog(this.fshader);const r=this._cgl.gl.getShaderInfoLog(this.vshader);if(this.logError)this._log.error(this._name+" shader linking fail...");else this._log.warn(this._name+" shader linking fail...");if(n)this._log.warn(this._cgl.gl.getShaderInfoLog(this.fshader));if(r)this._log.warn(this._cgl.gl.getShaderInfoLog(this.vshader));this._cgl.gl.getProgramInfoLog(e);
31014if(!CABLES.UI)this._log.log(this);this._isValid=false;this._cgl.printError("shader link err")}}}getProgram(){return this._program}setFeedbackNames(e){this.setWhyCompile("setFeedbackNames");this._feedBackNames=e}addAttribute(t){for(let e=0;e<this._attributes.length;e++){if(this._attributes[e].name==t.name&&this._attributes[e].nameFrag==t.nameFrag)return}this._attributes.push(t);this.setWhyCompile("addAttribute")}bindTextures(){this._bindTextures()}_bindTextures(){if(this._textureStackTex.length>this._cgl.maxTextureUnits){this._log.warn("[shader._bindTextures] too many textures bound",this._textureStackTex.length+"/"+this._cgl.maxTextureUnits)}for(let i=0;i<this._textureStackTex.length;i++){if(!this._textureStackTex[i]&&!this._textureStackTexCgl[i]){this._log.warn("no texture for pushtexture",this._name)}else{let e=this._textureStackTex[i];if(this._textureStackTexCgl[i]){e=this._textureStackTexCgl[i].tex||CGL.Texture.getEmptyTexture(this._cgl).tex}let t=true;if(!this._textureStackUni[i]){this._log.warn("no uniform for pushtexture",this._name);t=this._cgl.setTexture(i,e,this._textureStackType[i])}else{this._textureStackUni[i].setValue(i);t=this._cgl.setTexture(i,e,this._textureStackType[i])}if(!t)this._log.warn("tex bind failed",this.getName(),this._textureStackUni[i])}}}setUniformTexture(t,i){i=i||u.getTempTexture(this._cgl);for(let e=0;e<this._textureStackUni.length;e++)if(this._textureStackUni[e]==t){const n=this._textureStackTex[e]||this._textureStackTexCgl[e];if(i.hasOwnProperty("tex")){this._textureStackTexCgl[e]=i;this._textureStackTex[e]=null}else{this._textureStackTexCgl[e]=null;this._textureStackTex[e]=i}return n}return null}pushTexture(e,t,i){if(!e){return}if(!t){return}if(!t.hasOwnProperty("tex")&&!(t instanceof WebGLTexture)){this._log.warn(new Error("invalid texture").stack);this._log.warn("[cgl_shader] invalid texture...",t);return}this._textureStackUni.push(e);if(t.hasOwnProperty("tex")){this._textureStackTexCgl.push(t);this._textureStackTex.push(null)}else{this._textureStackTexCgl.push(null);this._textureStackTex.push(t)}this._textureStackType.push(i)}popTexture(){this._textureStackUni.pop();this._textureStackTex.pop();this._textureStackTexCgl.pop();this._textureStackType.pop()}popTextures(){this._textureStackTex.length=this._textureStackTexCgl.length=this._textureStackType.length=this._textureStackUni.length=0}getMaterialId(){return this._materialId}getInfo(){const e={};e.name=this._name;e.defines=this.getDefines();e.hasErrors=this.hasErrors();return e}getDefaultFragmentShader(e,t,i,n){return I(e,t,i,n)}getDefaultVertexShader(){return R()}}F.getDefaultVertexShader=R;F.getDefaultFragmentShader=I;F.getErrorFragmentShader=function(){return""+A+"void main()"+A+"{"+A+" float g=mod((gl_FragCoord.y+gl_FragCoord.x),50.0)/50.0;"+A+" g= step(0.1,g);"+A+" outColor = vec4( g+0.5, 0.0, 0.0, 1.0);"+A+"}"};F.createShader=function(e,t,i,n){if(e.aborted)return;const r=e.gl.createShader(i);e.gl.shaderSource(r,t);e.gl.compileShader(r);if(!e.gl.getShaderParameter(r,e.gl.COMPILE_STATUS)){n.error={str:t,infoLog:e.gl.getShaderInfoLog(r)};if(CABLES.UI)gui.emitEvent("ShaderError",n);if(!n.error.infoLog){n._log.warn("empty shader info log",this._name);return}n.setSource(F.getDefaultVertexShader(),F.getErrorFragmentShader())}return r};const k=Math.PI/180;const G=180/Math.PI;const j=null;const z=window.navigator.userAgent.includes("Windows");const M=function(t){let i;if(t.wheelDelta){i=t.wheelDelta%120-0==-0?t.wheelDelta/120:t.wheelDelta/30;i*=-1.5;if(z)i*=2}else{let e=t.deltaY;if(t.shiftKey)e=t.deltaX;const n=e||t.detail;i=-(n%3?n*10:n/3);i*=-3}if(i>20)i=20;if(i<-20)i=-20;return i};const H=M;const X=M;class y{constructor(e){this._cgl=e;this._lastTime=0;this.pause=false;this.profileUniformCount=0;this.profileShaderBinds=0;this.profileUniformCount=0;this.profileShaderCompiles=0;this.profileVideosPlaying=0;this.profileMVPMatrixCount=0;this.profileEffectBuffercreate=0;this.profileShaderGetUniform=0;this.profileFrameBuffercreate=0;this.profileMeshSetGeom=0;this.profileTextureNew=0;this.profileGenMipMap=0;this.profileOnAnimFrameOps=0;this.profileFencedPixelRead=0;this.profileMainloopMs=0;this.profileMeshDraw=0;this.profileTextureEffect=0;this.profileTexPreviews=0;this.shaderCompileTime=0;this.profileMeshNumElements=0;this.profileMeshAttributes=0;this.profileSingleMeshAttribute=[];this.heavyEvents=[];this.doProfileGlQuery=false;this.glQueryData={};this.counts={}}clear(){this.counts={};this.profileSingleMeshAttribute={};this.profileMeshAttributes=0;this.profileUniformCount=0;this.profileShaderGetUniform=0;this.profileShaderCompiles=0;this.profileShaderBinds=0;this.profileTextureResize=0;this.profileFrameBuffercreate=0;this.profileEffectBuffercreate=0;this.profileTextureDelete=0;this.profileMeshSetGeom=0;this.profileVideosPlaying=0;this.profileMVPMatrixCount=0;this.profileNonTypedAttrib=0;this.profileNonTypedAttribNames="";this.profileTextureNew=0;this.profileGenMipMap=0;this.profileFramebuffer=0;this.profileMeshDraw=0;this.profileTextureEffect=0;this.profileTexPreviews=0;this.profileMeshNumElements=0;this.profileFencedPixelRead=0}clearGlQuery(){for(let e in this.glQueryData){if(!this.glQueryData[e].lastClear||performance.now()-this.glQueryData[e].lastClear>1e3){this.glQueryData[e].time=this.glQueryData[e]._times/this.glQueryData[e]._numcount;this.glQueryData[e].num=this.glQueryData[e]._numcount;this.glQueryData[e]._times=0;this.glQueryData[e]._numcount=0;this.glQueryData[e].lastClear=performance.now()}}}count(e,t){this.counts[e]=this.counts[e]||[];this.counts[e].push(t)}addHeavyEvent(e,t,i){const n={event:e,name:t,info:i,date:performance.now()};this.heavyEvents.push(n);this._cgl.emitEvent("heavyEvent",n)}}class N{constructor(){this._arr=[w.mat4.create()];this._index=0;this.stateCounter=0}push(e){this._index++;this.stateCounter++;if(this._index==this._arr.length){const t=w.mat4.create();this._arr.push(t)}w.mat4.copy(this._arr[this._index],e||this._arr[this._index-1]);return this._arr[this._index]}pop(){this.stateCounter++;this._index--;if(this._index<0)this._index=0;return this._arr[this._index]}length(){return this._index}}class W{hasFocus=false;forceAspect=0;pixelDensity=1;_oldWidthRp=-1;_oldHeightRp=-1;constructor(e){this._log=new h.Logger("CgCanvas");if(!e){this._log.error("CgCanvas no options")}else{this._canvasEle=e.canvasEle}if(!e.cg)this._log.error("CgCanvas options has no cg");this._cg=e.cg;if(this.canvasEle){this.canvasWidth=this.canvasEle.clientWidth;this.canvasHeight=this.canvasEle.clientHeight;this.setSize(this.canvasWidth,this.canvasHeight);this.canvasEle.addEventListener("focus",()=>{this.hasFocus=true});this.canvasEle.addEventListener("blur",()=>{this.hasFocus=false})}}get canvasEle(){return this._canvasEle}setSize(t,i,e=false){let n=0;if(this.forceAspect){let e=t/this.forceAspect;if(e<i)n=(i-e)/2;i=e}if(this._oldWidthRp!=t*this.pixelDensity||this._oldHeightRp!=i*this.pixelDensity){this._oldWidthRp=this.canvasEle.width=t*this.pixelDensity;this._oldHeightRp=this.canvasEle.height=i*this.pixelDensity;if(!e){this.canvasEle.style.width=t+"px";this.canvasEle.style.height=i+"px";this.canvasEle.style.marginTop=n+"px"}this.updateSize();this._cg.emitEvent("resize")}}updateSize(){this.canvasEle.width=this.canvasWidth=Math.ceil(this.canvasEle.clientWidth*this.pixelDensity);this.canvasEle.height=this.canvasHeight=Math.ceil(this.canvasEle.clientHeight*this.pixelDensity)}dispose(){if(this._canvasEle)this._canvasEle.remove();this._canvasEle=null}}class q extends h.Events{constructor(){super();this._timeStartFrame=0;this._timeStartSecond=0;this._fpsCounter=0;this._msCounter=0;this._frameCount=0;this.logFps=false;this.stats={ms:0,fps:0}}get frameCount(){return this._frameCount}startFrame(){this._timeStartFrame=(0,E.now)()}endFrame(){this._frameCount++;this._fpsCounter++;const e=(0,E.now)()-this._timeStartFrame;this._msCounter+=e;if((0,E.now)()-this._timeStartSecond>1e3)this.endSecond()}endSecond(){this.stats.fps=this._fpsCounter;this.stats.ms=Math.round(this._msCounter/this._fpsCounter*100)/100;this.emitEvent("performance",this.stats);if(this.logFps)console.log(this.stats);this._fpsCounter=0;this._msCounter=0;this._timeStartSecond=(0,E.now)()}}class P extends h.Events{static API_UNKNOWN=0;static API_WEBGL=1;static API_WEBGPU=2;static EVENT_RESIZE="resize";gApi=0;_textureslots=[];_pMatrixStack=new N;_mMatrixStack=new N;_vMatrixStack=new N;canvasScale=1;constructor(e){super();this._log=new h.Logger("cg_context",{onError:e.config.onError});this.tempData=this.frameStore=this.frameStore||{};this.fpsCounter=new q;this._identView=w.vec3.create();this._ident=w.vec3.create();w.vec3.set(this._identView,0,0,-2);w.vec3.set(this._ident,0,0,0);this._onetimeCallbacks=[];this.maxTexSize=2048;this._viewPort=[0,0,1,1];this._viewPortStack=[];this.patch=e;this.autoReSize=true;this.DEPTH_COMPARE_FUNC_NEVER=0;this.DEPTH_COMPARE_FUNC_LESS=1;this.DEPTH_COMPARE_FUNC_EQUAL=2;
31014this.DEPTH_COMPARE_FUNC_LESSEQUAL=3;this.DEPTH_COMPARE_FUNC_GREATER=4;this.DEPTH_COMPARE_FUNC_NOTEQUAL=5;this.DEPTH_COMPARE_FUNC_GREATEREQUAL=6;this.DEPTH_COMPARE_FUNC_ALWAYS=7;this.profileData=new y(this);this.pMatrix=w.mat4.create();this.mMatrix=w.mat4.create();this.vMatrix=w.mat4.create();w.mat4.identity(this.mMatrix);w.mat4.identity(this.vMatrix);window.matchMedia("screen and (min-resolution: 2dppx)").addEventListener("change",()=>{this.emitEvent("resize")})}get canvasWidth(){return this.width}get canvasHeight(){return this.height}get width(){return this.cgCanvas.canvasWidth}get height(){return this.cgCanvas.canvasHeight}get widthCss(){return this.cgCanvas.canvasWidth/this.pixelDensity}get heightCss(){return this.cgCanvas.canvasHeight/this.pixelDensity}set pixelDensity(e){if(this.cgCanvas.pixelDensity!=e){this.cgCanvas.pixelDensity=e;this.cgCanvas.updateSize();this.emitEvent("resize")}}get pixelDensity(){return this.cgCanvas.pixelDensity}getGApiName(){return["unknown","WebGL","WebGPU"][this.gApi]}get canvas(){return this.cgCanvas.canvasEle}get viewPort(){return[0,0,this.canvasWidth,this.canvasHeight]}setCanvas(e){if(this.cgCanvas&&e==this.cgCanvas.canvasEle)return;if(typeof e==="string")e=document.getElementById(e);this.cgCanvas=new W({canvasEle:e,cg:this});if(!e)return;e.parentElement.classList.add("cablesContainer");if(this._setCanvas)this._setCanvas(e);this.updateSize()}_setCanvas(e){}updateSize(){this.cgCanvas.updateSize()}setSize(e,t,i=false){this.cgCanvas.setSize(e,t,i)}_resizeToWindowSize(){if(this.autoReSize){this.setSize(window.innerWidth,window.innerHeight);this.updateSize()}}_resizeToParentSize(){if(this.autoReSize){const e=this.canvas.parentElement;if(!e){this._log.error("cables: can not resize to container element");return}this.setSize(e.clientWidth,e.clientHeight);this.updateSize()}}setAutoResize(e){window.removeEventListener("resize",this._resizeToWindowSize.bind(this));window.removeEventListener("resize",this._resizeToParentSize.bind(this));if(e=="window"){window.addEventListener("resize",this._resizeToWindowSize.bind(this));window.addEventListener("orientationchange",this._resizeToWindowSize.bind(this));this._resizeToWindowSize()}if(e=="parent"){window.addEventListener("resize",this._resizeToParentSize.bind(this));this._resizeToParentSize()}}pushPMatrix(){this.pMatrix=this._pMatrixStack.push(this.pMatrix)}popPMatrix(){this.pMatrix=this._pMatrixStack.pop();return this.pMatrix}getProjectionMatrixStateCount(){return this._pMatrixStack.stateCounter}pushModelMatrix(){this.mMatrix=this._mMatrixStack.push(this.mMatrix)}popModelMatrix(){this.mMatrix=this._mMatrixStack.pop();return this.mMatrix}modelMatrix(){return this.mMatrix}pushViewMatrix(){this.vMatrix=this._vMatrixStack.push(this.vMatrix)}popViewMatrix(){this.vMatrix=this._vMatrixStack.pop()}getViewMatrixStateCount(){return this._vMatrixStack.stateCounter}_startMatrixStacks(e,t){e=e||this._ident;t=t||this._identView;w.mat4.perspective(this.pMatrix,45,this.canvasWidth/this.canvasHeight,.1,1e3);w.mat4.identity(this.mMatrix);w.mat4.identity(this.vMatrix);w.mat4.translate(this.mMatrix,this.mMatrix,e);w.mat4.translate(this.vMatrix,this.vMatrix,t);this.pushPMatrix();this.pushModelMatrix();this.pushViewMatrix()}_endMatrixStacks(){this.popViewMatrix();this.popModelMatrix();this.popPMatrix()}dispose(){this.aborted=true;if(this.cgCanvas)this.cgCanvas.dispose();if(this._dispose)this._dispose()}_dispose(){}shouldDrawHelpers(e){return false}addNextFrameOnceCallback(e){if(e&&this._onetimeCallbacks.indexOf(e)==-1)this._onetimeCallbacks.push(e)}_execOneTimeCallbacks(){if(this._onetimeCallbacks.length>0){for(let e=0;e<this._onetimeCallbacks.length;e++)this._onetimeCallbacks[e]();this._onetimeCallbacks.length=0}}checkTextureSize(e){e=e||1;e=Math.floor(e);e=Math.min(e,this.maxTexSize);e=Math.max(e,1);return e}screenShot(e,t,i,n){console.log("no screenshot function implemented")}saveScreenshot(i,n,e,t,r){this.patch.renderOneFrame();let s=this.canvas.clientWidth*this.pixelDensity;let a=this.canvas.clientHeight*this.pixelDensity;if(e){this.canvas.width=e;s=e}if(t){this.canvas.height=t;a=t}function o(e,t,i){return Array(t-String(e).length+1).join(i||"0")+e}const l=new Date;const u="".concat(String(l.getFullYear())+String(l.getMonth()+1)+String(l.getDate()),"_").concat(o(l.getHours(),2)).concat(o(l.getMinutes(),2)).concat(o(l.getSeconds(),2));if(!i)i="cables_"+u+".png";else i+=".png";this.screenShot(e=>{this.canvas.width=s;this.canvas.height=a;if(e){const t=document.createElement("a");t.download=i;t.href=URL.createObjectURL(e);console.log("scrrenshot");setTimeout(function(){t.click();if(n)n(e)},100)}else{this._log.log("screenshot: no blob")}})}hasFocus(){return this.cgCanvas.hasFocus}}const Y={BLEND_NONE:0,BLEND_NORMAL:1,BLEND_ADD:2,BLEND_SUB:3,BLEND_MUL:4};class Z extends P{constructor(e){super(e);this.gApi=P.API_WEBGL;this.aborted=false;this.pushMvMatrix=this.pushModelMatrix;this.popMvMatrix=this.popmMatrix=this.popModelMatrix;this._log=new h.Logger("cgl_context",{onError:e.config.onError});this.glVersion=0;this.glUseHalfFloatTex=false;this.clearCanvasTransparent=true;this.clearCanvasDepth=true;this.debugOneFrame=false;this.checkGlErrors=false;this.maxTextureUnits=0;this.maxVaryingVectors=0;this.currentProgram=null;this._hadStackError=false;this.glSlowRendere=false;this._isSafariCrap=false;this.temporaryTexture=null;this.gl=null;this._cursor="auto";this._currentCursor="";this._viewPortStack=[];this._glFrameBufferStack=[];this._frameBufferStack=[];this._shaderStack=[];this._stackDepthTest=[];this.mainloopOp=null;this._stackBlendMode=[];this._stackBlendModePremul=[];this._stackBlend=[];this._stackDepthFunc=[];this._stackCullFaceFacing=[];this._stackCullFace=[];this._stackDepthWrite=[];this._stackDepthTest=[];this._stackStencil=[];this._simpleShader=new F(this,"simpleshader");this._simpleShader.setModules(["MODULE_VERTEX_POSITION","MODULE_COLOR","MODULE_BEGIN_FRAG","MODULE_VERTEX_MODELVIEW"]);this._simpleShader.setSource(F.getDefaultVertexShader(),F.getDefaultFragmentShader());this._currentShader=this._simpleShader;this._oldCanvasWidth=-1;this._oldCanvasHeight=-1;this._enabledExtensions={};this.errorShader=null}
31014get viewPort(){if(this._viewPortStack.length>3){const e=this._viewPortStack.length;return[this._viewPortStack[e-4],this._viewPortStack[e-3],this._viewPortStack[e-2],this._viewPortStack[e-1]]}else{return this._viewPort}}get mvMatrix(){return this.mMatrix}set mvMatrix(e){this.mMatrix=e}_setCanvas(e){if(!e)this._log.stack("_setCanvas undef");if(!this.patch.config.canvas)this.patch.config.canvas={};if(!this.patch.config.canvas.hasOwnProperty("preserveDrawingBuffer"))this.patch.config.canvas.preserveDrawingBuffer=true;if(!this.patch.config.canvas.hasOwnProperty("premultipliedAlpha"))this.patch.config.canvas.premultipliedAlpha=false;if(!this.patch.config.canvas.hasOwnProperty("alpha"))this.patch.config.canvas.alpha=false;this.patch.config.canvas.stencil=true;if(this.patch.config.hasOwnProperty("clearCanvasColor"))this.clearCanvasTransparent=this.patch.config.clearCanvasColor;if(this.patch.config.hasOwnProperty("clearCanvasDepth"))this.clearCanvasDepth=this.patch.config.clearCanvasDepth;if(/^((?!chrome|android).)*safari/i.test(navigator.userAgent)){this._isSafariCrap=true;this.glUseHalfFloatTex=true}if(!this.patch.config.canvas.forceWebGl1)this.gl=e.getContext("webgl2",this.patch.config.canvas);if(!this.gl||this.gl.isContextLost()){this.aborted=true;this._log.error("NO_WEBGL","sorry, could not initialize WebGL. Please check if your Browser supports WebGL or try to restart your browser.");return}if(this.gl.getParameter(this.gl.VERSION)!="WebGL 1.0"){this.glVersion=2}else{this.gl=e.getContext("webgl",this.patch.config.canvas)||e.getContext("experimental-webgl",this.patch.config.canvas);this.glVersion=1;if(/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream){if(!this.patch.config.canvas.hasOwnProperty("powerPreference"))this.patch.config.canvas.powerPreference="high-performance"}this.enableExtension("OES_standard_derivatives");const i=this.enableExtension("ANGLE_instanced_arrays")||this.gl;if(i.vertexAttribDivisorANGLE){this.gl.vertexAttribDivisor=i.vertexAttribDivisorANGLE.bind(i);this.gl.drawElementsInstanced=i.drawElementsInstancedANGLE.bind(i)}}const t=this.enableExtension("WEBGL_debug_renderer_info");if(t){this.glRenderer=this.gl.getParameter(t.UNMASKED_RENDERER_WEBGL);if(this.glRenderer==="Google SwiftShader")this.glSlowRenderer=true}this.canvas.addEventListener("webglcontextlost",e=>{if(this.aborted)return this._log.warn("[cgl_state] aborted context lost... can be ignored...");this._log.error("canvas lost...",e);this.emitEvent("webglcontextlost");this.aborted=true});this.maxAnisotropic=0;if(this.enableExtension("EXT_texture_filter_anisotropic"))this.maxAnisotropic=this.gl.getParameter(this.enableExtension("EXT_texture_filter_anisotropic").MAX_TEXTURE_MAX_ANISOTROPY_EXT);this.maxVaryingVectors=this.gl.getParameter(this.gl.MAX_VARYING_VECTORS);this.maxTextureUnits=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS);this.maxTexSize=this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE);this.maxUniformsFrag=this.gl.getParameter(this.gl.MAX_FRAGMENT_UNIFORM_VECTORS);this.maxUniformsVert=this.gl.getParameter(this.gl.MAX_VERTEX_UNIFORM_VECTORS);this.maxSamples=0;if(this.gl.MAX_SAMPLES)this.maxSamples=this.gl.getParameter(this.gl.MAX_SAMPLES);if(this.glVersion==1){this.enableExtension("OES_standard_derivatives");const i=this.enableExtension("ANGLE_instanced_arrays")||this.gl;if(i.vertexAttribDivisorANGLE){this.gl.vertexAttribDivisor=i.vertexAttribDivisorANGLE.bind(i);this.gl.drawElementsInstanced=i.drawElementsInstancedANGLE.bind(i)}}this.DEPTH_FUNCS=[this.gl.NEVER,this.gl.ALWAYS,this.gl.LESS,this.gl.LEQUAL,this.gl.GREATER,this.gl.GEQUAL,this.gl.EQUAL,this.gl.NOTEQUAL];this.CULL_MODES=[null,this.gl.BACK,this.gl.FRONT,this.gl.FRONT_AND_BACK]}getInfo(){return{glVersion:this.glVersion,glRenderer:this.glRenderer,glUseHalfFloatTex:this.glUseHalfFloatTex,maxVaryingVectors:this.maxVaryingVectors,maxTextureUnits:this.maxTextureUnits,maxTexSize:this.maxTexSize,maxUniformsFrag:this.maxUniformsFrag,maxUniformsVert:this.maxUniformsVert,maxSamples:this.maxSamples}}popViewPort(){this._viewPortStack.pop();this._viewPortStack.pop();this._viewPortStack.pop();this._viewPortStack.pop();if(this._viewPortStack.length==0)this.setViewPort(0,0,this.canvasWidth,this.canvasHeight);else this.setViewPort(this._viewPortStack[this._viewPort.length-4],this._viewPortStack[this._viewPort.length-3],this._viewPortStack[this._viewPort.length-2],this._viewPortStack[this._viewPort.length-1])}pushViewPort(e,t,i,n){this._viewPortStack.push(e,t,i,n);this.setViewPort(e,t,i,n)}getViewPort(){return this._viewPort}
31014resetViewPort(){this.gl.viewport(this._viewPort[0],this._viewPort[1],this._viewPort[2],this._viewPort[3])}setViewPort(e,t,i,n){this._viewPort[0]=Math.round(e);this._viewPort[1]=Math.round(t);this._viewPort[2]=Math.round(i);this._viewPort[3]=Math.round(n);this.gl.viewport(this._viewPort[0],this._viewPort[1],this._viewPort[2],this._viewPort[3])}screenShot(t,e,i,n){if(e){this.gl.clearColor(1,1,1,1);this.gl.colorMask(false,false,false,true);this.gl.clear(this.gl.COLOR_BUFFER_BIT);this.gl.colorMask(true,true,true,true)}if(this.canvas&&this.canvas.toBlob){this.canvas.toBlob(e=>{if(t)t(e);else this._log.log("no screenshot callback...")},i,n)}}endFrame(){if(this.patch.isEditorMode())CABLES.GL_MARKER.drawMarkerLayer(this);this.setPreviousShader();if(this._vMatrixStack.length()>0)this.logStackError("view matrix stack length !=0 at end of rendering...");if(this._mMatrixStack.length()>0)this.logStackError("mvmatrix stack length !=0 at end of rendering...");if(this._pMatrixStack.length()>0)this.logStackError("pmatrix stack length !=0 at end of rendering...");if(this._glFrameBufferStack.length>0)this.logStackError("glFrameBuffer stack length !=0 at end of rendering...");if(this._stackDepthTest.length>0)this.logStackError("depthtest stack length !=0 at end of rendering...");if(this._stackDepthWrite.length>0)this.logStackError("depthwrite stack length !=0 at end of rendering...");if(this._stackDepthFunc.length>0)this.logStackError("depthfunc stack length !=0 at end of rendering...");if(this._stackBlend.length>0)this.logStackError("blend stack length !=0 at end of rendering...");if(this._stackBlendMode.length>0)this.logStackError("blendMode stack length !=0 at end of rendering...");if(this._shaderStack.length>0)this.logStackError("this._shaderStack length !=0 at end of rendering...");if(this._stackCullFace.length>0)this.logStackError("this._stackCullFace length !=0 at end of rendering...");if(this._stackCullFaceFacing.length>0)this.logStackError("this._stackCullFaceFacing length !=0 at end of rendering...");if(this._viewPortStack.length>0)this.logStackError("viewport stack length !=0 at end of rendering...");this._frameStarted=false;if(this._oldCanvasWidth!=this.canvasWidth||this._oldCanvasHeight!=this.canvasHeight){this._oldCanvasWidth=this.canvasWidth;this._oldCanvasHeight=this.canvasHeight;this.emitEvent(P.EVENT_RESIZE)}if(this._cursor!=this._currentCursor){this._currentCursor=this.canvas.style.cursor=this._cursor}this.emitEvent("endframe");this.fpsCounter.endFrame()}logStackError(e){if(!this._hadStackError){this._hadStackError=true;this._log.warn("["+this.canvas.id+"]: ",e)}}getShader(){if(this._currentShader)if(!this.tempData||this.tempData.renderOffscreen===true==this._currentShader.offScreenPass===true)return this._currentShader;for(let e=this._shaderStack.length-1;e>=0;e--)if(this._shaderStack[e])if(this.tempData.renderOffscreen==this._shaderStack[e].offScreenPass)return this._shaderStack[e]}getDefaultShader(){return this._simpleShader}setShader(e){this.pushShader(e)}pushShader(t){if(this.tempData.forceShaderMods){for(let e=0;e<this.tempData.forceShaderMods.length;e++){t=this.tempData.forceShaderMods[e].bind(t,false)}}this._shaderStack.push(t);this._currentShader=t}popShader(){this.setPreviousShader()}setPreviousShader(){if(this.tempData.forceShaderMods){for(let e=0;e<this.tempData.forceShaderMods.length;e++){this.tempData.forceShaderMods[e].unbind(false)}}if(this._shaderStack.length===0)throw new Error("Invalid shader stack pop!");this._shaderStack.pop();this._currentShader=this._shaderStack[this._shaderStack.length-1]}pushGlFrameBuffer(e){this._glFrameBufferStack.push(e)}popGlFrameBuffer(){if(this._glFrameBufferStack.length==0)return null;this._glFrameBufferStack.pop();return this._glFrameBufferStack[this._glFrameBufferStack.length-1]}getCurrentGlFrameBuffer(){if(this._glFrameBufferStack.length===0)return null;return this._glFrameBufferStack[this._glFrameBufferStack.length-1]}pushFrameBuffer(e){this._frameBufferStack.push(e)}popFrameBuffer(){if(this._frameBufferStack.length==0)return null;this._frameBufferStack.pop();return this._frameBufferStack[this._frameBufferStack.length-1]}getCurrentFrameBuffer(){if(this._frameBufferStack.length===0)return null;return this._frameBufferStack[this._frameBufferStack.length-1]}renderStart(e,t,i){this.fpsCounter.startFrame();this.pushDepthTest(true);this.pushDepthWrite(true);this.pushDepthFunc(e.gl.LEQUAL);this.pushCullFaceFacing(e.gl.BACK);this.pushCullFace(false);e.setViewPort(0,0,e.canvasWidth,e.canvasHeight);this._startMatrixStacks(t,i);e.pushBlendMode(p.BLEND_MODES.BLEND_NORMAL,false);for(let e=0;e<this._textureslots.length;e++)this._textureslots[e]=null;this.pushShader(this._simpleShader);this._frameStarted=true;this._execOneTimeCallbacks();for(let e=0;e<this._textureslots.length;e++){this.gl.activeTexture(this.gl.TEXTURE0+e);this.gl.bindTexture(this.gl.TEXTURE_2D,null);this._textureslots[e]=null}this.emitEvent("beginFrame")}renderEnd(e){this._endMatrixStacks();this.popDepthTest();this.popDepthWrite();this.popDepthFunc();this.popCullFaceFacing();this.popCullFace();this.popBlend();this.popBlendMode();e.endFrame();this.emitEvent("endFrame")}getTexture(e){return this._textureslots[e]}hasFrameStarted(){return this._frameStarted}checkFrameStarted(e){if(!this._frameStarted){this._log.warn("frame not started "+e);Error.stackTraceLimit=25;E.utils.logStack();this.patch.printTriggerStack()}}setTexture(e,t,i){this.checkFrameStarted("cgl setTexture");
31014if(t===null)t=u.getEmptyTexture(this).tex;if(this._textureslots[e]!=t){this.gl.activeTexture(this.gl.TEXTURE0+e);this.gl.bindTexture(i||this.gl.TEXTURE_2D,t);this._textureslots[e]=t}return true}fullScreen(){if(this.canvas.requestFullscreen)this.canvas.requestFullscreen();else if(this.canvas.mozRequestFullScreen)this.canvas.mozRequestFullScreen();else if(this.canvas.webkitRequestFullscreen)this.canvas.webkitRequestFullscreen();else if(this.canvas.msRequestFullscreen)this.canvas.msRequestFullscreen()}printError(t){if(!this.checkGlErrors)return;let i=false;let n=this.gl.getError();if(n!=this.gl.NO_ERROR){let e="";if(n==this.gl.OUT_OF_MEMORY)e="OUT_OF_MEMORY";if(n==this.gl.INVALID_ENUM)e="INVALID_ENUM";if(n==this.gl.INVALID_OPERATION)e="INVALID_OPERATION";if(n==this.gl.INVALID_FRAMEBUFFER_OPERATION)e="INVALID_FRAMEBUFFER_OPERATION";if(n==this.gl.INVALID_VALUE)e="INVALID_VALUE";if(n==this.gl.CONTEXT_LOST_WEBGL){this.aborted=true;e="CONTEXT_LOST_WEBGL"}if(n==this.gl.NO_ERROR)e="NO_ERROR";i=true;this._log.warn("gl error ["+this.canvas.id+"]: ",t,n,e);if(this.canvas.id.includes("glGuiCanvas"))if(!this._loggedGlError){this.patch.printTriggerStack();this._log.stack("glerror");this._loggedGlError=true}}n=this.gl.getError();return i}_dispose(){this._simpleShader.dispose();this.gl=null}pushDepthTest(e){this._stackDepthTest.push(e);if(!e)this.gl.disable(this.gl.DEPTH_TEST);else this.gl.enable(this.gl.DEPTH_TEST)}stateDepthTest(){return this._stackDepthTest[this._stackDepthTest.length-1]}popDepthTest(){this._stackDepthTest.pop();if(!this._stackDepthTest[this._stackDepthTest.length-1])this.gl.disable(this.gl.DEPTH_TEST);else this.gl.enable(this.gl.DEPTH_TEST)}pushDepthWrite(e){e=e||false;this._stackDepthWrite.push(e);this.gl.depthMask(e)}stateDepthWrite(){return this._stackDepthWrite[this._stackDepthWrite.length-1]}popDepthWrite(){this._stackDepthWrite.pop();this.gl.depthMask(this._stackDepthWrite[this._stackDepthWrite.length-1]||false)}pushCullFace(e){this._stackCullFace.push(e);if(e)this.gl.enable(this.gl.CULL_FACE);else this.gl.disable(this.gl.CULL_FACE)}stateCullFace(){return this._stackCullFace[this._stackCullFace.length-1]}popCullFace(){this._stackCullFace.pop();if(this._stackCullFace[this._stackCullFace.length-1])this.gl.enable(this.gl.CULL_FACE);else this.gl.disable(this.gl.CULL_FACE)}pushCullFaceFacing(e){this._stackCullFaceFacing.push(e);this.gl.cullFace(this._stackCullFaceFacing[this._stackCullFaceFacing.length-1])}stateCullFaceFacing(){return this._stackCullFaceFacing[this._stackCullFaceFacing.length-1]}popCullFaceFacing(){this._stackCullFaceFacing.pop();if(this._stackCullFaceFacing.length>0)this.gl.cullFace(this._stackCullFaceFacing[this._stackCullFaceFacing.length-1])}pushDepthFunc(e){this._stackDepthFunc.push(e);this.gl.depthFunc(e)}stateDepthFunc(){if(this._stackDepthFunc.length>0)return this._stackDepthFunc[this._stackDepthFunc.length-1];return false}popDepthFunc(){this._stackDepthFunc.pop();if(this._stackDepthFunc.length>0)this.gl.depthFunc(this._stackDepthFunc[this._stackDepthFunc.length-1])}pushBlend(e){this._stackBlend.push(e);if(!e)this.gl.disable(this.gl.BLEND);else this.gl.enable(this.gl.BLEND)}popBlend(){this._stackBlend.pop();if(!this._stackBlend[this._stackBlend.length-1])this.gl.disable(this.gl.BLEND);else this.gl.enable(this.gl.BLEND)}stateBlend(){return this._stackBlend[this._stackBlend.length-1]}pushBlendMode(e,t){this._stackBlendMode.push(e);this._stackBlendModePremul.push(t);const i=this._stackBlendMode.length-1;this.pushBlend(this._stackBlendMode[i]!==p.BLEND_MODES.BLEND_NONE);this._setBlendMode(this._stackBlendMode[i],this._stackBlendModePremul[i])}popBlendMode(){this._stackBlendMode.pop();this._stackBlendModePremul.pop();const e=this._stackBlendMode.length-1;this.popBlend();if(e>=0)this._setBlendMode(this._stackBlendMode[e],this._stackBlendModePremul[e])}pushStencil(e){this._stackStencil.push(e);if(!e)this.gl.disable(this.gl.STENCIL_TEST);else this.gl.enable(this.gl.STENCIL_TEST)}popStencil(){this._stackStencil.pop();if(!this._stackStencil[this._stackStencil.length-1])this.gl.disable(this.gl.STENCIL_TEST);else this.gl.enable(this.gl.STENCIL_TEST)}glGetAttribLocation(e,t){const i=this.gl.getAttribLocation(e,t);return i}shouldDrawHelpers(e){if(this.tempData.shadowPass)return false;if(!e.patch.isEditorMode())return false;return gui.shouldDrawOverlay}_setBlendMode(e,t){const i=this.gl;if(e==p.BLEND_MODES.BLEND_NONE){}else if(e==p.BLEND_MODES.BLEND_ADD){if(t){i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD);i.blendFuncSeparate(i.ONE,i.ONE,i.ONE,i.ONE)}else{i.blendEquation(i.FUNC_ADD);i.blendFunc(i.SRC_ALPHA,i.ONE)}}else if(e==p.BLEND_MODES.BLEND_SUB){if(t){i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD);i.blendFuncSeparate(i.ZERO,i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ONE_MINUS_SRC_ALPHA)}else{i.blendEquation(i.FUNC_ADD);i.blendFunc(i.ZERO,i.ONE_MINUS_SRC_COLOR)}}else if(e==p.BLEND_MODES.BLEND_MUL){if(t){i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD);i.blendFuncSeparate(i.ZERO,i.SRC_COLOR,i.ZERO,i.SRC_ALPHA)}else{i.blendEquation(i.FUNC_ADD);i.blendFunc(i.ZERO,i.SRC_COLOR)}}else if(e==p.BLEND_MODES.BLEND_NORMAL){if(t){i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD);i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA)}else{i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD);i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA)}}else{this._log.log("setblendmode: unknown blendmode")}}createMesh(e,t){if(E.utils.isNumeric(t))t={glPrimitive:t};return new v(this,e,t)}setCursor(e){this._cursor=e}enableExtension(e){if(!this.gl)return null;if(this._enabledExtensions.hasOwnProperty(e))return this._enabledExtensions[e];const t=this.gl.getExtension(e);this._enabledExtensions[e]=t;if(!t)this._log.warn("[cgl_state] extension not available "+e);return t}
31014getErrorShader(){if(this.errorShader)return this.errorShader;this.errorShader=new F(this,"errormaterial");this.errorShader.setSource(F.getDefaultVertexShader(),F.getErrorFragmentShader());return this.errorShader}}const L={Framebuffer2:e,Geometry:b,BoundingBox:x,Marker:r,WirePoint:s,WireCube:o,MatrixStack:N,Mesh:v,MESH:S,ShaderLibMods:C,Shader:F,Uniform:c,MESHES:T,getWheelSpeed:H,getWheelDelta:X,Context:Z,Texture:u,TextureEffect:O,onLoadingAssetsFinished:j,ProfileData:y,UniColorShader:D,...p.BLEND_MODES,...p.SHADER,...p.MATH,...p.BLEND_MODES};window.CABLES=window.CABLES||{};window.CABLES.CGL=window.CABLES.CGL||L;window.CGL=window.CGL||L;E.Anim.slerpQuaternion=function(e,t,i,n,r,s){if(!E.Anim.slerpQuaternion.q1){E.Anim.slerpQuaternion.q1=quat.create();E.Anim.slerpQuaternion.q2=quat.create()}const a=i.getKeyIndex(e);let o=a+1;if(o>=i.keys.length)o=i.keys.length-1;if(a==o){quat.set(t,i.keys[a].value,n.keys[a].value,r.keys[a].value,s.keys[a].value)}else{const l=i.keys[a].time;const u=i.keys[o].time;const h=(e-l)/(u-l);quat.set(E.Anim.slerpQuaternion.q1,i.keys[a].value,n.keys[a].value,r.keys[a].value,s.keys[a].value);quat.set(E.Anim.slerpQuaternion.q2,i.keys[o].value,n.keys[o].value,r.keys[o].value,s.keys[o].value);quat.slerp(t,E.Anim.slerpQuaternion.q1,E.Anim.slerpQuaternion.q2,h)}return t};class Q{constructor(e,t,i){this.cgl=e;this._options=i;this.fb=null;let n=i.shader;this._useDefaultShader=true;if(i.shader)this._useDefaultShader=false;i.numRenderBuffers=i.numRenderBuffers||1;if(!n){n="".endl()+"IN vec2 texCoord;";for(let e=0;e<i.numRenderBuffers;e++){n=n.endl()+"UNI sampler2D tex"+e+";".endl()}n=n.endl()+"void main()".endl()+"{";if(i.numRenderBuffers==1){n=n.endl()+" outColor= texture(tex0,texCoord);".endl()}else for(let e=0;e<i.numRenderBuffers;e++){n=n.endl()+"outColor"+e+" = texture(tex"+e+",texCoord);".endl()}n=n.endl()+"}"}const r=i.vertexShader||"".endl()+"IN vec3 vPosition;".endl()+"IN vec2 attrTexCoord;".endl()+"OUT vec2 texCoord;".endl()+"void main()".endl()+"{".endl()+" texCoord=attrTexCoord;".endl()+" gl_Position = vec4(vPosition, 1.0);".endl()+"}";this.bgShader=new L.Shader(e,"corelib copytexture "+t);this.bgShader.setSource(r,n);if(!i.vertexShader)this.bgShader.ignoreMissingUniforms=true;new L.Uniform(this.bgShader,"t","tex",0);new L.Uniform(this.bgShader,"t","tex1",1);new L.Uniform(this.bgShader,"t","tex2",2);new L.Uniform(this.bgShader,"t","tex3",3);this.mesh=L.MESHES.getSimpleRect(this.cgl,"texEffectRect")}setSize(e,t){this._options.width=e;this._options.height=t}copy(e,t,i,n,r){const s=this.cgl;if(!e)e=L.Texture.getEmptyTexture(this.cgl);let a=this._options.width||e.width,o=this._options.height||e.height;if(this.fb){if(a<=0)a=8;if(o<=0)o=8;if(this.fb.getWidth()!=a||this.fb.getHeight()!=o)this.fb.setSize(a,o)}else{let e=L.Texture.FILTER_LINEAR;let t=L.Texture.WRAP_CLAMP_TO_EDGE;if(this._options.isFloatingPointTexture)e=L.Texture.FILTER_NEAREST;if(this._options.hasOwnProperty("filter"))e=this._options.filter;if(this._options.hasOwnProperty("wrap"))t=this._options.wrap;const l={isFloatingPointTexture:this._options.isFloatingPointTexture,pixelFormat:this._options.pixelFormat,numRenderBuffers:this._options.numRenderBuffers||1,filter:e,wrap:t};if(s.glVersion==1)this.fb=new L.Framebuffer(s,a,o,l);else this.fb=new L.Framebuffer2(s,a,o,l)}s.tempData.renderOffscreen=true;this.fb.renderStart(s);s.setTexture(0,e.tex);if(t)s.setTexture(1,t.tex);if(i)s.setTexture(2,i.tex);if(n)s.setTexture(3,n.tex);if(r)s.setTexture(4,r.tex);s.pushShader(this.bgShader);this.mesh.render(this.bgShader);s.popShader();this.fb.renderEnd();s.tempData.renderOffscreen=false;return this.fb.getTextureColor()}dispose(){if(this.fb)this.fb.dispose();if(this.bgShader)this.bgShader.dispose();if(this.mesh)this.mesh.dispose()}}})();var e=CGL=typeof CGL==="undefined"?{}:CGL;for(var t in J)e[t]=J[t];if(J.__esModule)Object.defineProperty(e,"__esModule",{value:true})})();(()=>{var r={};(()=>{r.d=(e,t)=>{for(var i in t){if(r.o(t,i)&&!r.o(e,i)){Object.defineProperty(e,i,{enumerable:true,get:t[i]})}}}})();(()=>{r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)})();(()=>{r.r=e=>{if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}
31014Object.defineProperty(e,"__esModule",{value:true})}})();var i={};(()=>{"use strict";r.r(i);r.d(i,{ShaderGraph:()=>u,ShaderGraphOp:()=>e,ShaderGraphProgram:()=>n});const l=CABLES;class e{constructor(e,t){e.sgOp=this;this._op=e;this._inPorts=[];this._outPorts=[];this._defines=[];this.enabled=true;this.info=null;if(t)this.parseCode(t);this._op.on("onLinkChanged",this.updateGraph.bind(this));this.addPortWatcher()}addPortWatcher(){for(let e=0;e<this._op.portsIn.length;e++){if(this._op.portsIn[e].type!=l.CONSTANTS.OP.OP_PORT_TYPE_OBJECT)continue;if(this._op.portsIn[e].uiAttribs.objType&&this._op.portsIn[e].uiAttribs.objType.indexOf("sg_")==0)this._op.portsIn[e].setUiAttribs({display:"sg_vec"});this._op.portsIn[e].on("change",this.updateGraph.bind(this))}}updateGraph(){for(let e=0;e<this._op.portsOut.length;e++){if(this._op.portsOut[e].type!=l.CONSTANTS.OP.OP_PORT_TYPE_OBJECT)continue;this._op.portsOut[e].setRef({})}}isTypeDef(e){return e=="void"||e=="float"||e=="sampler2D"||e=="vec2"||e=="vec3"||e=="vec4"||e=="void"||e=="mat4"||e=="mat3"||e=="mat2"||e=="out"}parseCode(e){let t=e;let o={functions:[],uniforms:[]};const l=t.split("\n");const i=t.split("\n");for(let e=0;e<i.length;e++)i[e]+="###line:"+e+":###";t=i.join("\n");t=t.replaceAll("{{","");t=t.replaceAll("}}","");t=t.replaceAll("\n{","{");t=t.replaceAll(";"," ;");t=t.replaceAll("("," ( ");t=t.replaceAll(")"," ) ");t=t.replaceAll(","," , ");t=t.replace(/ +(?= )/g,"");const u=t.split("\n");for(let a=0;a<u.length;a++){if(u[a].indexOf("{")>0&&u[a].indexOf("(")>0&&u[a].indexOf(")")>0){const h=u[a].split(" ");if(this.isTypeDef(h[0])){let t="";for(let e=a;e<u.length;e++)t+=u[e];const c=t.indexOf("{");let e=0;let i=0;for(i=c;i<t.length;i++){if(t.charAt(i)=="{")e++;if(t.charAt(i)=="}")e--;if(e==0)break}let n=t.substring(0,i+1);const g=n.split("###line:");let r=a,s=a-1;if(g.length>1){r=parseInt(g[1].split(":")[0]);s=parseInt(g[g.length-1].split(":")[0])}n="";for(let e=r;e<=s+1;e++)if(l[e])n+=l[e]+"\n";const f={name:h[1],type:h[0],params:[],src:n};f.uniqueName=h[0]+"_"+h[1];h.length=h.indexOf(")")+1;for(let e=3;e<h.length-2;e+=3){f.params.push({name:h[e+1],type:h[e]});f.uniqueName+="_"+h[e+0]+"_"+h[e+1]}o.functions.push(f)}}if(u[a].indexOf("UNI")==0||u[a].indexOf("uniform")==0){const h=u[a].split(" ");if(this.isTypeDef(h[1]))o.uniforms.push({name:h[2],type:h[1]})}}o.src=e;this.info=o;this.updatePorts(this.info);return o}updatePorts(t){const i={};this._op.shaderSrc=t.src;if(t.functions.length>0){const n=t.functions[t.functions.length-1];this._op.setTitle(n.name);this._op.shaderFunc=n.name;for(let t=0;t<n.params.length;t++){const e=this._op.getPort(n.params[t].name)||this._op.inObject(n.params[t].name);e.setUiAttribs({objType:"sg_"+n.params[t].type,ignoreObjTypeErrors:true});this._inPorts.push(e);i[n.params[t].name]=true}let e=this._op.getPort("Result");if(!e){e=this._op.outObject("Result");this._outPorts.push(e)}e.setUiAttribs({objType:"sg_"+n.type})}for(let e=0;e<this._inPorts.length;e++)if(!i[this._inPorts[e].name])this._inPorts[e].remove();this.addPortWatcher();this._op.refreshParams()}define(t,i){if(i===null||i===undefined)i="";if(typeof i=="object"){i.removeEventListener("change",i.onDefineChange);i.onDefineChange=e=>{this.define(t,e)};i.on("change",i.onDefineChange);i=i.get()}for(let e=0;e<this._defines.length;e++){if(this._defines[e][0]==t&&this._defines[e][1]==i)return;if(this._defines[e][0]==t){this._defines[e][1]=i;return}}this._defines.push([t,i]);this.updateGraph()}getDefines(){return this._defines}getDefine(t){for(let e=0;e<this._defines.length;e++)if(this._defines[e][0]==t)return this._defines[e][1];return null}hasDefine(t){for(let e=0;e<this._defines.length;e++)if(this._defines[e][0]==t)return true}removeDefine(t){for(let e=0;e<this._defines.length;e++){if(this._defines[e][0]==t){this._defines.splice(e,1);this.updateGraph();return}}}toggleDefine(e,t){if(t)this.define(e);else this.removeDefine(e);this.updateGraph()}}e.getMaxGenTypeFromPorts=(i,t)=>{const n=["sg_float","sg_vec2","sg_vec3","sg_vec4"];let r=0;for(let t=0;t<i.length;t++)for(let e=0;e<i[t].links.length;e++){const s=n.indexOf(i[t].links[e].getOtherPort(i[t]).uiAttribs.objType);r=Math.max(r,s)}const s=n[r];if(t)for(let e=0;e<t.length;e++)t[e].setUiAttribs({objType:s});return s};const t=CABLES.SHARED;const n=class extends t.Events{constructor(e,t,i){super();this._type=i;this._op=e;this._port=t;this.uniforms=[];this._opIdsHeadFuncSrc={};this._opIdsFuncCallSrc={};this._functionIdInHead={};this._headFuncSrc="";this._headUniSrc="";this._callFuncStack=[];this.finalSrc=""}setOpShaderId(e){if(!e.shaderId)e.shaderId=CGL.ShaderGraph.getNewId()}replaceId(e,t){this.setOpShaderId(e);return t.replaceAll("_ID","_"+e.shaderId)}addOpShaderFuncCode(i){if(!i.sgOp){console.warn("HAS NO SGOP!",i);return}if(this._opIdsHeadFuncSrc[i.id]){return}this._opIdsHeadFuncSrc[i.id]=true;if(i.sgOp&&i.sgOp._defines)for(let e=0;e<i.sgOp._defines.length;e++)this._headFuncSrc+="#define "+i.sgOp._defines[e][0]+"\n";if(i.sgOp.info){for(let t=0;t<i.sgOp.info.functions.length;t++){const n=i.sgOp.info.functions[t];if(this._functionIdInHead[n.uniqueName])continue;if(!n.name.includes("_ID"))this._functionIdInHead[n.uniqueName]=true;let e=n.src;e=this.replaceId(i,e);this._headFuncSrc+=e}}if(i.shaderUniforms){for(let e=0;e<i.shaderUniforms.length;e++){const t=i.shaderUniforms[e];if(!t.static){this._headUniSrc+="uniform "+CGL.Uniform.glslTypeString(t.type)+" "+t.name+";".endl();this.uniforms.push(t)}else this._headUniSrc+=this.uniformAsStaticVar(t)}}}uniformAsStaticVar(t){const i=CGL.Uniform.glslTypeString(t.type);let n="";if(i=="float"){let e=String(t.ports[0].get());if(!e.includes("."))e+=".";n=i+" "+t.name+" = "+e+";".endl()}else{n=i+" "+t.name+"="+i+"(";for(let e=0;e<t.ports.length;e++){n+=t.ports[e].get();if(e!=t.ports.length-1)n+=","}n+=");".endl()}return n}callFunc(i,e){this.setOpShaderId(i);let n=" ";const t="var_"+i.getTitle()+"_"+i.shaderId;if(e)n+=u.typeConv(e)+" "+t+" = ";if(this._opIdsFuncCallSrc[i.shaderId]){if(t)return t;return}this._opIdsFuncCallSrc[i.shaderId]=true;n+=this.replaceId(i,i.shaderFunc||"")+"(";
31014this.addOpShaderFuncCode(i);const r=this.countObjectInputPorts(i);let s=0;for(let e=0;e<i.portsIn.length;e++){let t="";const a=i.portsIn[e];if(a.uiAttribs.objType=="sg_void")continue;if(a.type!=l.CONSTANTS.OP.OP_PORT_TYPE_OBJECT)continue;if(a.isLinked()){for(let e=0;e<a.links.length;e++){const o=a.links[e].getOtherPort(a);t=this._getPortParamStr(o,a.uiAttribs.objType);this.addOpShaderFuncCode(o.op)}}else{this.addOpShaderFuncCode(a.op);t=u.getDefaultParameter(a.uiAttribs.objType)}if(a.op.shaderCodeOperator){n+=t;if(s<r-1)n+=" "+a.op.shaderCodeOperator+" "}else if(t){n+=t;if(s<r-1)n+=", "}s++}n+=");";this._callFuncStack.push(n);return t}countObjectInputPorts(t){let i=0;for(let e=0;e<t.portsIn.length;e++)if(t.portsIn[e].type==l.CONSTANTS.OP.OP_PORT_TYPE_OBJECT)i++;return i}_getPortParamStr(e,t){let i="";if(e.op.shaderVar){i=e.op.shaderVar}else if(e.direction==l.CONSTANTS.PORT.PORT_DIR_OUT){i+=this.callFunc(e.op,e.uiAttribs.objType)}if(t&&t!=e.uiAttribs.objType){i=u.convertTypes(t,e.uiAttribs.objType,i)}return i}compile(){const t=this._port;const i=t.links;this.uniforms=[];this._callFuncStack=[];this._functionIdInHead={};this._opIdsFuncCallSrc={};this._opIdsHeadFuncSrc={};this._headFuncSrc="";this._headUniSrc="";let n="";for(let e=0;e<i.length;e++){const r=i[e];n+=this.callFunc(r.getOtherPort(t).op)+";".endl()}n=this._callFuncStack.join("\n");let e="".endl()+"{{MODULES_HEAD}}".endl().endl();if(this._type=="frag")e+="IN vec2 texCoord;".endl().endl();if(this._type=="vert")e+="IN vec3 vPosition;".endl()+"IN vec2 attrTexCoord;".endl()+"OUT vec2 texCoord;".endl().endl();if(this._type=="vert")e+="".endl()+"UNI mat4 projMatrix;".endl().endl()+"UNI mat4 viewMatrix;".endl().endl()+"UNI mat4 modelMatrix;".endl().endl();e+=this._headUniSrc.endl().endl()+this._headFuncSrc.endl().endl()+"void main()".endl()+"{".endl();if(this._type=="frag")e+=" {{MODULE_BEGIN_FRAG}}".endl();if(this._type=="vert")e+=" {{MODULE_BEGIN_VERTEX}}".endl();e+=n.endl()+"}".endl();this.finalSrc=e;this.emitEvent("compiled")}};const u=class extends t.Events{constructor(e,t,i){super();this._op=e;this._portFrag=t;this._portVert=i;this.progFrag=new n(e,t,"frag");this.progVert=new n(e,i,"vert");this.progFrag.on("compiled",()=>{this.emitEvent("compiled")});this.progVert.on("compiled",()=>{this.emitEvent("compiled")});t.on("change",()=>{this.progFrag.compile()});i.on("change",this.updateVertex.bind(this));i.on("onLinkChanged",this.updateVertex.bind(this))}getUniforms(){const t=[];for(let e=0;e<this.progFrag.uniforms.length;e++)t.push(this.progFrag.uniforms[e]);for(let e=0;e<this.progVert.uniforms.length;e++)t.push(this.progVert.uniforms[e]);return t}updateVertex(){console.log("update vertex",this._portVert.isLinked());if(this._portVert.isLinked())this.progVert.compile();else{this.progVert.finalSrc=CGL.Shader.getDefaultVertexShader();this.emitEvent("compiled")}}getSrcFrag(){return this.progFrag.finalSrc}getSrcVert(){return this.progVert.finalSrc||CGL.Shader.getDefaultVertexShader()}};u.convertTypes=function(e,t,i){if(e=="sg_genType")return i;if(t=="sg_texture"&&e=="sg_vec3")return i+".xyz";if(t=="sg_vec4"&&e=="sg_vec3")return i+".xyz";if(t=="sg_vec4"&&e=="sg_vec2")return i+".xy";if(t=="sg_vec4"&&e=="sg_float")return i+".x";if(t=="sg_vec3"&&e=="sg_vec2")return i+".xy";if(t=="sg_vec3"&&e=="sg_float")return i+".x";if(t=="sg_vec2"&&e=="sg_float")return i+".x";if(t=="sg_vec3"&&e=="sg_vec4")return"vec4("+i+", 0.)";if(t=="sg_vec2"&&e=="sg_vec3")return"vec3("+i+", 0.)";if(t=="sg_vec2"&&e=="sg_vec4")return"vec4("+i+", 0., 0.)";if(t=="sg_float"&&e=="sg_vec2")return"vec2("+i+","+i+")";if(t=="sg_float"&&e=="sg_vec3")return"vec3("+i+","+i+","+i+")";if(t=="sg_float"&&e=="sg_vec4")return"vec4("+i+","+i+","+i+", 0.0)";return"/* conversionfail: "+t+"->"+e+" */"};u.getDefaultParameter=function(e){if(e=="sg_vec4")return"vec4(0., 0., 0., 0.)";if(e=="sg_vec3")return"vec3(0., 0., 0.)";if(e=="sg_vec2")return"vec2(0., 0.)";if(e=="sg_float")return"0.";if(e=="sg_genType")return"0.";return"/* no default: "+e+"*/"};u.typeConv=function(e){return e.substr(3)};u.shaderIdCounter=u.shaderIdCounter||1;u.getNewId=()=>{return++u.shaderIdCounter}})();var e=CGL=typeof CGL==="undefined"?{}:CGL;
31014for(var t in i)e[t]=i[t];if(i.__esModule)Object.defineProperty(e,"__esModule",{value:true})})();(()=>{var n={};(()=>{n.d=(e,t)=>{for(var i in t){if(n.o(t,i)&&!n.o(e,i)){Object.defineProperty(e,i,{enumerable:true,get:t[i]})}}}})();(()=>{n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)})();(()=>{n.r=e=>{if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(e,"__esModule",{value:true})}})();var i={};(()=>{"use strict";n.r(i);n.d(i,{PixelReader:()=>t});const e=CABLES.SHARED;class t{constructor(){this._log=new e.Logger("LoadingStatus");this.pixelData=null;this._finishedFence=true;this._size=0;this._pbo=null}_fence(s){const a=s.gl;this._finishedFence=false;return new Promise(function(t,i){if(s.aborted)return;let n=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);if(!n)return;a.flush();function r(){if(s.aborted)return;const e=a.clientWaitSync(n,0,0);if(e==a.WAIT_FAILED){console.error("fence wait failed");if(i)i()}else if(e==a.TIMEOUT_EXPIRED){return setTimeout(r,0)}else if(e==a.CONDITION_SATISFIED){t();a.deleteSync(n)}else if(e==a.ALREADY_SIGNALED){t();a.deleteSync(n)}else{this._log.log("unknown fence status",e)}}r()})}read(i,n,e,r,s,a,o,t){if(CABLES.UI)if(!CABLES.UI.loaded||performance.now()-CABLES.UI.loadedTime<1e3)return;if(!this._finishedFence)return;const l=i.gl;let u=1;if(i.aborted)return;if(!n)return;if(e===CGL.Texture.TYPE_FLOAT)e=CGL.Texture.PFORMATSTR_RGBA32F;let h=CGL.Texture.isPixelFormatFloat(e);if(h)u=4;if(CGL.Texture.isPixelFormatHalfFloat(e))u=2;const c=CGL.Texture.setUpGlPixelFormat(i,e);const g=c.numColorChannels*a*o;if(a==0||o==0||g==0)return;if(!this._pixelData||this._size!=g*u){if(u>1)this._pixelData=new Float32Array(g);else this._pixelData=new Uint8Array(g);this._size=g*u}let f=l.UNSIGNED_BYTE;if(u>1)f=l.FLOAT;if(this._size==0||!this._pixelData){this._log.error("readpixel size 0",this._size,a,o);return}if(this._finishedFence){this._pbo=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,this._pbo);l.bufferData(l.PIXEL_PACK_BUFFER,this._pixelData.byteLength,l.DYNAMIC_READ);l.bindFramebuffer(l.FRAMEBUFFER,n);l.bindBuffer(l.PIXEL_PACK_BUFFER,this._pbo);i.profileData.profileFencedPixelRead++;if(this._size!=g*u)this._log.error("buffer size invalid",g,a,o,u);let e=c.glDataType;if(u>1)e=i.gl.FLOAT;let t=c.glDataFormat;l.readPixels(r,s,a,o,t,e,0);l.bindBuffer(l.PIXEL_PACK_BUFFER,null);l.bindFramebuffer(l.FRAMEBUFFER,null)}let d=this._pixelData.byteLength;if(this._finishedFence&&this._pbo)this._fence(i).then(e=>{this._wasTriggered=false;this._finishedFence=true;if(!e&&this._pixelData&&this._pixelData.byteLength==d){l.bindBuffer(l.PIXEL_PACK_BUFFER,this._pbo);l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,this._pixelData);l.bindBuffer(l.PIXEL_PACK_BUFFER,null);if(t)t(this._pixelData)}l.deleteBuffer(this._pbo);this._pbo=null});return true}}})();var e=CGL=typeof CGL==="undefined"?{}:CGL;for(var t in i)e[t]=i[t];if(i.__esModule)Object.defineProperty(e,"__esModule",{value:true})})();
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.