GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — GaiaMod-Render/src/RenderWebGL.js at develop · GaiaMod-Main/GaiaMod-Render Expand file tree/ Copy pathRenderWebGL.jsMore file actions 2818 lines (2493 loc) · 106 KB / Copy pathRenderWebGL.jsFile metadata and controls2818 lines (2493 loc) · 106 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 const EventEmitter = require('events'); const hull = require('hull.js'); const twgl = require('twgl.js'); const SVGRenderer = require('scratch-svg-renderer'); const Skin = require('./Skin'); const BitmapSkin = require('./BitmapSkin'); const Drawable = require('./Drawable'); const Rectangle = require('./Rectangle'); const PenSkin = require('./PenSkin'); const RenderConstants = require('./RenderConstants'); const ShaderManager = require('./ShaderManager'); const SVGSkin = require('./SVGSkin'); const TextBubbleSkin = require('./TextBubbleSkin'); const TextCostumeSkin = require('./TextCostumeSkin'); const EffectTransform = require('./EffectTransform'); const CanvasMeasurementProvider = require('./util/canvas-measurement-provider'); const log = require('./util/log'); const __isTouchingDrawablesPoint = twgl.v3.create(); const __candidatesBounds = new Rectangle(); const __fenceBounds = new Rectangle(); const __touchingColor = new Uint8ClampedArray(4); const __blendColor = new Uint8ClampedArray(4); // More pixels than this and we give up to the GPU and take the cost of readPixels // Width * Height * Number of drawables at location const __cpuTouchingColorPixelCount = 4e4; /** * @callback RenderWebGL#idFilterFunc * @param {int} drawableID The ID to filter. * @return {bool} True if the ID passes the filter, otherwise false. */ /** * Maximum touch size for a picking check. * @todo Figure out a reasonable max size. Maybe this should be configurable? * @type {Array<int>} * @memberof RenderWebGL */ const MAX_TOUCH_SIZE = [3, 3]; /** * Passed to the uniforms for mask in touching color */ const MASK_TOUCHING_COLOR_TOLERANCE = 2; /** * Maximum number of pixels in either dimension of "extracted drawable" data * @type {int} */ const MAX_EXTRACTED_DRAWABLE_DIMENSION = 2048; /** * Determines if the mask color is "close enough" (only test the 6 top bits for * each color). These bit masks are what scratch 2 used to use, so we do the same. * @param {Uint8Array} a A color3b or color4b value. * @param {Uint8Array} b A color3b or color4b value. * @returns {boolean} If the colors match within the parameters. */ const maskMatches = (a, b) => // has some non-alpha component to test against a[3] > 0 && (a[0] & 0b11111100) === (b[0] & 0b11111100) && (a[1] & 0b11111100) === (b[1] & 0b11111100) && (a[2] & 0b11111100) === (b[2] & 0b11111100); /** * Determines if the given color is "close enough" (only test the 5 top bits for * red and green, 4 bits for blue). These bit masks are what scratch 2 used to use, * so we do the same. * @param {Uint8Array} a A color3b or color4b value. * @param {Uint8Array} b A color3b or color4b value / or a larger array when used with offsets * @param {number} offset An offset into the `b` array, which lets you use a larger array to test * multiple values at the same time. * @returns {boolean} If the colors match within the parameters. */ const colorMatches = (a, b, offset) => (a[0] & 0b11111000) === (b[offset + 0] & 0b11111000) && (a[1] & 0b11111000) === (b[offset + 1] & 0b11111000) && (a[2] & 0b11110000) === (b[offset + 2] & 0b11110000); /** * Sprite Fencing - The number of pixels a sprite is required to leave remaining * onscreen around the edge of the staging area. * @type {number} */ const FENCE_WIDTH = 15; // Loading text wrapper takes a while because of some of its dependencies, so only do so when needed. let _TextWrapper; const lazilyLoadTextWrapper = () => { if (!_TextWrapper) { // eslint-disable-next-line global-require _TextWrapper = require('./util/text-wrapper'); } return _TextWrapper; }; let _stylesheet; const loadStyles = () => { if (!_stylesheet) { _stylesheet = document.createElement('style'); // eslint-disable-next-line global-require _stylesheet.textContent = require('!raw-loader!./renderer.css'); _stylesheet.className = 'scratch-render-styles'; document.head.appendChild(_stylesheet); } }; class RenderWebGL extends EventEmitter { /** * Check if this environment appears to support this renderer before attempting to create an instance. * Catching an exception from the constructor is also a valid way to test for (lack of) support. * @param {canvas} [optCanvas] - An optional canvas to use for the test. Otherwise a temporary canvas will be used. * @returns {boolean} - True if this environment appears to support this renderer, false otherwise. */ static isSupported (optCanvas) { try { optCanvas = optCanvas || document.createElement('canvas'); const options = { alpha: true, stencil: true, antialias: false, xrCompatible: true }; return !!( optCanvas.getContext('webgl2', options) || optCanvas.getContext('experimental-webgl', options) || optCanvas.getContext('webgl', options) ); } catch (e) { return false; } } /** * Ask TWGL to create a rendering context with the attributes used by this renderer. * @param {canvas} canvas - attach the context to this canvas. * @returns {WebGLRenderingContext} - a TWGL rendering context (backed by either WebGL 1.0 or 2.0). * @private */ static _getContext (canvas) { const contextAttribs = { alpha: true, stencil: true, antialias: false, xrCompatible: true, powerPreference: RenderWebGL.powerPreference }; // getWebGLContext = try WebGL 1.0 only // getContext = try WebGL 2.0 and if that doesn't work, try WebGL 1.0 // getWebGLContext || getContext = try WebGL 1.0 and if that doesn't work, try WebGL 2.0 return ( twgl.getContext(canvas, contextAttribs) || twgl.getWebGLContext(canvas, contextAttribs) ); } /** * Create a renderer for drawing Scratch sprites to a canvas using WebGL. * Coordinates will default to Scratch 2.0 values if unspecified. * The stage's "native" size will be calculated from the these coordinates. * For example, the defaults result in a native size of 480x360. * Queries such as "touching color?" will always execute at the native size. * @see RenderWebGL#setStageSize * @see RenderWebGL#resize * @param {canvas} canvas The canvas to draw onto. * @param {int} [xLeft=-240] The x-coordinate of the left edge. * @param {int} [xRight=240] The x-coordinate of the right edge. * @param {int} [yBottom=-180] The y-coordinate of the bottom edge. * @param {int} [yTop=180] The y-coordinate of the top edge. * @constructor * @listens RenderWebGL#event:NativeSizeChanged */ constructor (canvas, xLeft, xRight, yBottom, yTop) { super(); /** @type {WebGLRenderingContext} */ const gl = (this._gl = RenderWebGL._getContext(canvas)); if (!gl) { throw new Error( 'Could not get WebGL context: this browser or environment may not support WebGL.' ); } /** @type {RenderWebGL.UseGpuModes} */ this._useGpuMode = RenderWebGL.UseGpuModes.Automatic; /** @type {Drawable[]} */ this._allDrawables = []; /** @type {Skin[]} */ this._allSkins = []; /** @type {Array<int>} */ this._drawList = []; // A list of layer group names in the order they should appear // from furthest back to furthest in front. /** @type {Array<String>} */ this._groupOrdering = []; /** * @typedef LayerGroup * @property {int} groupIndex The relative position of this layer group in the group ordering * @property {int} drawListOffset The absolute position of this layer group in the draw list * This number gets updated as drawables get added to or deleted from the draw list. */ // Map of group name to layer group /** @type {Object.<string, LayerGroup>} */ this._layerGroups = {}; /** @type {int} */ this._nextDrawableId = RenderConstants.ID_NONE + 1; /** @type {int} */ this._nextSkinId = RenderConstants.ID_NONE + 1; /** @type {module:twgl/m4.Mat4} */ this._projection = twgl.m4.identity(); /** @type {ShaderManager} */ this._shaderManager = new ShaderManager(gl); /** @type {any} */ this._regionId = null; /** @type {function} */ this._exitRegion = null; /** @type {object} */ this._backgroundDrawRegionId = { enter: () => this._enterDrawBackground(), exit: () => this._exitDrawBackground() }; /** @type {Array.<snapshotCallback>} */ this._snapshotCallbacks = []; /** @type {Array<number>} */ // Don't set this directly-- use setBackgroundColor so it stays in sync with _backgroundColor3b this._backgroundColor4f = [0, 0, 0, 1]; /** @type {Uint8ClampedArray} */ // Don't set this directly-- use setBackgroundColor so it stays in sync with _backgroundColor4f this._backgroundColor3b = new Uint8ClampedArray(3); // tw: track id of pen skin this._penSkinId = null; // pm: extra rendering settings this.customRenderConfig = { textCostumeResolution: { capped: false, fixed: false, value: 1 } }; this.useHighQualityRender = true; this.offscreenTouching = false; this.dirty = true; /** * Element that contains all overlays. * @type {HTMLElement} */ this.overlayContainer = document.createElement('div'); this.overlayContainer.className = 'scratch-render-overlays'; /** * @type {Array<{container: HTMLElement; userElement: HTMLElement; mode: string;}>} */ this._overlays = []; loadStyles(); this._createGeometry(); this.on(RenderConstants.Events.NativeSizeChanged, this.onNativeSizeChanged); this.setBackgroundColor(1, 1, 1); this.setStageSize( xLeft || -240, xRight || 240, yBottom || -180, yTop || 180 ); this.resize(this._nativeSize[0], this._nativeSize[1]); gl.disable(gl.DEPTH_TEST); /** @todo disable when no partial transparency? */ gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); /** * Whether or not the renderer should be drawing to an XR layer. * Used for the Virtual Reality extension. */ this.xrEnabled = false; /** * Whether or not the renderer should be drawing the image split for VR screens. * Used for the Virtual Reality extension. */ this.xrSplitting = false; /** * An offset where the XR splitting will shift closer to the center. * Used for the Virtual Reality extension. */ this.xrSplitOffset = 0; /** * The layer that should be drawn to. * Used for the Virtual Reality extension. */ this.xrLayer = null; /** * set to true by default as this is still expieremental */ this.renderOffscreen = true; /** * Whether projects should be able to access the contents of private skins such as webcams. * If set to false, routines such as isTouchingColor will ignore private skins. * Private skins will still be rendered on the canvas regardless of this setting. * This is set to true by default for compatibility with vanilla Scratch. * @type {boolean} */ this.allowPrivateSkinAccess = true; /** * Suggested maximum texture size in texels. This is not a hard limit. * Defualt value is same as Scratch's SVGSkin max. * @type {number} */ this.maxTextureDimension = 2048; /** * Custom fonts, used by SVGs. Maps font families to their @font-face statement. * Do not modify directly -- use {@link setCustomFonts}. * @type {Record<string, string>} */ this.customFonts = {}; /** * <style> element used for custom fonts. * @type {HTMLStyleElement|null} */ this._customFontStyles = null; /** * Export internals for third-party extensions. */ this.exports = { twgl, SVGRenderer, Drawable, Skin, BitmapSkin, TextBubbleSkin, PenSkin, SVGSkin, CanvasMeasurementProvider, Rectangle }; } setRenderOffscreen (bool) { this.renderOffscreen = bool; this.dirty = true; this.draw(); } // tw: implement high quality pen option setUseHighQualityRender (enabled) { this.dirty = true; this.useHighQualityRender = enabled; this.emit(RenderConstants.Events.UseHighQualityRenderChanged, enabled); this._updateRenderQuality(); } _updateRenderQuality () { if (this._penSkinId !== null) { const skin = this._allSkins[this._penSkinId]; if (skin) { if (this.useHighQualityRender) { skin.setRenderQuality(this.canvas.width / this._nativeSize[0]); } else { skin.setRenderQuality(1); } } } for (const drawable of this._allDrawables) { if (drawable) { drawable.setHighQuality(this.useHighQualityRender); } } } /** * Configure whether the renderer should let projects access private skins. * @param {boolean} allowPrivateSkinAccess Whether projects can access private skins or not. */ setPrivateSkinAccess (allowPrivateSkinAccess) { this.allowPrivateSkinAccess = allowPrivateSkinAccess; this.emit( RenderConstants.Events.AllowPrivateSkinAccessChanged, allowPrivateSkinAccess ); } /** * Modify the suggested maximum texture dimension. This should be set before any skins are created. * @param {number} newMax The new maximum in texels */ setMaxTextureDimension (newMax) { const hardwareLimit = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE); this.maxTextureDimension = Math.min(newMax, hardwareLimit); } /** * @returns {WebGLRenderingContext} the WebGL rendering context associated with this renderer. */ get gl () { return this._gl; } /** * @returns {HTMLCanvasElement} the canvas of the WebGL rendering context associated with this renderer. */ get canvas () { return this._gl && this._gl.canvas; } /** * Set the physical size of the stage in device-independent pixels. * This will be multiplied by the device's pixel ratio on high-DPI displays. * @param {int} pixelsWide The desired width in device-independent pixels. * @param {int} pixelsTall The desired height in device-independent pixels. */ resize (pixelsWide, pixelsTall) { const {canvas} = this._gl; const pixelRatio = window.devicePixelRatio || 1; const newWidth = pixelsWide * pixelRatio; const newHeight = pixelsTall * pixelRatio; // Certain operations, such as moving the color picker, call `resize` once per frame, even though the canvas // size doesn't change. To avoid unnecessary canvas updates, check that we *really* need to resize the canvas. if (canvas.width !== newWidth || canvas.height !== newHeight) { canvas.width = newWidth; canvas.height = newHeight; this._updateRenderQuality(); this._updateOverlays(); // Resizing the canvas causes it to be cleared, so redraw it. this.dirty = true; this.draw(); } } /** * Set the background color for the stage. The stage will be cleared with this * color each frame. * @param {number} red The red component for the background. * @param {number} green The green component for the background. * @param {number} blue The blue component for the background. * @param {number} alpha The alpha component for the background. */ setBackgroundColor (red, green, blue, alpha = 1) { this.dirty = true; // WebGL will want the color to be pre-multiplied. this._backgroundColor4f[0] = red * alpha; this._backgroundColor4f[1] = green * alpha; this._backgroundColor4f[2] = blue * alpha; this._backgroundColor4f[3] = alpha; this._backgroundColor3b[0] = red * alpha * 255; this._backgroundColor3b[1] = green * alpha * 255; this._backgroundColor3b[2] = blue * alpha * 255; } /** * Tell the renderer to draw various debug information to the provided canvas * during certain operations. * @param {canvas} canvas The canvas to use for debug output. */ setDebugCanvas (canvas) { this._debugCanvas = canvas; } /** * Control the use of the GPU or CPU paths in `isTouchingColor`. * @param {RenderWebGL.UseGpuModes} useGpuMode - automatically decide, force CPU, or force GPU. */ setUseGpuMode (useGpuMode) { this._useGpuMode = useGpuMode; } /** * Set logical size of the stage in Scratch units. * @param {int} xLeft The left edge's x-coordinate. Scratch 2 uses -240. * @param {int} xRight The right edge's x-coordinate. Scratch 2 uses 240. * @param {int} yBottom The bottom edge's y-coordinate. Scratch 2 uses -180. * @param {int} yTop The top edge's y-coordinate. Scratch 2 uses 180. */ setStageSize (xLeft, xRight, yBottom, yTop) { this._xLeft = xLeft; this._xRight = xRight; this._yBottom = yBottom; this._yTop = yTop; // swap yBottom & yTop to fit Scratch convention of +y=up this._projection = twgl.m4.ortho(xLeft, xRight, yBottom, yTop, -1, 1); this._setNativeSize(Math.abs(xRight - xLeft), Math.abs(yBottom - yTop)); } /** * @return {Array<int>} the "native" size of the stage, which is used for pen, query renders, etc. */ getNativeSize () { return [this._nativeSize[0], this._nativeSize[1]]; } /** * Set the "native" size of the stage, which is used for pen, query renders, etc. * @param {int} width - the new width to set. * @param {int} height - the new height to set. * @private * @fires RenderWebGL#event:NativeSizeChanged */ _setNativeSize (width, height) { this._nativeSize = [width, height]; this._updateOverlays(); this.emit(RenderConstants.Events.NativeSizeChanged, { newSize: this._nativeSize }); } /** * @param {HTMLElement} element HTML element * @param {string} mode Resize mode * @returns {*} Internal overlay object */ addOverlay (element, mode = 'scale') { const container = document.createElement('div'); container.appendChild(element); this.overlayContainer.appendChild(container); const overlay = { container, userElement: element, mode }; this._overlays.push(overlay); this._updateOverlays(); return overlay; } /** * @param {HTMLElement} element HTML element */ removeOverlay (element) { const overlayIndex = this._overlays.findIndex( i => i.userElement === element ); if (overlayIndex !== -1) { this._overlays[overlayIndex].container.remove(); this._overlays.splice(overlayIndex, 1); } } _updateOverlays () { const [nativeWidth, nativeHeight] = this._nativeSize; const dpiIndependentWidth = this.canvas.width / window.devicePixelRatio; const dpiIndependentHeight = this.canvas.height / window.devicePixelRatio; this.overlayContainer.style.width = `${dpiIndependentWidth}px`; this.overlayContainer.style.height = `${dpiIndependentHeight}px`; for (const overlay of this._overlays) { const container = overlay.container; if (overlay.mode === 'scale' || overlay.mode === 'scale-centered') { const xScale = dpiIndependentWidth / nativeWidth; const yScale = dpiIndependentHeight / nativeHeight; container.style.width = `${nativeWidth}px`; container.style.height = `${nativeHeight}px`; const scale = `scale(${xScale}, ${yScale})`; container.style.transformOrigin = 'top left'; if (overlay.mode === 'scale') { container.style.transform = scale; } else { const shiftToCenter = `translate(${nativeWidth / 2}px, ${nativeHeight / 2}px)`; container.style.transform = `${scale} ${shiftToCenter}`; } } else { container.style.transform = ''; container.style.width = '100%'; container.style.height = '100%'; } } } /** * Create a new bitmap skin from a snapshot of the provided bitmap data. * @param {ImageData|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} bitmapData - new contents for this skin. * @param {!int} [costumeResolution=1] - The resolution to use for this bitmap. * @param {?Array<number>} [rotationCenter] Optional: rotation center of the skin. If not supplied, the center of * the skin will be used. * @returns {!int} the ID for the new skin. */ createBitmapSkin (bitmapData, costumeResolution, rotationCenter) { const skinId = this._nextSkinId++; const newSkin = new BitmapSkin(skinId, this); newSkin.setBitmap(bitmapData, costumeResolution, rotationCenter); this._allSkins[skinId] = newSkin; return skinId; } /** * Create a new SVG skin. * @param {!string} svgData - new SVG to use. * @param {?Array<number>} rotationCenter Optional: rotation center of the skin. If not supplied, the center of the * skin will be used * @returns {!int} the ID for the new skin. */ createSVGSkin (svgData, rotationCenter) { const skinId = this._nextSkinId++; const newSkin = new SVGSkin(skinId, this); newSkin.setSVG(svgData, rotationCenter); this._allSkins[skinId] = newSkin; return skinId; } /** * Create a new PenSkin - a skin which implements a Scratch pen layer. * @returns {!int} the ID for the new skin. */ createPenSkin () { const skinId = this._nextSkinId++; const newSkin = new PenSkin(skinId, this); this._allSkins[skinId] = newSkin; // tw: track id of pen skin this._penSkinId = skinId; // tw: high quality pen may have been enabled before the pen skin was created this._updateRenderQuality(); return skinId; } /** * Create a new SVG skin using the text skin creator. The rotation center * is always placed at the top left. * @param {!string} type - either "say" or "think". * @param {!string} text - the text for the bubble. * @param {!boolean} pointsLeft - which side the bubble is pointing. * @param {!object} props - text props. * @returns {!int} the ID for the new skin. */ createTextSkin (type, text, pointsLeft, props) { const skinId = this._nextSkinId++; const newSkin = new TextBubbleSkin(skinId, this); newSkin.setTextBubble(type, text, pointsLeft, props); this._allSkins[skinId] = newSkin; return skinId; } /** * Update an existing SVG skin, or create an SVG skin if the previous skin was not SVG. * @param {!int} skinId the ID for the skin to change. * @param {!string} svgData - new SVG to use. * @param {?Array<number>} rotationCenter Optional: rotation center of the skin. If not supplied, the center of the * skin will be used */ updateSVGSkin (skinId, svgData, rotationCenter) { if (this._allSkins[skinId] instanceof SVGSkin) { this._allSkins[skinId].setSVG(svgData, rotationCenter); return; } const newSkin = new SVGSkin(skinId, this); newSkin.setSVG(svgData, rotationCenter); this._reskin(skinId, newSkin); } /** * Update an existing bitmap skin, or create a bitmap skin if the previous skin was not bitmap. * @param {!int} skinId the ID for the skin to change. * @param {!ImageData|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} imgData - new contents for this skin. * @param {!number} bitmapResolution - the resolution scale for a bitmap costume. * @param {?Array<number>} rotationCenter Optional: rotation center of the skin. If not supplied, the center of the * skin will be used */ updateBitmapSkin (skinId, imgData, bitmapResolution, rotationCenter) { if (this._allSkins[skinId] instanceof BitmapSkin) { this._allSkins[skinId].setBitmap( imgData, bitmapResolution, rotationCenter ); return; } const newSkin = new BitmapSkin(skinId, this); newSkin.setBitmap(imgData, bitmapResolution, rotationCenter); this._reskin(skinId, newSkin); } _reskin (skinId, newSkin) { const oldSkin = this._allSkins[skinId]; this._allSkins[skinId] = newSkin; // Tell drawables to update for (const drawable of this._allDrawables) { if (drawable && drawable.skin === oldSkin) { drawable.skin = newSkin; } } oldSkin.dispose(); } /** * Update a skin using the text skin creator. * @param {!int} skinId the ID for the skin to change. * @param {!string} type - either "say" or "think". * @param {!string} text - the text for the bubble. * @param {!boolean} pointsLeft - which side the bubble is pointing. * @param {!object} props - the text props. */ updateTextSkin (skinId, type, text, pointsLeft, props) { if (this._allSkins[skinId] instanceof TextBubbleSkin) { this._allSkins[skinId].setTextBubble(type, text, pointsLeft, props); return; } const newSkin = new TextBubbleSkin(skinId, this); newSkin.setTextBubble(type, text, pointsLeft, props); this._reskin(skinId, newSkin); } /** * Update a skin using the text costume svg creator. * @param {!object} textState the state to apply. * @param {!boolean} pointsLeft - which side the bubble is pointing. * @returns {number} the the skin id */ updateTextCostumeSkin (textState) { // update existing skin if ( textState.skinId && this._allSkins[textState.skinId] instanceof TextCostumeSkin ) { this._allSkins[textState.skinId].setTextAndStyle(textState); return textState.skinId; } // create and update a new skin const skinId = this._nextSkinId++; const newSkin = new TextCostumeSkin(skinId, this); this._allSkins[skinId] = newSkin; newSkin.setTextAndStyle(textState); // this._reskin(skinId, newSkin); // this is erroring- might be necessary? return skinId; } /** * Destroy an existing skin. Do not use the skin or its ID after calling this. * @param {!int} skinId - The ID of the skin to destroy. */ destroySkin (skinId) { const oldSkin = this._allSkins[skinId]; oldSkin.dispose(); delete this._allSkins[skinId]; } /** * Create a new Drawable and add it to the scene. * @param {string} group Layer group to add the drawable to * @returns {int} The ID of the new Drawable. */ createDrawable (group) { if ( !group || !Object.prototype.hasOwnProperty.call(this._layerGroups, group) ) { log.warn('Cannot create a drawable without a known layer group'); return; } const drawableID = this._nextDrawableId++; const drawable = new Drawable(drawableID, this); this._allDrawables[drawableID] = drawable; this._addToDrawList(drawableID, group); // tw: implement high quality render drawable.setHighQuality(this.useHighQualityRender); drawable.skin = null; return drawableID; } /** * @param {CanvasMeasurementProvider} measurementProvider helper for measuring text * @returns {TextWrapper} an instance of TextWrapper */ createTextWrapper (measurementProvider) { return new (lazilyLoadTextWrapper())(measurementProvider); } /** * Mark a skin as containing private information. * @param {number} skinID The skin's ID */ markSkinAsPrivate (skinID) { const skin = this._allSkins[skinID]; if (!skin) { return; } skin.private = true; } /** * Mark a drawable as being non-interactive by default. * @param {number} drawableID The drawable's ID */ markDrawableAsNoninteractive (drawableID) { const drawable = this._allDrawables[drawableID]; if (!drawable) { return; } drawable.interactive = false; } /** * Set the layer group ordering for the renderer. * @param {Array<string>} groupOrdering The ordered array of layer group * names */ setLayerGroupOrdering (groupOrdering) { const oldGroups = {}; for (let i = 0; i < this._groupOrdering.length; i++) { const groupID = this._groupOrdering[i]; const layerGroup = this._layerGroups[groupID]; const startIndex = layerGroup.drawListOffset; const endIndex = this._endIndexForKnownLayerGroup(layerGroup); oldGroups[groupID] = this._drawList.slice(startIndex, endIndex); } this._drawList = []; this._groupOrdering = groupOrdering; for (let i = 0; i < this._groupOrdering.length; i++) { const groupID = this._groupOrdering[i]; const oldLayerGroup = oldGroups[groupID]; if (oldLayerGroup) { this._drawList = this._drawList.concat(oldLayerGroup); } this._layerGroups[groupID] = { groupIndex: i, drawListOffset: this._drawList.length }; } } _addToDrawList (drawableID, group) { const currentLayerGroup = this._layerGroups[group]; const currentGroupOrderingIndex = currentLayerGroup.groupIndex; const drawListOffset = this._endIndexForKnownLayerGroup(currentLayerGroup); this._drawList.splice(drawListOffset, 0, drawableID); this._updateOffsets('add', currentGroupOrderingIndex); } _updateOffsets (updateType, currentGroupOrderingIndex) { for ( let i = currentGroupOrderingIndex + 1; i < this._groupOrdering.length; i++ ) { const laterGroupName = this._groupOrdering[i]; if (updateType === 'add') { this._layerGroups[laterGroupName].drawListOffset++; } else if (updateType === 'delete') { this._layerGroups[laterGroupName].drawListOffset--; } } } get _visibleDrawList () { return this._drawList.filter(id => this._allDrawables[id]._visible); } // Given a layer group, return the index where it ends (non-inclusive), // e.g. the returned index does not have a drawable from this layer group in it) _endIndexForKnownLayerGroup (layerGroup) { const groupIndex = layerGroup.groupIndex; if (groupIndex === this._groupOrdering.length - 1) { return this._drawList.length; } return this._layerGroups[this._groupOrdering[groupIndex + 1]] .drawListOffset; } /** * Destroy a Drawable, removing it from the scene. * @param {int} drawableID The ID of the Drawable to remove. * @param {string} group Group name that the drawable belongs to */ destroyDrawable (drawableID, group) { if ( !group || !Object.prototype.hasOwnProperty.call(this._layerGroups, group) ) { log.warn('Cannot destroy drawable without known layer group.'); return; } this.dirty = true; const drawable = this._allDrawables[drawableID]; drawable.dispose(); delete this._allDrawables[drawableID]; const currentLayerGroup = this._layerGroups[group]; const endIndex = this._endIndexForKnownLayerGroup(currentLayerGroup); let index = currentLayerGroup.drawListOffset; while (index < endIndex) { if (this._drawList[index] === drawableID) { break; } index++; } if (index < endIndex) { this._drawList.splice(index, 1); this._updateOffsets('delete', currentLayerGroup.groupIndex); } else { log.warn( 'Could not destroy drawable that could not be found in layer group.' ); return; } } /** * Returns the position of the given drawableID in the draw list. This is * the absolute position irrespective of layer group. * @param {number} drawableID The drawable ID to find. * @return {number} The postion of the given drawable ID. */ getDrawableOrder (drawableID) { return this._drawList.indexOf(drawableID); } /** * Set a drawable's order in the drawable list (effectively, z/layer). * Can be used to move drawables to absolute positions in the list, * or relative to their current positions. * "go back N layers": setDrawableOrder(id, -N, true, 1); (assuming stage at 0). * "go to back": setDrawableOrder(id, 1); (assuming stage at 0). * "go to front": setDrawableOrder(id, Infinity); * @param {int} drawableID ID of Drawable to reorder. * @param {number} order New absolute order or relative order adjusment. * @param {string=} group Name of layer group drawable belongs to. * Reordering will not take place if drawable cannot be found within the bounds * of the layer group. * @param {boolean=} optIsRelative If set, `order` refers to a relative change. * @param {number=} optMin If set, order constrained to be at least `optMin`. * @return {?number} New order if changed, or null. */ setDrawableOrder (drawableID, order, group, optIsRelative, optMin) { if ( !group || !Object.prototype.hasOwnProperty.call(this._layerGroups, group) ) { log.warn( 'Cannot set the order of a drawable without a known layer group.' ); return; } this.dirty = true; const currentLayerGroup = this._layerGroups[group]; const startIndex = currentLayerGroup.drawListOffset; const endIndex = this._endIndexForKnownLayerGroup(currentLayerGroup); let oldIndex = startIndex; while (oldIndex < endIndex) { if (this._drawList[oldIndex] === drawableID) { break; } oldIndex++; } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |