Picture Shuffle

Stacks of polaroid tiles deal across the canvas to form a picture, then fold back on a click.

What you are seeing

A dark panel with three small piles of white-bordered photo tiles along the bottom edge. Choosing a pile deals about sixty tilted, overlapping tiles across the panel to form a picture of a harbor at dusk, layered hills at sunset or a fruit market. Choosing it again folds the tiles back into the pile.

How it works

A script loads a picture and cuts it into rotated square snapshots on an offscreen canvas.

Each snapshot gets a white border and a shadow, then becomes a data URL on an SVG image element.

Tiles keep small random errors in position and angle, so the collage looks assembled by hand.

One click runs a chain of animations from the stack to each tile position, and the next click reverses it.

History

Posted on September 18, 2010. The original used family photographs, which are not included.

Source

/picture-shuffle/picture-shuffle.xhtml
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <head>
        <title>Picture shuffle: a polaroid collage in SVG</title>
        <meta name="description" content="Three stacks of polaroid tiles deal out across an SVG canvas to form a picture and fold back when clicked."/>
        <link rel="icon" href="../res/2.0/images/favicon.svg" />
        <link rel="icon alternate" href="../res/2.0/images/favicon.png" />
        <script type="text/javascript" src="../res/3.0/scripts/compat/restore.js"></script>
        <script type="text/javascript" src="../res/3.0/scripts/yui/yui/yui-debug.js"></script>
        <script type="text/javascript" src="picture-shuffle.js"></script>
    </head>
    <body>
    <style >
        html {
            background-color: #404040;
            background: linear-gradient(45deg, #f0f0f0, #a0a0a0);
            width: 100%;
            min-height: 100%;
        }

        svg, canvas {
            max-width: 100%;
            height: auto;
            background: #303030;
            border-radius: 5px;
            margin-left: auto;
            margin-right: auto;
            display: block;
            margin-top: 1em;
            margin-bottom: auto;
            box-shadow:0 0 10px 0px rgba(0,0,0,0.25);
            border: 1px solid #404040;
        }

        #polaroidStacks > g:focus { outline: none; }
        #polaroidStacks > g:focus-visible { outline: 2px solid #ffd27f; }

        #help p { margin: 0.4em 0; }

        #help {
            color: rgb(255, 255, 255);
            width: 640px;
            max-width: 100%;
            font-size: 15px;
            margin-left: auto;
            margin-right: auto;
            margin-top: auto;
            border: 1px solid rgba(255,255,255,0);
            text-align: center;
            font-weight: bold;
            text-shadow: white 0px 0px 5px;
            font-family: 'Trebuchet MS', Verdana, sans-serif;
        }
    </style>
    <div>

        <canvas id="canvas" width="300" height="300" style="display:none;"></canvas>
        <svg id="svgCanvas" version="1.1" xmlns="http://www.w3.org/2000/svg"
             xmlns:svg="http://www.w3.org/2000/svg"
             xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
             width="800px" height="600px" viewBox="0 0 800 600" xml:space="preserve">
            <desc>Three small stacks of photo tiles sit at the bottom. Choosing one deals its tiles across the canvas, slightly rotated and overlapped, to form a harbor, hills or market picture drawn for this restoration.</desc>

            <svg:foreignObject width="100%" height="100%" xmlns="http://www.w3.org/1999/xhtml">
                <div id="help">
                    <p>Click a stack to deal it out, click again to fold it. Keys 1, 2, 3 also work.</p>
                </div>
            </svg:foreignObject>
            <g id="polaroidStacks">
            </g>


        </svg>


    </div>
</body>
</html>
/picture-shuffle/picture-shuffle.js
/** =======================================================================
 *  Vincent Hardy
 *  License terms: see svg-wow.org
 *  CC0 http://creativecommons.org/publicdomain/zero/1.0/
 *  ======================================================================= */
