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 — scratch-render/src/RenderWebGL.js at develop · bocoup/scratch-render Expand file tree/ Copy pathRenderWebGL.jsMore file actions 1827 lines (1601 loc) · 70.3 KB / Copy pathRenderWebGL.jsFile metadata and controls1827 lines (1601 loc) · 70.3 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 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 SVGTextBubble = require('./util/svg-text-bubble'); const EffectTransform = require('./EffectTransform'); const log = require('./util/log'); const __isTouchingDrawablesPoint = twgl.v3.create(); const __candidatesBounds = 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; /** * 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; 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 { // Create the context the same way that the constructor will: attributes may make the difference. return !!RenderWebGL._getContext(optCanvas || document.createElement('canvas')); } 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) { return twgl.getWebGLContext(canvas, {alpha: false, stencil: true}); } /** * 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 {HTMLCanvasElement} */ this._tempCanvas = document.createElement('canvas'); /** @type {any} */ this._regionId = null; /** @type {function} */ this._exitRegion = null; /** @type {Array.<snapshotCallback>} */ this._snapshotCallbacks = []; this._svgTextBubble = new SVGTextBubble(); 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.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE); } /** * @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 pixelRatio = window.devicePixelRatio || 1; this._gl.canvas.width = pixelsWide * pixelRatio; this._gl.canvas.height = pixelsTall * pixelRatio; } /** * 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. */ setBackgroundColor (red, green, blue) { this._backgroundColor = [red, green, blue, 1]; } /** * 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.emit(RenderConstants.Events.NativeSizeChanged, {newSize: this._nativeSize}); } /** * 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; return skinId; } /** * Create a new SVG skin using the text bubble svg 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. * @returns {!int} the ID for the new skin. */ createTextSkin (type, text, pointsLeft) { const bubbleSvg = this._svgTextBubble.buildString(type, text, pointsLeft); return this.createSVGSkin(bubbleSvg, [0, 0]); } /** * 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; drawable.setConvexHullDirty(); drawable.setTransformDirty(); } } oldSkin.dispose(); } /** * Update a skin using the text bubble svg 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. */ updateTextSkin (skinId, type, text, pointsLeft) { const bubbleSvg = this._svgTextBubble.buildString(type, text, pointsLeft); this.updateSVGSkin(skinId, bubbleSvg, [0, 0]); } /** * 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 || !this._layerGroups.hasOwnProperty(group)) { log.warn('Cannot create a drawable without a known layer group'); return; } const drawableID = this._nextDrawableId++; const drawable = new Drawable(drawableID); this._allDrawables[drawableID] = drawable; this._addToDrawList(drawableID, group); drawable.skin = null; return drawableID; } /** * Set the layer group ordering for the renderer. * @param {Array<string>} groupOrdering The ordered array of layer group * names */ setLayerGroupOrdering (groupOrdering) { this._groupOrdering = groupOrdering; for (let i = 0; i < this._groupOrdering.length; i++) { this._layerGroups[this._groupOrdering[i]] = { groupIndex: i, drawListOffset: 0 }; } } _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 || !this._layerGroups.hasOwnProperty(group)) { log.warn('Cannot destroy drawable without known layer group.'); return; } 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 || !this._layerGroups.hasOwnProperty(group)) { log.warn('Cannot set the order of a drawable without a known layer group.'); return; } 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++; } if (oldIndex < endIndex) { // Remove drawable from the list. if (order === 0) { return oldIndex; } const _ = this._drawList.splice(oldIndex, 1)[0]; // Determine new index. let newIndex = order; if (optIsRelative) { newIndex += oldIndex; } const possibleMin = (optMin || 0) + startIndex; const min = (possibleMin >= startIndex && possibleMin < endIndex) ? possibleMin : startIndex; newIndex = Math.max(newIndex, min); newIndex = Math.min(newIndex, endIndex); // Insert at new index. this._drawList.splice(newIndex, 0, drawableID); return newIndex; } return null; } /** * Draw all current drawables and present the frame on the canvas. */ draw () { this._doExitDrawRegion(); const gl = this._gl; twgl.bindFramebufferInfo(gl, null); gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); gl.clearColor.apply(gl, this._backgroundColor); gl.clear(gl.COLOR_BUFFER_BIT); this._drawThese(this._drawList, ShaderManager.DRAW_MODE.default, this._projection); if (this._snapshotCallbacks.length > 0) { const snapshot = gl.canvas.toDataURL(); this._snapshotCallbacks.forEach(cb => cb(snapshot)); this._snapshotCallbacks = []; } } /** * Get the precise bounds for a Drawable. * @param {int} drawableID ID of Drawable to get bounds for. * @return {object} Bounds for a tight box around the Drawable. */ getBounds (drawableID) { const drawable = this._allDrawables[drawableID]; // Tell the Drawable about its updated convex hull, if necessary. if (drawable.needsConvexHullPoints()) { const points = this._getConvexHullPointsForDrawable(drawableID); drawable.setConvexHullPoints(points); } const bounds = drawable.getFastBounds(); // In debug mode, draw the bounds. if (this._debugCanvas) { const gl = this._gl; this._debugCanvas.width = gl.canvas.width; this._debugCanvas.height = gl.canvas.height; const context = this._debugCanvas.getContext('2d'); context.drawImage(gl.canvas, 0, 0); context.strokeStyle = '#FF0000'; const pr = window.devicePixelRatio; context.strokeRect( pr * (bounds.left + (this._nativeSize[0] / 2)), pr * (-bounds.top + (this._nativeSize[1] / 2)), pr * (bounds.right - bounds.left), pr * (-bounds.bottom + bounds.top) ); } return bounds; } /** * Get the precise bounds for a Drawable around the top slice. * Used for positioning speech bubbles more closely to the sprite. * @param {int} drawableID ID of Drawable to get bubble bounds for. * @return {object} Bounds for a tight box around the Drawable top slice. */ getBoundsForBubble (drawableID) { const drawable = this._allDrawables[drawableID]; // Tell the Drawable about its updated convex hull, if necessary. if (drawable.needsConvexHullPoints()) { const points = this._getConvexHullPointsForDrawable(drawableID); drawable.setConvexHullPoints(points); } const bounds = drawable.getBoundsForBubble(); // In debug mode, draw the bounds. if (this._debugCanvas) { const gl = this._gl; this._debugCanvas.width = gl.canvas.width; this._debugCanvas.height = gl.canvas.height; const context = this._debugCanvas.getContext('2d'); context.drawImage(gl.canvas, 0, 0); context.strokeStyle = '#FF0000'; const pr = window.devicePixelRatio; context.strokeRect( pr * (bounds.left + (this._nativeSize[0] / 2)), pr * (-bounds.top + (this._nativeSize[1] / 2)), pr * (bounds.right - bounds.left), pr * (-bounds.bottom + bounds.top) ); } return bounds; } /** * Get the current skin (costume) size of a Drawable. * @param {int} drawableID The ID of the Drawable to measure. * @return {Array<number>} Skin size, width and height. */ getCurrentSkinSize (drawableID) { const drawable = this._allDrawables[drawableID]; return this.getSkinSize(drawable.skin.id); } /** * Get the size of a skin by ID. * @param {int} skinID The ID of the Skin to measure. * @return {Array<number>} Skin size, width and height. */ getSkinSize (skinID) { const skin = this._allSkins[skinID]; return skin.size; } /** * Get the rotation center of a skin by ID. * @param {int} skinID The ID of the Skin * @return {Array<number>} The rotationCenterX and rotationCenterY */ getSkinRotationCenter (skinID) { const skin = this._allSkins[skinID]; return skin.calculateRotationCenter(); } /** * Check if a particular Drawable is touching a particular color. * Unlike touching drawable, if the "tester" is invisble, we will still test. * @param {int} drawableID The ID of the Drawable to check. * @param {Array<int>} color3b Test if the Drawable is touching this color. * @param {Array<int>} [mask3b] Optionally mask the check to this part of Drawable. * @returns {boolean} True iff the Drawable is touching the color. */ isTouchingColor (drawableID, color3b, mask3b) { const candidates = this._candidatesTouching(drawableID, this._visibleDrawList); if (candidates.length === 0) { return false; } const bounds = this._candidatesBounds(candidates); const maxPixelsForCPU = this._getMaxPixelsForCPU(); const debugCanvasContext = this._debugCanvas && this._debugCanvas.getContext('2d'); if (debugCanvasContext) { this._debugCanvas.width = bounds.width; this._debugCanvas.height = bounds.height; } // if there are just too many pixels to CPU render efficiently, we need to let readPixels happen if (bounds.width * bounds.height * (candidates.length + 1) >= maxPixelsForCPU) { this._isTouchingColorGpuStart(drawableID, candidates.map(({id}) => id).reverse(), bounds, color3b, mask3b); } const drawable = this._allDrawables[drawableID]; const point = __isTouchingDrawablesPoint; const color = __touchingColor; const hasMask = Boolean(mask3b); // Scratch Space - +y is top for (let y = bounds.bottom; y <= bounds.top; y++) { if (bounds.width * (y - bounds.bottom) * (candidates.length + 1) >= maxPixelsForCPU) { return this._isTouchingColorGpuFin(bounds, color3b, y - bounds.bottom); } for (let x = bounds.left; x <= bounds.right; x++) { point[1] = y; point[0] = x; // if we use a mask, check our sample color... if (hasMask ? maskMatches(Drawable.sampleColor4b(point, drawable, color), mask3b) : drawable.isTouching(point)) { RenderWebGL.sampleColor3b(point, candidates, color); if (debugCanvasContext) { debugCanvasContext.fillStyle = `rgb(${color[0]},${color[1]},${color[2]})`; debugCanvasContext.fillRect(x - bounds.left, bounds.bottom - y, 1, 1); } // ...and the target color is drawn at this pixel if (colorMatches(color, color3b, 0)) { return true; } } } } return false; } _getMaxPixelsForCPU () { switch (this._useGpuMode) { case RenderWebGL.UseGpuModes.ForceCPU: return Infinity; case RenderWebGL.UseGpuModes.ForceGPU: return 0; case RenderWebGL.UseGpuModes.Automatic: default: return __cpuTouchingColorPixelCount; } } _isTouchingColorGpuStart (drawableID, candidateIDs, bounds, color3b, mask3b) { this._doExitDrawRegion(); const gl = this._gl; twgl.bindFramebufferInfo(gl, this._queryBufferInfo); // Limit size of viewport to the bounds around the target Drawable, // and create the projection matrix for the draw. gl.viewport(0, 0, bounds.width, bounds.height); const projection = twgl.m4.ortho(bounds.left, bounds.right, bounds.top, bounds.bottom, -1, 1); let fillBackgroundColor = this._backgroundColor; // When using masking such that the background fill color will showing through, ensure we don't // fill using the same color that we are trying to detect! if (color3b[0] > 196 && color3b[1] > 196 && color3b[2] > 196) { fillBackgroundColor = [0, 0, 0, 255]; } gl.clearColor.apply(gl, fillBackgroundColor); gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); let extraUniforms; if (mask3b) { extraUniforms = { u_colorMask: [mask3b[0] / 255, mask3b[1] / 255, mask3b[2] / 255], u_colorMaskTolerance: MASK_TOUCHING_COLOR_TOLERANCE / 255 }; } try { gl.enable(gl.STENCIL_TEST); gl.stencilFunc(gl.ALWAYS, 1, 1); gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE); gl.colorMask(false, false, false, false); this._drawThese( [drawableID], mask3b ? ShaderManager.DRAW_MODE.colorMask : ShaderManager.DRAW_MODE.silhouette, projection, { extraUniforms, ignoreVisibility: true // Touching color ignores sprite visibility }); gl.stencilFunc(gl.EQUAL, 1, 1); gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); gl.colorMask(true, true, true, true); this._drawThese(candidateIDs, ShaderManager.DRAW_MODE.default, projection, {idFilterFunc: testID => testID !== drawableID} ); } finally { gl.colorMask(true, true, true, true); gl.disable(gl.STENCIL_TEST); } } _isTouchingColorGpuFin (bounds, color3b, stop) { const gl = this._gl; const pixels = new Uint8Array(Math.floor(bounds.width * (bounds.height - stop) * 4)); gl.readPixels(0, 0, bounds.width, (bounds.height - stop), gl.RGBA, gl.UNSIGNED_BYTE, pixels); if (this._debugCanvas) { this._debugCanvas.width = bounds.width; this._debugCanvas.height = bounds.height; const context = this._debugCanvas.getContext('2d'); const imageData = context.getImageData(0, 0, bounds.width, bounds.height - stop); imageData.data.set(pixels); context.putImageData(imageData, 0, 0); } for (let pixelBase = 0; pixelBase < pixels.length; pixelBase += 4) { if (colorMatches(color3b, pixels, pixelBase)) { return true; } } return false; } /** * Check if a particular Drawable is touching any in a set of Drawables. * @param {int} drawableID The ID of the Drawable to check. * @param {?Array<int>} candidateIDs The Drawable IDs to check, otherwise all visible drawables in the renderer * @returns {boolean} True if the Drawable is touching one of candidateIDs. */ isTouchingDrawables (drawableID, candidateIDs = this._drawList) { const candidates = this._candidatesTouching(drawableID, // even if passed an invisible drawable, we will NEVER touch it! candidateIDs.filter(id => this._allDrawables[id]._visible)); // if we are invisble we don't touch anything. if (candidates.length === 0 || !this._allDrawables[drawableID]._visible) { return false; } // Get the union of all the candidates intersections. const bounds = this._candidatesBounds(candidates); const drawable = this._allDrawables[drawableID]; const point = __isTouchingDrawablesPoint; // This is an EXTREMELY brute force collision detector, but it is // still faster than asking the GPU to give us the pixels. for (let x = bounds.left; x <= bounds.right; x++) { // Scratch Space - +y is top point[0] = x; for (let y = bounds.bottom; y <= bounds.top; y++) { point[1] = y; if (drawable.isTouching(point)) { for (let index = 0; index < candidates.length; index++) { if (candidates[index].drawable.isTouching(point)) { return true; } } } } } return false; } /** * Convert a client based x/y position on the canvas to a Scratch 3 world space * Rectangle. This creates recangles with a radius to cover selecting multiple * scratch pixels with touch / small render areas. * * @param {int} centerX The client x coordinate of the picking location. * @param {int} centerY The client y coordinate of the picking location. * @param {int} [width] The client width of the touch event (optional). * @param {int} [height] The client width of the touch event (optional). * @returns {Rectangle} Scratch world space rectangle, iterate bottom <= top, * left <= right. */ clientSpaceToScratchBounds (centerX, centerY, width = 1, height = 1) { const gl = this._gl; const clientToScratchX = this._nativeSize[0] / gl.canvas.clientWidth; const clientToScratchY = this._nativeSize[1] / gl.canvas.clientHeight; width *= clientToScratchX; height *= clientToScratchY; width = Math.max(1, Math.min(Math.round(width), MAX_TOUCH_SIZE[0])); height = Math.max(1, Math.min(Math.round(height), MAX_TOUCH_SIZE[1])); const x = (centerX * clientToScratchX) - ((width - 1) / 2); // + because scratch y is inverted const y = (centerY * clientToScratchY) + ((height - 1) / 2); const xOfs = (width % 2) ? 0 : -0.5; // y is offset +0.5 const yOfs = (height % 2) ? 0 : -0.5; const bounds = new Rectangle(); bounds.initFromBounds(Math.floor(this._xLeft + x + xOfs), Math.floor(this._xLeft + x + xOfs + width - 1), Math.ceil(this._yTop - y + yOfs), Math.ceil(this._yTop - y + yOfs + height - 1)); return bounds; } /** * Determine if the drawable is touching a client based x/y. Helper method for sensing * touching mouse-pointer. Ignores visibility. * * @param {int} drawableID The ID of the drawable to check. * @param {int} centerX The client x coordinate of the picking location. * @param {int} centerY The client y coordinate of the picking location. * @param {int} [touchWidth] The client width of the touch event (optional). * @param {int} [touchHeight] The client height of the touch event (optional). * @returns {boolean} If the drawable has any pixels that would draw in the touch area */ drawableTouching (drawableID, centerX, centerY, touchWidth, touchHeight) { const drawable = this._allDrawables[drawableID]; if (!drawable) { return false; } const bounds = this.clientSpaceToScratchBounds(centerX, centerY, touchWidth, touchHeight); const worldPos = twgl.v3.create(); drawable.updateMatrix(); if (drawable.skin) { drawable.skin.updateSilhouette(); } else { log.warn(`Could not find skin for drawable with id: ${drawableID}`); } for (worldPos[1] = bounds.bottom; worldPos[1] <= bounds.top; worldPos[1]++) { for (worldPos[0] = bounds.left; worldPos[0] <= bounds.right; worldPos[0]++) { if (drawable.isTouching(worldPos)) { return true; } } } return false; } /** * Detect which sprite, if any, is at the given location. * This function will pick all drawables that are visible, unless specific * candidate drawable IDs are provided. Used for determining what is clicked * or dragged. Will not select hidden / ghosted sprites. * * @param {int} centerX The client x coordinate of the picking location. * @param {int} centerY The client y coordinate of the picking location. * @param {int} [touchWidth] The client width of the touch event (optional). * @param {int} [touchHeight] The client height of the touch event (optional). * @param {Array<int>} [candidateIDs] The Drawable IDs to pick from, otherwise all visible drawables. * @returns {int} The ID of the topmost Drawable under the picking location, or * RenderConstants.ID_NONE if there is no Drawable at that location. */ pick (centerX, centerY, touchWidth, touchHeight, candidateIDs) { candidateIDs = (candidateIDs || this._drawList).filter(id => { const drawable = this._allDrawables[id]; |
| 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. |