(function () {
    /**
     * YUI global object instance.
     * See the load call at the end of this file.
     */
    var Y;
    
    /**
     * Utility to get the viewbox information.
     */
    function getViewBox () {
        var svg = Y.one('svg'), vb = svg.get('viewBox');
        return {
            x: vb.baseVal.x,
            y: vb.baseVal.y,
            width: vb.baseVal.width,
            height: vb.baseVal.height
        };
    }

    /**
     * The size of each polaroid picture frame.
     */
    var polaroidSize = {width: 80, height: 80};

    /**
     * The polaroidSpacing gives the amount of space along each axis between
     * the polaroid's anchor point.
     */
    var polaroidSpacing = {width: 60, height: 60};

    /**
     * The amount of overlap between polaroid pictures in the [0, 1] range.
     * The allows the polaroids to move about their anchor point in a random
     * way, bounded by the min and max overlap values.
     */
    var overlap = {min: 0, max: 0.2};

    /**
     * The amount of rotation for the polaroid pictures about their anchor point.
     */
    var rotation = {min: 5, max: 90};

    /**
     * The amount of randomness given to the alignment between polaroids.
     * 0 is no randomness at all. 1 is the maximum randomness allowed.
     */
    var alignmentRoughness = 0.01; // +/-1% of random alignment

    /**
     * The margin around the image
     */
    var margin = 100;

    /**
     * The polaroid border width
     */
    var borderWidth = 4;

    function onScriptsReady (YUI) {
        Y = YUI;
        createPolaroidStack('scene-market.png',
                            {x: 200, y: 600},
                            positionAndAnimateStack);
        createPolaroidStack('scene-harbor.png',
                            {x: 400, y: 600},
                            positionAndAnimateStack);
        createPolaroidStack('scene-hills.png',
                            {x: 600, y: 600},
                            positionAndAnimateStack);
    }

    /**
     * Creates a stack of images in their final position.
     *
     * @param imageURL the image to display.
     * @param position the desired stack position in viewBox space.
     * @param callback the function to invoke when the stack has been created.
     * @return an SVG group with the polaroid elements.
     */
    function createPolaroidStack (imageURL, position, callback) {
        var img = new Image();

        img.onload = function () {
            callback(onPolaroidStackSourceReady(img), position);
        };

        img.onerror = function () {
            Y.one('#help').set('textContent', 'Could not load ' + imageURL);
        };

        // Setting the url triggers the image load.
        img.src = imageURL;
    }

    /**
     * Positions and animates the polaroid stack.
     *
     * @param stack the stack of polaroids
     * @param position the desired stack position, in viewBox space.
     */
    function positionAndAnimateStack (stack, position) {
        var c = stack.get('lastChild'),
            anims = [], anim = null, prevAnim = null,
            stackPosition, stackTxf, stackTop = c;

        // The stack position is in the stack space. Get the stack's
        // transform and combine its translation component with the desired
        // position.
        stackTxf = stack.getMatrix();
        stackPosition = {
            x: position.x - stackTxf.e(),
            y: position.y - stackTxf.f()
        };

        function getReverseHandler (a) {
            return function () {
                a.set('reverse', !a.get('reverse'));
                if (a.get('reverse') === true) {
                    a.set('duration', 0.15 + 0.15 * Math.random());
                } else {
                    a.set('duration', 0.25 + 0.25 * Math.random());
                }
            };
        }

        while (c !== null) {
            prevAnim = anim;
            anim = new sw.animation.Animate({
                node: c,
                from: {
                    transform: {
                        r: c.r + 90,
                        tx: stackPosition.x + 10 - 20 * Math.random(),
                        ty: stackPosition.y + 10 - 10 * Math.random()
                    }
                },
                to: {
                    transform: {r: c.r, tx: c.cx, ty: c.cy}
                },
                transformTemplate: "translate(#tx, #ty) rotate(#r) " +
                                   "translate(" + (-c.cx) + "," + (-c.cy) +
                                   ")",
                duration: 0.25 + 0.25 * Math.random(),
                easing: Y.Easing.easeOutStrong
            });
            anims.push(anim);
            anim.applyStartFrame();
            if (prevAnim !== null) {
                prevAnim.onBegin(anim, 0.05 * Math.random());
            }

            anim.onEnd(getReverseHandler(anim));
            c = c.get('previousSibling');
        }

        Y.one('#polaroidStacks').appendChild(stack);
        anims[0].beginOn(stack, 'click');

        // Keyboard access: each stack is focusable, and 1, 2, 3 trigger them.
        var stackNode = stack._node, stackNumber = position.x / 200;
        function trigger () {
            stackNode.dispatchEvent(new MouseEvent('click', {bubbles: true}));
        }
        stackNode.setAttribute('tabindex', '0');
        stackNode.setAttribute('role', 'button');
        stackNode.setAttribute('aria-label', 'Picture stack ' + stackNumber);
        stackNode.addEventListener('keydown', function (evt) {
            if (evt.key === 'Enter' || evt.key === ' ') {
                evt.preventDefault();
                trigger();
            }
        });
        document.addEventListener('keydown', function (evt) {
            if (evt.key === String(stackNumber)) {
                trigger();
            }
        });

        stackTop.trace = true;
    }

    /**
     * Called when an image has been successfully loaded.
     *
     * @param img the image to use as the source for the stack.
     */
    function onPolaroidStackSourceReady(img) {
        var viewBox = getViewBox(),
            imageWidth, imageHeight,
            nCols, nRows,
            polaroidStack = Y.one(document.createElementNS(Y.svgNS, 'g')),
            sx, sy, s,
            cx, cy, r,
            ox, oy,
            dr = rotation.max - rotation.min,
            ds = overlap.max - overlap.min,
            polaroid,
            allPictures = [],
            prev = null,
            canvas, ctx,
            shadowBlur = 6,
            shadowOffsetX = 0,
            shadowOffsetY = 0,
            shadowColor = 'rgba(0,0,0,0.85)',
            shadowPadding = {
                width: 5,
                height: 5
            },
            snapshotSize = {
                width: polaroidSize.width + 2 * shadowPadding.width,
                height: polaroidSize.height + 2 * shadowPadding.height
            },
            polaroidTemplate = Y.one(Y.DOM.loadContent(null, {
                tag: 'image',
                'class': 'polaroid',
                width: snapshotSize.width,
                height: snapshotSize.height
            }));

        // =====================================================================
        // We want to display the image in the viewBox with some margin.
        // To achieve that, we compute the necessary scale factor for the
        // image.
        // =====================================================================

        // The padding allows rotated polaroids to still show the image content.
        // Without padding, a rotated polaroid on the edges would show part of
        // the image on the opposite side. For example, a polaroid on the
        // top would show content from the bottom.
        var picturePadding = {
            width: polaroidSize.width * (1 - 1 / Math.sqrt(2)) +
                   polaroidSize.width * overlap.max,
            height: polaroidSize.height * (1 - 1 / Math.sqrt(2)) +
                   polaroidSize.height * overlap.max
        };

        sx = (viewBox.width - margin * 2) / img.width;
        sy = (viewBox.height - margin * 2) / img.height;

        s = sx;
        if (sx > sy) {
            s = sy;
        }

        imageWidth = Math.round(img.width * s);
        imageHeight = Math.round(img.height * s);

        // Make padding conform to the image's aspect ratio
        var ar = img.width / img.height;
        picturePadding.width *= ar;

        var pictureWidth = imageWidth + 2 * picturePadding.width;
        var pictureHeight = imageHeight + 2 * picturePadding.height;


        // =====================================================================
        // Create a canvas where we'll draw the tiles as we need them.
        // =====================================================================
        canvas = document.createElement('canvas');
        canvas.width = snapshotSize.width;
        canvas.height = snapshotSize.height;
        ctx = canvas.getContext('2d');
        ctx.save();

        // imgCanvas is used to hold the scaled image of the source image.
        // We scale the image a bit compared to the target size to account for
        // the polaroids rotation and make sure they do not bleed over the
        // picture's edges.
        var imgCanvas = document.createElement('canvas');
        imgCanvas.width = pictureWidth;
        imgCanvas.height = pictureHeight;
        imgCanvas.getContext('2d').drawImage(img, 0, 0,
                     img.width, img.height, 0, 0, pictureWidth, pictureHeight);


        // snapshotCanvas is used to take a rotated snapshot to include in a
        // polaroid rendering.
        var snapshotCanvas = document.createElement('canvas');
        snapshotCanvas.width = polaroidSize.width;
        snapshotCanvas.height = polaroidSize.height;
        var snapshotCtx = snapshotCanvas.getContext('2d');

        /**
         * Private method.
         * Takes a picture of the polaroid centered on cx/cy which will be
         * rotated by r degrees.
         *
         * The resulting image is stored in snapshotCanvas.
         */
        function snapshot (cx, cy, r) {
            var p = alignmentRoughness;
            var ar = (1 - p + 2 * p * Math.random()) * r,
                acx = (1 - p + 2 * p * Math.random()) * cx,
                acy = (1 - p + 2 * p * Math.random()) * cy;

            snapshotCtx.save();
            snapshotCtx.clearRect(0, 0, polaroidSize.width, polaroidSize.height);
            snapshotCtx.translate(polaroidSize.width / 2, polaroidSize.height /2);
            snapshotCtx.rotate(-ar * Math.PI / 180);
            snapshotCtx.translate(-acx, -acy);
            snapshotCtx.drawImage(imgCanvas, 0, 0);
            snapshotCtx.restore();
        }
        
        /**
         * Private method.
         * Takes a picture of the polaroid centered on cx/cy and add decoration
         * to it (drop shadow and border).
         *
         * @return a string dataURL with the polaroid's image.
         */
        function polaroidSnapshot (cx, cy, r) {
            // Create the snapshot we need
            snapshot(cx, cy, r);

            ctx.clearRect(0, 0, snapshotSize.width, snapshotSize.height);
            ctx.shadowBlur = shadowBlur;
            ctx.shadowOffsetX = shadowOffsetX;
            ctx.shadowOffsetY = shadowOffsetY;
            ctx.shadowColor = shadowColor;
            ctx.drawImage(snapshotCanvas, shadowPadding.width, shadowPadding.height);
            ctx.restore();
            ctx.strokeStyle = '#fff';
            ctx.lineWidth = borderWidth;
            ctx.strokeRect(shadowPadding.width + borderWidth / 2,
                           shadowPadding.height + borderWidth / 2,
                           polaroidSize.width - borderWidth,
                           polaroidSize.height - borderWidth);
            ctx.save();
            
            return canvas.toDataURL();
        }

        // =====================================================================
        // Create the polaroids.
        // =====================================================================
        nCols = Math.floor(imageWidth / polaroidSpacing.width);
        nRows = Math.floor(imageHeight / polaroidSpacing.height);

        var dx = 0;
        if (nCols > 0) {
            dx = (imageWidth - nCols * polaroidSpacing.width) / 2;
        }

        var dy = 0;
        if (nRows > 0) {
            dy = (imageHeight - nRows * polaroidSpacing.height) / 2;
        }

        polaroidStack.set('transform', 'translate(' +
            (viewBox.width - imageWidth) / 2 + ',' +
            (viewBox.height - imageHeight) / 2 + ')');

        for (var ri = 0; ri < nRows; ri++) {
            for (var ci = 0; ci < nCols; ci++) {
                ox = overlap.min + ds * Math.random();
                if (Math.random() > 0.5) {
                    ox *= -1;
                }

                oy = overlap.min + ds * Math.random();
                if (Math.random() > 0.5) {
                    oy *= -1;
                }

                // cx/cy is the center of the polaroid tile in the the polaroid
                // stack group space. The so-called picturePadding is offset
                // compared to the polaroid stack coordinate space by the
                // pattern padding.
                //
                // This is why we offset the polaroidSnapshot call below by
                // the picturePadding amount along both axis.
                cx = polaroidSpacing.width * (ci + 0.5 + ox) + dx;
                cy = polaroidSpacing.height * (ri + 0.5 + oy) + dy;
                r = rotation.min + Math.random() * dr;
                if (Math.random() > 0.5) {
                    r = -r;
                }

                polaroid = polaroidTemplate.cloneNode();

                polaroid.setAttrs({
                    id: "polaroid_" + ri + "_" + ci,
                    x: cx - snapshotSize.width / 2,
                    y: cy - snapshotSize.height / 2
                });

                polaroid._node.setAttributeNS(Y.xlinkNS, 'href',
                            polaroidSnapshot(cx + picturePadding.width,
                                             cy + picturePadding.height, r));

                polaroid.set('transform',
                                  'rotate(' + r + ',' + cx + ',' + cy + ')');
                polaroid.r = r;
                polaroid.cx = cx;
                polaroid.cy = cy;

                if (allPictures.length > 0) {
                    prev = allPictures[
                        Math.round((allPictures.length - 1) * Math.random())];
                }

                polaroidStack.insertBefore(polaroid, prev);
                allPictures.push(polaroid);
            }
        }

        return polaroidStack;
    }

    /**
     * Main entry point. Refer to the YUI documentation to understand how the
     * YUI framework loads scripts and handles dependencies.
     *
     * The following declares the modules required by the code (such as
     * 'anim-svg') and their dependencies.
     *
     * The onScriptsReady function is called when the DOM tree is ready.
     */
    YUI({
        groups: {
            svg: {
                combine: false,
                base: "../res/3.0/scripts/yui/",
                modules:  {
                    "node-svg": {
                        path: 'svg/node-svg-debug.js',
                        requires: ['node']
                    },
                    "dom-style-svg": {
                        path: 'svg/dom-style-svg-debug.js',
                        requires: ['node', 'dom-svg']
                    },
                    "dom-svg": {
                        path: 'svg/dom-svg-debug.js',
                        requires: ['dom']
                    },
                    "anim-timing": {
                        path: 'anim-timing/anim-timing-debug.js',
                        requires: ['anim', 'node-svg']
                    },
                    "anim-svg": {
                        path: 'svg/anim-svg-debug.js',
                        requires: ['anim', 'dom-style-svg']
                    },
                    "text-effects": {
                        path: '../tools/text-effects.js',
                        requires: ['anim-svg', 'anim-timing']
                    }
                }
            }
        }
    }).use('anim-svg', 'anim-timing', function(YUI) {
        YUI.on('contentready', function () {
            onScriptsReady(YUI);
        }, 'body');
    });
    
})();
/res/3.0/scripts/compat/restore.js
/**
 * Compatibility layer for the restored YUI 3 demos.
 *
 * Load this before yui-debug.js. It keeps the YUI loader on this origin,
 * restores two SVG DOM members that browsers have removed, and provides the
 * start control and the synthesized sound used in place of the original
 * music tracks. Sound is created only after a click on a start button.
 */
(function () {
    'use strict';

    // Never let the loader build a combo URL for the retired YUI CDN.
    window.YUI_config = window.YUI_config || {};
    window.YUI_config.combine = false;
    // Only the -debug builds of the modules were archived.
    window.YUI_config.filter = 'debug';
    window.YUI_config.debug = false;
    window.YUI_config.useBrowserConsole = false;

    // =========================================================================
    // Removed SVG DOM members
    // =========================================================================
    var graphics = (window.SVGGraphicsElement || window.SVGElement).prototype;

    if (!graphics.getTransformToElement) {
        graphics.getTransformToElement = function (target) {
            return target.getScreenCTM().inverse().multiply(this.getScreenCTM());
        };
    }

    if (!('nearestViewportElement' in graphics)) {
        Object.defineProperty(graphics, 'nearestViewportElement', {
            configurable: true,
            get: function () { return this.ownerSVGElement; }
        });
    }

    // dom-utils.js only installs this when it is missing. Its own version
    // passes an output argument to transformPoint, which DOMMatrix ignores.
    graphics.getViewportBBox = function () {
        var box = this.getBBox(),
            m = this.getTransformToElement(this.nearestViewportElement),
            xs = [], ys = [];
        [[box.x, box.y], [box.x + box.width, box.y],
         [box.x, box.y + box.height], [box.x + box.width, box.y + box.height]
        ].forEach(function (p) {
            xs.push(m.a * p[0] + m.c * p[1] + m.e);
            ys.push(m.b * p[0] + m.d * p[1] + m.f);
        });
        var minX = Math.min.apply(null, xs), minY = Math.min.apply(null, ys);
        return {
            x: minX,
            y: minY,
            width: Math.max.apply(null, xs) - minX,
            height: Math.max.apply(null, ys) - minY
        };
    };

    // =========================================================================
    // Start control, sound toggle and replay button
    // =========================================================================
    var css = [
        '.sw-controls{position:absolute;z-index:20;display:flex;flex-wrap:wrap;gap:8px;',
        'justify-content:center;transform:translate(-50%,-50%);width:max-content;max-width:92vw}',
        '.sw-controls button,.sw-sound{font:600 15px/1.2 system-ui,-apple-system,"Segoe UI",sans-serif;',
        'min-height:44px;padding:10px 18px;border-radius:6px;border:1px solid #202020;',
        'background:#202020;color:#fff;cursor:pointer}',
        '.sw-controls button.sw-alt{background:#fff;color:#202020}',
        '.sw-controls button:hover,.sw-sound:hover{background:#b0122f;border-color:#b0122f;color:#fff}',
        '.sw-controls button:focus-visible,.sw-sound:focus-visible{outline:3px solid #ffb000;outline-offset:2px}',
        '.sw-sound{position:fixed;top:8px;right:8px;z-index:21;font-size:13px;min-height:36px;padding:6px 12px}'
    ].join('');

    function addStyle() {
        if (document.getElementById('sw-restore-style')) { return; }
        var style = document.createElement('style');
        style.id = 'sw-restore-style';
        style.textContent = css;
        (document.head || document.documentElement).appendChild(style);
    }

    function button(label, className, handler) {
        var b = document.createElement('button');
        b.setAttribute('type', 'button');
        if (className) { b.className = className; }
        b.textContent = label;
        b.addEventListener('click', function (event) {
            event.stopPropagation();
            handler(event);
        });
        return b;
    }

    function placeOver(box, target, at) {
        function place() {
            var r = target.getBoundingClientRect();
            box.style.left = (r.left + window.pageXOffset + r.width / 2) + 'px';
            box.style.top = (r.top + window.pageYOffset + r.height * at) + 'px';
        }
        place();
        window.addEventListener('resize', place);
        return function () { window.removeEventListener('resize', place); };
    }

    /**
     * Shows "Start" and "Start with sound" over the target element.
     *
     * @param opts.target the element to centre the buttons on
     * @param opts.onStart called once with true when sound was requested
     * @param opts.score optional note pattern for the synthesized sound
     * @param opts.at vertical position over the target, 0 to 1
     */
    function startControl(opts) {
        addStyle();
        var box = document.createElement('div'), release, primary;
        box.className = 'sw-controls';

        function go(withSound) {
            release();
            box.parentNode.removeChild(box);
            if (withSound) {
                var s = createScore(opts.score);
                s.play();
                soundToggle(s);
            }
            opts.onStart(withSound);
        }

        primary = button('Start', '', function () { go(false); });
        box.appendChild(primary);
        box.appendChild(button('Start with sound', 'sw-alt', function () { go(true); }));
        document.body.appendChild(box);
        release = placeOver(box, opts.target, opts.at === undefined ? 0.5 : opts.at);
        try { primary.focus({preventScroll: true}); } catch (e) { primary.focus(); }
    }

    function soundToggle(score) {
        var b = button('Sound off', 'sw-sound', function () {
            if (score.playing()) {
                score.stop();
                b.textContent = 'Sound on';
            } else {
                score.play();
                b.textContent = 'Sound off';
            }
        });
        document.body.appendChild(b);
    }

    /** Shows a "Play again" button, which reloads the document. */
    function replay(target, at) {
        addStyle();
        var box = document.createElement('div');
        box.className = 'sw-controls';
        box.appendChild(button('Play again', '', function () { window.location.reload(); }));
        document.body.appendChild(box);
        placeOver(box, target, at === undefined ? 0.92 : at);
    }

    // =========================================================================
    // Synthesized sound: a soft plucked pattern scheduled with Web Audio.
    // =========================================================================
    var DEFAULT_SCORE = {
        tempo: 92,
        notes: [220, 0, 261.63, 293.66, 0, 329.63, 293.66, 0,
                196, 0, 246.94, 293.66, 0, 329.63, 392, 0],
        bass: [110, 110, 98, 98]
    };

    function createScore(pattern) {
        var score = pattern || DEFAULT_SCORE,
            stepLength = 60 / score.tempo / 2,
            ctx = null, master = null, timer = null, step = 0, nextTime = 0;

        function pluck(freq, when, length, level, type) {
            var osc = ctx.createOscillator(), gain = ctx.createGain();
            osc.type = type;
            osc.frequency.value = freq;
            gain.gain.setValueAtTime(0.0001, when);
            gain.gain.exponentialRampToValueAtTime(level, when + 0.015);
            gain.gain.exponentialRampToValueAtTime(0.0001, when + length);
            osc.connect(gain);
            gain.connect(master);
            osc.start(when);
            osc.stop(when + length + 0.02);
        }

        function schedule() {
            while (nextTime < ctx.currentTime + 0.25) {
                var n = score.notes[step % score.notes.length];
                if (n) { pluck(n, nextTime, 0.7, 0.16, 'triangle'); }
                if (step % 4 === 0) {
                    pluck(score.bass[(step / 4) % score.bass.length], nextTime,
                          stepLength * 3.5, 0.2, 'sine');
                }
                step++;
                nextTime += stepLength;
            }
        }

        return {
            play: function () {
                var Ctx = window.AudioContext || window.webkitAudioContext;
                if (!Ctx || timer !== null) { return; }
                if (!ctx) {
                    ctx = new Ctx();
                    master = ctx.createGain();
                    master.gain.value = 0.5;
                    master.connect(ctx.destination);
                }
                ctx.resume();
                nextTime = ctx.currentTime + 0.05;
                schedule();
                timer = setInterval(schedule, 80);
            },
            stop: function () {
                if (timer !== null) { clearInterval(timer); timer = null; }
                if (ctx) { ctx.suspend(); }
            },
            playing: function () { return timer !== null; }
        };
    }

    window.SwRestore = {
        startControl: startControl,
        replay: replay,
        createScore: createScore,
        reducedMotion: function () {
            return !!(window.matchMedia &&
                      window.matchMedia('(prefers-reduced-motion: reduce)').matches);
        }
    };
})();
/res/3.0/scripts/yui/anim-timing/anim-timing-debug.js
/** =======================================================================
 *  Vincent Hardy
 *  License terms: see svg-wow.org
 *  CC0 http://creativecommons.org/publicdomain/zero/1.0/
 *  ======================================================================= */

(function () {

window.sw = window.sw || {};
sw.animation = sw.animation || {};

YUI.add("anim-timing", function (Y) {

// =============================================================================
// Utility class used to manage animation time offsets.
// =============================================================================

var OffsetManager = {
    /**
     * List of pending offsets
     */
    _pendingOffsets: [],

    /**
     * The most recent timer identifier (used for cancellation
     */
    _lastTimerId: -1,

    /**
     * Adds a new offset client.
     *
     * @param p_offset {Number} the offset after which callback should be called.
     * @param p_callback the callback to invoke after offset expires. Should
     *        be a function or an animation instance (i.e., an object with a
     *        'run' method).
     */
    addOffsetListener : function (p_offset, p_callback) {
        p_offset = p_offset !== undefined ? p_offset : 0;

        if (p_offset === undefined || p_offset <= 0) {
            // Invoke callback immediately.
            this._invokeCallback(p_callback);
        } else {
            var currentTime = (new Date()).getTime(),
                offset = {
                    callback: p_callback,
                    offset: p_offset,
                    requestedAt: currentTime,
                    remainingOffset: p_offset * 1000
                };

            this._updatePendingOffsets(currentTime);

            if (this._insertPendingOffset(offset) === 0) {
                // the new offset is at index 0, i.e., it is our most immediate
                // new timer. Cancel the current timer if one was set.
                // In all cases, start a new timeout.
                if (this._lastTimerId !== -1) {
                    clearTimeout(this._lastTimerId);
                }

                this._startTimer();
            }
        }
    },

    /**
     * Implementation helper.
     * Starts the timer on the most immediate callback. This assumes the
     * callbacks have been sorted in time order and that there is at least
     * one.
     */
    _startTimer : function () {
        this._lastTimerId = setTimeout(function () {
                        OffsetManager._onTimeout();
                    }, this._pendingOffsets[0].remainingOffset);
    },

    /**
     * setTimeout callback
     *
     */
    _onTimeout : function () {
        this._timerId = -1;

        var po = this._pendingOffsets, o,
            currentTime = (new Date()).getTime();
        this._updatePendingOffsets(currentTime);

        o = po[0];
        while (o !== undefined && o.remainingOffset <= 0) {
            po.splice(0, 1);
            this._invokeCallback(o.callback);
            o = po[0];
        }

        if (po.length > 0) {
            this._startTimer();
        }
    },

    /**
     * Implementation helper.
     *
     * Updates the remainingOffset on the _pendingOffsets elements.
     *
     * @param p_currentTime the current time when this call is made
     */
    _updatePendingOffsets : function (p_currentTime) {
        var po = this._pendingOffsets, o;
        var n = po.length;
        for (var i = 0; i < n; i++) {
            o = po[i];
            o.remainingOffset = o.offset * 1000 - (p_currentTime - o.requestedAt);
        }
    },

    /**
     * Implementation helper.
     *
     * Inserts a new timing offset in the array managed by the offset manager.
     *
     * @param p_offset the new offset object to insert.
     * @return the index at which the new offset object was inserted.
     */
    _insertPendingOffset : function (p_offset) {
        var po = this._pendingOffsets, o;
        var n = po.length;
        for (var i = 0; i < n; i++) {
            o = po[i];
            if (o.remainingOffset > p_offset.remainingOffset) {
                po.splice(i, 0, p_offset);
                break;
            }
         }

         if (i === n) {
             po.push(p_offset);
         }

         return i;
    },

    /**
     * Invokes the callback.
     *
     * @param p_callback may be a function or an animation instance.
     */
    _invokeCallback : function (p_callback) {
        if (typeof p_callback === "function") {
            p_callback.call();
        } else if (typeof p_callback === "object" &&
                   p_callback !== null &&
                   typeof p_callback.run === "function") {
            p_callback.run();
        }
    }

};

/**
 * Simple extension of the YUI animation classes to handle SVG transforms.
 *
 * The extension handles the "r", "sx", "sy", "tx" and "ty" pseudo attributes
 * by manipulating the transform of the target element using a template.
 *
 * @param config the configuration
 *
 * @see http://developer.yahoo.com/yui/docs/YAHOO.util.Anim.html
 */
sw.animation.Animate = function (config) {
    sw.animation.Animate.superclass.constructor.apply(this, arguments);
};

sw.animation.Animate.NAME = "sw.animation.Animate";

sw.animation.Animate.ATTRS = {
    transformTemplate: {
        value: "rotate(#r) scale(#sx, #sy) translate(#tx, #ty)"
    }
};

/**
 * Work around usage of regexp in YUI to detect which properties should have a
 * default unit.
 *
 * Unfortunately, the default regexp matches stop-opacity with 'top'
 */
Y.Anim.RE_DEFAULT_UNIT = /^width|^height|^top|^right|^bottom|^left|^margin.*|^padding.*|^border.*$/i;

Y.extend(sw.animation.Animate, Y.Anim, {
    /**
     * Initializer.
     * @see Y.Base
     */
    initializer : function () {
        var _endCallbacks = [],
            _beginCallbacks = [];

        this._endCallbacks = _endCallbacks;
        this._beginCallbacks = _beginCallbacks;

        this.on("end", function () {
            for (var i = 0; i < _endCallbacks.length; i++) {
                OffsetManager.addOffsetListener(_endCallbacks[i].offset,
                                                _endCallbacks[i].callback);
            }
        });

        this.on("start", function () {
            for (var i = 0; i < _beginCallbacks.length; i++) {
                OffsetManager.addOffsetListener(_beginCallbacks[i].offset,
                                                _beginCallbacks[i].callback);
            }
        });

        // Override the run/stop methods. Since it is initialized in the animate
        // class' constructor, we need to do an override in the derived class'
        // constructor as well.
        this._superRun = sw.animation.Animate.superclass.run;
        this._superStop = sw.animation.Animate.superclass.stop;        
    },

    /**
     * Override the base class' _runAttrs to fix a bug in reverse mode.
     */
    _runAttrs: function(t, d, reverse) {
        var attr = this._runtimeAttr,
            customAttr = Y.Anim.behaviors,
            easing = attr.easing,
            lastFrame = d,
            attribute,
            setter,
            i;

        if (reverse) {
            t = d - t;
            lastFrame = 0;
        }

        for (i in attr) {
            if (attr[i].to) {
                attribute = attr[i];
                setter = (i in customAttr && 'set' in customAttr[i]) ?
                        customAttr[i].set : Y.Anim.DEFAULT_SETTER;

                if (t < d && t > 0) {
                    setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit);
                } else {
                    setter(this, i, attribute.from, attribute.to, lastFrame, d, easing, attribute.unit);
                }
            }
        }
    },

    /**
     * Applies the initial animation value.
     */
    applyStartFrame: function() {
        this._checkRuntimeAttr();

        var d = this._runtimeAttr.duration,
            t = 0,
            attr = this._runtimeAttr,
            customAttr = Y.Anim.behaviors,
            easing = attr.easing,
            attribute,
            setter,
            i,
            reverse = this.get("reverse");

        if (reverse) {
            t = d;
        }

        for (i in attr) {
            if (attr[i].to) {
                attribute = attr[i];
                setter = (i in customAttr && 'set' in customAttr[i]) ?
                         customAttr[i].set : Y.Anim.DEFAULT_SETTER;

                setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit);                 
            }
        }
    },

    /**
     * Implementation helper: checks that the runtime attributes have been
     * initialized. If not, initialize them now.
     */
    _checkRuntimeAttr : function () {
        if (this._runtimeAttr === undefined) {
            this._initAnimAttr();
        }
    },

    /**
     * Returns a handler that will run this animation instance when invoked.
     */
    getRunHandler : function () {
        var that = this;
        if (this._runHandler === undefined) {
            this._runHandler = function () {
                that.run();
            };
        }

        return this._runHandler;
    },
    
    /**
     * Returns the handler that will stop this animation instance when invoked
     */
    getStopHandler : function () {
        var that = this;
        if (this._stopHandler === undefined) {
            this._stopHandler = function () {
                that.stop();
            };
        }
        return this._stopHandler;
    },

    /**
     * Adds a function of animation to call or play when this animation ends
     *
     * @param p_animOrCallback an animation or function to trigger when this
     *        animation ends
     * @param p_oOffset {Number} optional time offset to add before calling the
     *        end callback.
     */
    onEnd : function (p_animOrCallback, p_oOffset) {
        this._endCallbacks.push({
            callback: p_animOrCallback,
            offset: p_oOffset
        });
    },

    /**
     * Adds a function of animation to call or play when this animation begins
     *
     * @param p_animOrCallback an animation or function to trigger when this
     *        animation begins
     * @param p_oOffset {Number} optional time offset to add before calling the
     *        begin callback.
     */
    onBegin : function (p_animOrCallback, p_oOffset) {
        this._beginCallbacks.push({
            callback: p_animOrCallback,
            offset: p_oOffset
        });
    },

    /**
     * Starts the animation with the requseted offset. The offset is optional,
     * and defaults to zero if unspecified.
     *
     * @param p_oOffset {Number} optional time offset, in seconds, before
     *        starting the animation.
     */
    run : function (p_offset) {
        if (p_offset === undefined || p_offset === 0) {
            this._superRun.call(this);
            this.applyStartFrame(); // Applies the initial animation frame.
        } else {
            OffsetManager.addOffsetListener(p_offset, this);
        }
    },
    
    /**
     * Stops the animation with the requested offset. The offset is optional and
     * defaults to zero if unspecified.
     *
     * @param p_oOffset {Number} optional time offset, in seconds, before ending
     *        the animation.
     */
    stop : function (p_offset) {
        if (p_offset === undefined || p_offset === 0) {
            this._superStop.call(this);
        } else {
            OffsetManager.addOffsetListener(p_offset, this.getStopHandler());
        }
    },
     

    /**
     * Adds a start condition for this animation.
     *
     * @param p_evtTarget the event target (DOM object) or animation.
     * @param p_evtType the event type. If the target is an animation instance,
     *        should be "begin" or "end".
     * @param p_oOffset an offset after which the animation should begin. In
     *        seconds.
     */
    beginOn : function (p_evtTarget, p_evtType, p_oOffset) {
        var that = this;

        if (p_evtTarget.run !== undefined) {
            if (p_evtType === "begin") {
                p_evtTarget.onBegin(this, p_oOffset);
            } else if (p_evtType === "end") {
                p_evtTarget.onEnd(this, p_oOffset);
            }
        } else {
            p_evtTarget.on(p_evtType, function () {
                that.run(p_oOffset);
            });
        }
    },

    /**
     * Adds an end condition for this animation.
     *
     * @param p_evtTarget the event target
     * @param p_evtType the event type. If the target is an animation instance,
     *        should be "begin" or "end".
     * @param p_oOffset an offset after which the animation should begin In
     *        seconds.
     */
    endOn : function (p_evtTarget, p_evtType, p_oOffset) {
        var that = this;
        if (p_evtTarget.run !== undefined) {
            if (p_evtType === "begin") {
                p_evtTarget.onBegin(function () {
                    that.stop(false);
                }, p_oOffset);
            } else if (p_evtType === "end") {
                p_evtTarget.onEnd(function() {
                    that.stop(false);
                }, p_oOffset);
            }
        } else {
            p_evtTarget.on(p_evtType, function () {
                OffsetManager.addOffsetListener(p_oOffset, function () {
                    that.stop(false);
                });
            });
        }
    }
});


});

})();
/res/3.0/scripts/yui/svg/anim-svg-debug.js
/** =======================================================================
 *  Vincent Hardy
 *  License terms: see svg-wow.org
 *  CC0 http://creativecommons.org/publicdomain/zero/1.0/
 *  ======================================================================= */

YUI.add("anim-svg", function (Y) {

/**
 * Object with the names of the transform pseudo attributes.
 */
var PSEUDO_ATTRIBUTES_REGEXP = {
    tx: /#tx/g,
    ty: /#ty/g,
    sx: /#sx/g,
    sy: /#sy/g,
    r:  /#r/g
};

var PSEUDO_ATTRIBUTES_ARRAY = ["tx", "ty", "sx", "sy", "r"];
var N_PSEUDO_ATTRIBUTES = PSEUDO_ATTRIBUTES_ARRAY.length;

var colorBehavior = Y.Anim.behaviors.color;
var svgColors = Y.DOM.SVG_COLORS;

var svgColorBehavior = {
    set: function(anim, att, from, to, elapsed, duration, fn) {
        if (from in svgColors) {
            from = svgColors[from];
        }
        if (to in svgColors) {
            to = svgColors[to];
        }
        colorBehavior.set(anim, att, from, to, elapsed, duration, fn);
    },

    get: colorBehavior.get
};

Y.Anim.behaviors.transform = {
    set: function (anim, att, from, to, elapsed, duration, fun) {
        var txf = anim.get(att + "Template"), val, p,
            e = anim._node;

        if (txf) {
            for (p in to) {
                if (to.hasOwnProperty(p)) {
                    val = fun(elapsed, from[p], to[p] - from[p], duration);
                    txf = txf.replace(PSEUDO_ATTRIBUTES_REGEXP[p], val);
                    e[p] = val;
                }
            }
            
            e.setAttribute(att, txf);
        }
    },

    get: function (anim, att) {
        var result = {
            tx: 0,
            ty: 0,
            sx: 1,
            sy: 1,
            r: 0
        };
        var e = anim._node;
        for (var i = 0; i < N_PSEUDO_ATTRIBUTES; i++) {
            var a = PSEUDO_ATTRIBUTES_ARRAY[i];
            if (e[a] !== undefined) {
                result[a] = e[a];
            } else {
                e[a] = result[a];
            }
        }
        return result;
    }
};

Y.Anim.behaviors.stdDeviation = {
    set: function (anim, att, from, to, elapsed, duration, fun) {
        var val = [fun(elapsed, from[0], to[0] - from[0], duration),
                   fun(elapsed, from[1], to[1] - from[1], duration)];

        // NOTE: setStdDeviation is more efficient, so use it if available.
        // Firefox 3.6 and earlier doesn't have support for setStdDeviation,
        // so fallback to setAttribute.
        if (anim._node.setStdDeviation) {
            anim._node.setStdDeviation(val[0], val[1]);
        } else {
            anim._node.setAttribute(att, val[0] + " " + val[1]);
        }
    },

    get: function (anim, attr) {
        // NOTE: Got errors in {Firefox, Opera, Safari} about stdDeviationX 
        // not being defined in some cases, fallback to the default value [0,0].
        var result = [0, 0];
        if (anim._node.stdDeviationX !== null &&
            anim._node.stdDeviationY !== undefined) {
            result = [anim._node.stdDeviationX.baseVal,
                    anim._node.stdDeviationY.baseVal];
        }
        return result;
    }
};

var lengthBehavior = {
    set: function (anim, att, from, to, elapsed, duration, fun) {
        var val = fun(elapsed, Number(from), Number(to) - Number(from), duration);
        anim._node.set(att, val);
    },

    get: function (anim, attr) {
        return anim._node.get(attr);
    }
};

var pathCommands = {
    m: 'm',
    M: 'M',
    l: 'l',
    L: 'L',
    h: 'h',
    H: 'H',
    v: 'v',
    V: 'V',
    q: 'q',
    Q: 'Q',
    c: 'c',
    C: 'C',
    z: 'z',
    Z: 'Z',
    s: 's',
    S: 'S',
    t: 't',
    T: 'T',
    a: 'a',
    A: 'A'
};

function parsePath (d) {
    var n;

    if (typeof d === "string") {
        d = d.replace(/([^ ])([hHvVmMlLtTqQsScCaAzZ])/g, '$1 $2')
             .replace(/([hHvVmMlLtTqQsScCaAzZ])([^ ])/g, '$1 $2')
             .replace(/([^ ,])-/g, '$1,-')
             .replace(/[ ]{2,}/g, ' ')
             .replace(/[ ]+/g,',').split(',');
        n = d.length;
        for (var i = 0; i < n; i++) {
            if (pathCommands[d[i]] === undefined) {
                d[i] = Number(d[i]);
            }
        }
    }
    return d;
}

Y.Anim.behaviors.d = {
    set: function (anim, att, from, to, elapsed, duration, fun) {
        from = parsePath(from);
        to = parsePath(to);

        // As in the SVG specification, it is a requirement that the path
        // segment types match. So we only need to interpolate the coordinates.
        var n = to.length,
            c,
            v = [],
            nc,
            is,
            max;
            
        for (var i = 0; i < n;) {
            c = to[i]; // command
            v.push(c);
            nc = 0;
            is = i + 1;
            switch (c) {
                case 'h':
                case 'H':
                case 'v':
                case 'V':
                    i++;
                    do {
                        i++;
                        nc++;
                    } while (typeof to[i] === "number");
                    break;
                case 'm':
                case 'M':
                case 'l':
                case 'L':
                case 't':
                case 'T':
                    i++;
                    do {
                        i += 2;
                        nc += 2;
                   } while (typeof to[i] === "number");
                    break;
                case 'q':
                case 'Q':
                case 's':
                case 'S':
                    i++;
                    do {
                        i += 4;
                        nc += 4;
                   } while (typeof to[i] === "number");
                    break;
                case 'c':
                case 'C':
                    i++;
                    do {
                        i += 6;
                        nc += 6;
                   } while (typeof to[i] === "number");
                    break;
                case 'a':
                case 'A':
                    i++;
                    do {
                        i += 7;
                        nc += 7;
                   } while (typeof to[i] === "number");
                    break;
                // case 'z':
                // case 'Z':
                default:
                    // Includes 'z' and 'Z'
                    i += 1;
                    break;
            }
            max = is + nc;
            for (var j = is; j < max; j++) {
                v[j] = fun(elapsed, from[j], to[j] - from[j], duration);
                if (isNaN(v[j]) === true) {
                    Y.log('v[' + j + '] is NaN');
                }
            }
        }

        anim._node.setAttribute(att, v.join(' '));
    },

    get: function (anim, attr) {
        return parsePath(anim._node.getAttribute(attr));
    }
};

Y.Anim.behaviors.fill = svgColorBehavior;
Y.Anim.behaviors.stroke = svgColorBehavior;
Y.Anim.behaviors["stop-color"] = svgColorBehavior;
Y.Anim.behaviors["flood-color"] = svgColorBehavior;
Y.Anim.behaviors["lighting-color"] = svgColorBehavior;

Y.Anim.behaviors.dy = lengthBehavior;
Y.Anim.behaviors.y = lengthBehavior;
Y.Anim.behaviors.dx = lengthBehavior;
Y.Anim.behaviors.x = lengthBehavior;
Y.Anim.behaviors.rotate = lengthBehavior;
Y.Anim.behaviors.width = lengthBehavior;
Y.Anim.behaviors.height = lengthBehavior;
Y.Anim.behaviors.r = lengthBehavior;
Y.Anim.behaviors.rx = lengthBehavior;
Y.Anim.behaviors.ry = lengthBehavior;
Y.Anim.behaviors.cx = lengthBehavior;
Y.Anim.behaviors.cy = lengthBehavior;
Y.Anim.behaviors.x1 = lengthBehavior;
Y.Anim.behaviors.x2 = lengthBehavior;
Y.Anim.behaviors.y1 = lengthBehavior;
Y.Anim.behaviors.y2 = lengthBehavior;
Y.Anim.behaviors.offset = lengthBehavior;


});