<commit_before>

function Chord(canvas, name, positions, fingering) {
	this.init(canvas, name, positions, fingering);
}

//Defaults

Chord.defaultSize = 3;
Chord.renderOnLoad = true;
var MUTED = -1;

//Matches a named chord with optional fingerings
//              |Small      |Large chord with seperators            |        |Optional|
//              |Chord      |dashes, dots or spaces                 |        |Fingerings
Chord.regex = /([0-9xX]{4,6}|(?:x|X|\d\d?)(?:[-\. ](?:x|\d\d?)){3,5})\b(?:\s*\[([T\d]+)\])?(?:\s+(\d+))?/g;

Chord.prototype = {
    init: function (name, positions, fingers) {
        this.parse(positions, fingers);
        this.name = name;
        this.rawPositions = positions;
        this.rawFingers = fingers || '';
    },

    parse: function (frets, fingers) {
        this.positions = [];
        var raw = [];
        if (frets.match(/^[0-9xX]{1,6}$/)) {
            for (var i = 0; i < frets.length; i++) {
                raw.push(frets.charAt(i));
            }
        } else {
            raw = frets.split(/[^\dxX]/);
        }
        this.stringCount = raw.length;
        if (this.stringCount == 4) {
            this.fretCount = 4;
        } else {
            this.fretCount = 5;
        }
        var maxFret = 0;
        var minFret = 1000;

        for (var i in raw) {
            var c = raw[i];
            if (c.toLowerCase() == 'x') {
                this.positions.push(MUTED);
            } else {
                var fret = parseInt(c);
                if (fret > 0 && fret < minFret) {
                    minFret = fret;
                }
                maxFret = Math.max(maxFret, fret);
                this.positions.push(fret);
            }
        }
        if (maxFret <= this.fretCount) {
            this.startFret = 1;
        } else {
            this.startFret = minFret;
        }
        this.fingerings = [];
        if (!fingers) {
            return;
        }
        var j = 0;
        for (var i = 0; i < fingers.length; i++) {
            for (; j < this.positions.length; j++) {
                if (this.positions[j] <= 0) {
                    this.fingerings.push(null);
                } else {
                    this.fingerings.push(fingers[i]);
                    j++;
                    break;
                }
            }
        }
    },

    drawMutedAndOpenStrings: function (info) {
        var r = this.renderer;
        for (var i in this.positions) {
            var pos = this.positions[i];
            var x = info.boxStartX + i * info.cellWidth;
            var y = info.nameFontSize + info.nameFontPaddingBottom + info.dotRadius - 2;
            if (this.startFret > 1) {
                y += info.nutSize;
            }
            if (pos == MUTED) {
                this.drawCross(info, x, y, info.muteStringRadius);
            } else if (pos == 0) {
                r.circle(x, y, info.openStringRadius, false);
            }
        }
    },

    drawPositions: function (info) {
        var r = this.renderer;
        for (var i in this.positions) {
            var pos = this.positions[i];
            if (pos > 0) {
                var relativePos = pos - this.startFret + 1;
                var x = info.boxStartX + i * info.cellWidth;
                if (relativePos <= 5) {
                    var y = info.boxStartY + relativePos * info.cellHeight - (info.cellHeight / 2)
                    r.circle(x, y, info.dotRadius, true);
                }
            }
        }
    },

    toString: function () {
        return 'Chord';
    },

    drawFretGrid: function (info) {
        var r = this.renderer;
        var width = (this.stringCount - 1) * info.cellWidth;
        for (var i = 0; i <= this.stringCount - 1; i++) {
            var x = info.boxStartX + i * info.cellWidth;
            r.line(x, info.boxStartY, x, info.boxStartY + this.fretCount * info.cellHeight, info.lineWidth, 'square');
        }

        for (var i = 0; i <= this.fretCount; i++) {
            var y = info.boxStartY + i * info.cellHeight;
            r.line(info.boxStartX, y, info.boxStartX + width, y, info.lineWidth, 'square');
        }
    },

    drawNut: function (info) {
        var r = this.renderer;
        if (this.startFret == 1) {
            r.rect(info.boxStartX, info.boxStartY - info.nutSize, info.boxWidth, info.nutSize, info.lineWidth);
        } else {
            r.text(info.boxStartX - info.dotRadius, info.boxStartY + info.cellHeight / 2.0, this.startFret + '', info.font, info.fretFontSize, 'middle', 'right');
        }
    },

    drawName: function (info) {
        var r = this.renderer;
        r.text(info.width / 2.0, 0, this.name, info.font, info.nameFontSize, 'top', 'center');
    },

    //It's better to specify this explicitly. Trying to scale in a nice way to doesn't works so well.
    sizes: {
        cellWidth: 				[4,   6,  8,  10, 12, 14, 16, 18, 20, 22],
        nutSize: 				[2,   3,  4,   5,  6,  7,  8,  9, 10, 11],
        lineWidth:  			[1,   1,  1,   1,  1,  1,  2,  2,  2,  2],
        barWidth:   			[2,   3,  3,   5,  5,  7,  8,  8, 10, 10],
        dotRadius:  			[2,   2.8,  3.7, 4.5,  5.3,  6.5,  7,  8,  9, 10],
        openStringRadius: 		[1.4,   2,  3,   4,  5,  5,  6,  7,  5.5,  6.5],
        muteStringRadius: 		[2,   3,  4,   5,  6,  7,  8,  9, 10, 11],
        nameFontSize: 			[12, 16, 20,  24, 28, 32, 36, 40, 44, 48],
        nameFontPaddingBottom: 	[4,   4,  5,   4,  4,  4,  5,  5,  5,  5],
        fingerFontSize: 		[7,   8,  9,  11, 13, 14, 15, 18, 20, 22],
        fretFontSize: 			[6,   8, 10,  12, 14, 14, 16, 17, 18, 19]
    },

    calculateDimensions: function (scale) {
        var info = {};
        scale--;
        for (var name in this.sizes) {
            info[name] = this.sizes[name][scale];
        }

        info.scale = scale;
        info.positions = this.rawPositions;
        info.fingers = this.rawFingers;
        info.name = this.name;
        info.cellHeight = info.cellWidth;
        info.dotWidth = 2 * info.dotRadius;
        info.font = 'Arial';
        info.boxWidth = (this.stringCount - 1) * info.cellWidth;
        info.boxHeight = (this.fretCount) * info.cellHeight;
        info.width = info.boxWidth + 4 * info.cellWidth;
        info.height = info.nameFontSize + info.nameFontPaddingBottom + info.dotWidth + info.nutSize + info.boxHeight + info.fingerFontSize + 2;
        info.boxStartX = Math.round(((info.width - info.boxWidth) / 2));
        info.boxStartY = Math.round(info.nameFontSize + info.nameFontPaddingBottom + info.nutSize + info.dotWidth);
        return info;
    },

    draw: function (scale) {
        var info = this.calculateDimensions(scale);
        this.renderer.init(info);
        this.drawFretGrid(info);
        this.drawNut(info);
        this.drawName(info);
        this.drawMutedAndOpenStrings(info);
        this.drawPositions(info);
        this.drawFingerings(info);
        this.drawBars(info);
    },

    getDiagram: function (scale, renderer) {
        this.renderer = Chord.renderers.canvas; //Could potentially put in different renderers here, SVG, url etc.
        this.draw(scale);
        return this.renderer.diagram();
    },

    drawBars: function (info) {
        var r = this.renderer;
        if (this.fingerings.length > 0) {
            var bars = {};
            for (var i = 0; i < this.positions.length; i++) {
                var fret = this.positions[i];
                if (fret > 0) {
                    if (bars[fret] && bars[fret].finger == this.fingerings[i]) {
                        bars[fret].length = i - bars[fret].index;
                    } else {
                        bars[fret] = { finger: this.fingerings[i], length: 0, index: i };
                    }
                }
            }
            for (var fret in bars) {
                if (bars[fret].length > 0) {
                    var xStart = info.boxStartX + bars[fret].index * info.cellWidth;
                    var xEnd = xStart + bars[fret].length * info.cellWidth;
                    var relativePos = fret - this.startFret + 1;
                    var y = info.boxStartY + relativePos * info.cellHeight - (info.cellHeight / 2);
                    r.line(xStart, y, xEnd, y, info.barWidth, 'square');
                }
            }

            //Explicit, calculate from that
        } else {
            //Try to guesstimate whether there is a bar or not
            var barFret = this.positions[this.positions.length - 1];
            if (barFret <= 0) {
                return;
            }
            if (this.positions.join('') == '-1-10232') { //Special case for the D chord...
                return;
            }
            var startIndex = -1;

            for (var i = 0; i < this.positions.length - 2; i++) {
                var fret = this.positions[i];
                if (fret > 0 && fret < barFret) {
                    return;
                } else if (fret == barFret && startIndex == -1) {
                    startIndex = i;
                } else if (startIndex != -1 && fret < barFret) {
                    return;
                }
            }
            if (startIndex >= 0) {
                var xStart = info.boxStartX + startIndex * info.cellWidth;
                var xEnd = (this.positions.length - 1) * info.cellWidth;
                var relativePos = barFret - this.startFret + 1;
                var y = info.boxStartY + relativePos * info.cellHeight - (info.cellHeight / 2);
                r.line(xStart, y, xEnd, y, info.dotRadius, 'square');
            }
        }
    },

    drawCross: function (info, x, y, radius) {
        var r = this.renderer;
        var angle = Math.PI / 4
        var lineWidth = info.lineWidth * 1.05;
        for (var i = 0; i < 2; i++) {
            var startAngle = angle + i * Math.PI / 2;
            var endAngle = startAngle + Math.PI;

            var startX = x + radius * Math.cos(startAngle);
            var startY = y + radius * Math.sin(startAngle);
            var endX = x + radius * Math.cos(endAngle);
            var endY = y + radius * Math.sin(endAngle);

            r.line(startX, startY, endX, endY, lineWidth, 'round');
        }
    },

    drawFingerings: function (info) {
        var r = this.renderer;
        var fontSize = info.fingerFontSize;
        for (var i in this.fingerings) {
            var finger = this.fingerings[i]
            var x = info.boxStartX + i * info.cellWidth;
            var y = info.boxStartY + info.boxHeight;
            if (finger) {
                r.text(x, y, finger, info.font, fontSize, 'top', 'center');
            }
        }
    }
}

Chord.renderers = {};

Chord.renderers.canvas = {

	init : function(info) {
		this.canvas = document.createElement('canvas');
		var ctx = this.ctx = this.canvas.getContext('2d');
		this.canvas.width = info.width;
		this.canvas.height = info.height;

		if (info.lineWidth%2==1){
			ctx.translate(0.5,0.5);
		}
		ctx.fillStyle = 'white';
		ctx.fillRect(-1,-1,this.canvas.width+2,this.canvas.height+2);
		ctx.fillStyle = 'black';

		ctx.lineJoin = 'miter';
		ctx.lineWidth = info.lineWidth;
		ctx.lineCap = 'square';
		ctx.strokeStyle = 'black';
	},

	line : function(x1,y1,x2,y2,width,cap) {
		var c = this.ctx;
		c.save();
		if (width) {
			c.lineWidth = width;
		}
		c.lineCap = cap || 'square';
		c.beginPath();
		c.moveTo(x1,y1);
		c.lineTo(x2,y2);
		c.stroke();
		c.restore();
	},

	text : function(x,y,text,font,size,baseline,align) {
		this.ctx.font = size + 'px ' + font;
		this.ctx.textBaseline = baseline;
		this.ctx.textAlign = align;
		this.ctx.fillText(text,x,y)
	},

	rect : function(x,y,width,height, lineWidth) {
		this.ctx.fillRect(x-lineWidth/2.0,y-lineWidth/2.0,width+lineWidth,height+lineWidth);
	},

	circle : function(x,y,radius, fillCircle) {
		var c = this.ctx;
		c.beginPath();
		c.arc(x,y,radius,2*Math.PI,false)
		if (fillCircle) {
			c.fill();
		} else {
			c.stroke();
		}
	},

	diagram : function() {
		var img = document.createElement('img');
		img.src = this.canvas.toDataURL();
		return img;
	}
};

Chord.autoRender = function() {
	if (!Chord.renderOnLoad) {
		return;
	}
	Chord.render(document.getElementsByTagName('span'));
};

if (document.addEventListener) {
	document.addEventListener('DOMContentLoaded', Chord.autoRender, true);
} else if (window.attachEvent) {
	window.attachEvent('onload', Chord.autoRender);
}

Chord.render = function(elements) {

	for (var i = 0; i < elements.length; i++) {
		var el = elements[i];
		var chordDef = el.getAttribute('data-chord');
		var chordName = el.firstChild.nodeValue;
		if (chordDef && chordDef.match(Chord.regex)) {
			var size = Chord.defaultSize;
			if (RegExp.$3) {
				size = parseInt(RegExp.$3);
            }

			el.replaceChild(new Chord(chordName, RegExp.$1, RegExp.$2).getDiagram(size), el.firstChild);
		}
	}
}

<commit_msg>Size of circles and crosses adjusted<commit_after>

function Chord(canvas, name, positions, fingering) {
	this.init(canvas, name, positions, fingering);
}

//Defaults

Chord.defaultSize = 3;
Chord.renderOnLoad = true;
var MUTED = -1;

//Matches a named chord with optional fingerings
//              |Small      |Large chord with seperators            |        |Optional|
//              |Chord      |dashes, dots or spaces                 |        |Fingerings
Chord.regex = /([0-9xX]{4,6}|(?:x|X|\d\d?)(?:[-\. ](?:x|\d\d?)){3,5})\b(?:\s*\[([T\d]+)\])?(?:\s+(\d+))?/g;

Chord.prototype = {
    init: function (name, positions, fingers) {
        this.parse(positions, fingers);
        this.name = name;
        this.rawPositions = positions;
        this.rawFingers = fingers || '';
    },

    parse: function (frets, fingers) {
        this.positions = [];
        var raw = [];
        if (frets.match(/^[0-9xX]{1,6}$/)) {
            for (var i = 0; i < frets.length; i++) {
                raw.push(frets.charAt(i));
            }
        } else {
            raw = frets.split(/[^\dxX]/);
        }
        this.stringCount = raw.length;
        if (this.stringCount == 4) {
            this.fretCount = 4;
        } else {
            this.fretCount = 5;
        }
        var maxFret = 0;
        var minFret = 1000;

        for (var i in raw) {
            var c = raw[i];
            if (c.toLowerCase() == 'x') {
                this.positions.push(MUTED);
            } else {
                var fret = parseInt(c);
                if (fret > 0 && fret < minFret) {
                    minFret = fret;
                }
                maxFret = Math.max(maxFret, fret);
                this.positions.push(fret);
            }
        }
        if (maxFret <= this.fretCount) {
            this.startFret = 1;
        } else {
            this.startFret = minFret;
        }
        this.fingerings = [];
        if (!fingers) {
            return;
        }
        var j = 0;
        for (var i = 0; i < fingers.length; i++) {
            for (; j < this.positions.length; j++) {
                if (this.positions[j] <= 0) {
                    this.fingerings.push(null);
                } else {
                    this.fingerings.push(fingers[i]);
                    j++;
                    break;
                }
            }
        }
    },

    drawMutedAndOpenStrings: function (info) {
        var r = this.renderer;
        for (var i in this.positions) {
            var pos = this.positions[i];
            var x = info.boxStartX + i * info.cellWidth;
            var y = info.nameFontSize + info.nameFontPaddingBottom + info.dotRadius - 2;
            if (this.startFret > 1) {
                y += info.nutSize;
            }
            if (pos == MUTED) {
                this.drawCross(info, x, y, info.muteStringRadius, info.muteStringLineWidth);
            } else if (pos == 0) {
                r.circle(x, y, info.openStringRadius, false, info.openStringLineWidth);
            }
        }
    },

    drawPositions: function (info) {
        var r = this.renderer;
        for (var i in this.positions) {
            var pos = this.positions[i];
            if (pos > 0) {
                var relativePos = pos - this.startFret + 1;
                var x = info.boxStartX + i * info.cellWidth;
                if (relativePos <= 5) {
                    var y = info.boxStartY + relativePos * info.cellHeight - (info.cellHeight / 2)
                    r.circle(x, y, info.dotRadius, true);
                }
            }
        }
    },

    toString: function () {
        return 'Chord';
    },

    drawFretGrid: function (info) {
        var r = this.renderer;
        var width = (this.stringCount - 1) * info.cellWidth;
        for (var i = 0; i <= this.stringCount - 1; i++) {
            var x = info.boxStartX + i * info.cellWidth;
            r.line(x, info.boxStartY, x, info.boxStartY + this.fretCount * info.cellHeight, info.lineWidth, 'square');
        }

        for (var i = 0; i <= this.fretCount; i++) {
            var y = info.boxStartY + i * info.cellHeight;
            r.line(info.boxStartX, y, info.boxStartX + width, y, info.lineWidth, 'square');
        }
    },

    drawNut: function (info) {
        var r = this.renderer;
        if (this.startFret == 1) {
            r.rect(info.boxStartX, info.boxStartY - info.nutSize, info.boxWidth, info.nutSize, info.lineWidth);
        } else {
            r.text(info.boxStartX - info.dotRadius, info.boxStartY + info.cellHeight / 2.0, this.startFret + '', info.font, info.fretFontSize, 'middle', 'right');
        }
    },

    drawName: function (info) {
        var r = this.renderer;
        r.text(info.width / 2.0, 0, this.name, info.font, info.nameFontSize, 'top', 'center');
    },

    //It's better to specify this explicitly. Trying to scale in a nice way to doesn't works so well.
    sizes: {
        cellWidth: 				[4,   6,  8,  10, 12, 14, 16, 18, 20, 22],
        nutSize: 				[2,   3,  4,   5,  6,  7,  8,  9, 10, 11],
        lineWidth:  			[1,   1,  1,   1,  1,  1,  2,  2,  2,  2],
        barWidth:   			[2.5,   3,  5,   7,  7,  9,  10,  10, 12, 12],
        dotRadius:  			[2,   2.8,  3.7, 4.5,  5.3,  6.5,  7,  8,  9, 10],
        openStringRadius: 		[1.5,   2,  2.5,   3,  3.5,  4,  4.5,  5,  5.5,  6.5],
        openStringLineWidth: 	[1,   1.2,  1.2,   1.4,  1.4,  1.4,  1.6,  2,  2,  2],
        muteStringRadius: 		[2,   2.5,  3,   3.5,  4,  4.5,  5,  5.5, 6, 6.5],
        muteStringLineWidth:	[1.05,   1.1,  1.1,   1.2,  1.5,  1.5,  1.5,  2,  2.4,  2.5],
		nameFontSize: 			[12, 16, 20,  24, 28, 32, 36, 40, 44, 48],
        nameFontPaddingBottom: 	[4,   4,  5,   4,  4,  4,  5,  5,  5,  5],
        fingerFontSize: 		[7,   8,  9,  11, 13, 14, 15, 18, 20, 22],
        fretFontSize: 			[6,   8, 10,  12, 14, 14, 16, 17, 18, 19]
    },

    calculateDimensions: function (scale) {
        var info = {};
        scale--;
        for (var name in this.sizes) {
            info[name] = this.sizes[name][scale];
        }

        info.scale = scale;
        info.positions = this.rawPositions;
        info.fingers = this.rawFingers;
        info.name = this.name;
        info.cellHeight = info.cellWidth;
        info.dotWidth = 2 * info.dotRadius;
        info.font = 'Arial';
        info.boxWidth = (this.stringCount - 1) * info.cellWidth;
        info.boxHeight = (this.fretCount) * info.cellHeight;
        info.width = info.boxWidth + 4 * info.cellWidth;
        info.height = info.nameFontSize + info.nameFontPaddingBottom + info.dotWidth + info.nutSize + info.boxHeight + info.fingerFontSize + 2;
        info.boxStartX = Math.round(((info.width - info.boxWidth) / 2));
        info.boxStartY = Math.round(info.nameFontSize + info.nameFontPaddingBottom + info.nutSize + info.dotWidth);
        return info;
    },

    draw: function (scale) {
        var info = this.calculateDimensions(scale);
        this.renderer.init(info);
        this.drawFretGrid(info);
        this.drawNut(info);
        this.drawName(info);
        this.drawMutedAndOpenStrings(info);
        this.drawPositions(info);
        this.drawFingerings(info);
        this.drawBars(info);
    },

    getDiagram: function (scale, renderer) {
        this.renderer = Chord.renderers.canvas; //Could potentially put in different renderers here, SVG, url etc.
        this.draw(scale);
        return this.renderer.diagram();
    },

    drawBars: function (info) {
        var r = this.renderer;
        if (this.fingerings.length > 0) {
            var bars = {};
            for (var i = 0; i < this.positions.length; i++) {
                var fret = this.positions[i];
                if (fret > 0) {
                    if (bars[fret] && bars[fret].finger == this.fingerings[i]) {
                        bars[fret].length = i - bars[fret].index;
                    } else {
                        bars[fret] = { finger: this.fingerings[i], length: 0, index: i };
                    }
                }
            }
            for (var fret in bars) {
                if (bars[fret].length > 0) {
                    var xStart = info.boxStartX + bars[fret].index * info.cellWidth;
                    var xEnd = xStart + bars[fret].length * info.cellWidth;
                    var relativePos = fret - this.startFret + 1;
                    var y = info.boxStartY + relativePos * info.cellHeight - (info.cellHeight / 2);
					console.log('y: ' + y + ', barWidth: ' + info.barWidth);
                    r.line(xStart, y, xEnd, y, info.barWidth, 'square');
                }
            }

            //Explicit, calculate from that
        } else {
            //Try to guesstimate whether there is a bar or not
            var barFret = this.positions[this.positions.length - 1];
            if (barFret <= 0) {
                return;
            }
            if (this.positions.join('') == '-1-10232') { //Special case for the D chord...
                return;
            }
            var startIndex = -1;

            for (var i = 0; i < this.positions.length - 2; i++) {
                var fret = this.positions[i];
                if (fret > 0 && fret < barFret) {
                    return;
                } else if (fret == barFret && startIndex == -1) {
                    startIndex = i;
                } else if (startIndex != -1 && fret < barFret) {
                    return;
                }
            }
            if (startIndex >= 0) {
                var xStart = info.boxStartX + startIndex * info.cellWidth;
                var xEnd = (this.positions.length - 1) * info.cellWidth;
                var relativePos = barFret - this.startFret + 1;
                var y = info.boxStartY + relativePos * info.cellHeight - (info.cellHeight / 2);
                r.line(xStart, y, xEnd, y, info.dotRadius, 'square');
            }
        }
    },

    drawCross: function (info, x, y, radius, lineWidth) {
        var r = this.renderer;
        var angle = Math.PI / 4
        for (var i = 0; i < 2; i++) {
            var startAngle = angle + i * Math.PI / 2;
            var endAngle = startAngle + Math.PI;

            var startX = x + radius * Math.cos(startAngle);
            var startY = y + radius * Math.sin(startAngle);
            var endX = x + radius * Math.cos(endAngle);
            var endY = y + radius * Math.sin(endAngle);

            r.line(startX, startY, endX, endY, lineWidth, 'round');
        }
    },

    drawFingerings: function (info) {
        var r = this.renderer;
        var fontSize = info.fingerFontSize;
        for (var i in this.fingerings) {
            var finger = this.fingerings[i]
            var x = info.boxStartX + i * info.cellWidth;
            var y = info.boxStartY + info.boxHeight;
            if (finger) {
                r.text(x, y, finger, info.font, fontSize, 'top', 'center');
            }
        }
    }
}

Chord.renderers = {};

Chord.renderers.canvas = {

	init : function(info) {
		this.canvas = document.createElement('canvas');
		var ctx = this.ctx = this.canvas.getContext('2d');
		this.canvas.width = info.width;
		this.canvas.height = info.height;

		if (info.lineWidth%2==1){
			ctx.translate(0.5,0.5);
		}
		ctx.fillStyle = 'white';
		ctx.fillRect(-1,-1,this.canvas.width+2,this.canvas.height+2);
		ctx.fillStyle = 'black';

		ctx.lineJoin = 'miter';
		ctx.lineWidth = info.lineWidth;
		ctx.lineCap = 'square';
		ctx.strokeStyle = 'black';
	},

	line : function(x1,y1,x2,y2,width,cap) {
		var c = this.ctx;
		c.save();
		if (width) {
			c.lineWidth = width;
		}
		c.lineCap = cap || 'square';
		c.beginPath();
		c.moveTo(x1,y1);
		c.lineTo(x2,y2);
		c.stroke();
		c.restore();
	},

	text : function(x,y,text,font,size,baseline,align) {
		this.ctx.font = size + 'px ' + font;
		this.ctx.textBaseline = baseline;
		this.ctx.textAlign = align;
		this.ctx.fillText(text,x,y)
	},

	rect : function(x,y,width,height, lineWidth) {
		this.ctx.fillRect(x-lineWidth/2.0,y-lineWidth/2.0,width+lineWidth,height+lineWidth);
	},

	circle : function(x,y,radius, fillCircle, lineWidth) {
		var c = this.ctx;
		c.beginPath();
		c.arc(x,y,radius,2*Math.PI,false)
		if (fillCircle) {
			c.fill();
		} else {
			c.lineWidth = lineWidth;
			c.stroke();
		}
	},

	diagram : function() {
		var img = document.createElement('img');
		img.src = this.canvas.toDataURL();
		return img;
	}
};

Chord.autoRender = function() {
	if (!Chord.renderOnLoad) {
		return;
	}
	Chord.render(document.getElementsByTagName('span'));
};

if (document.addEventListener) {
	document.addEventListener('DOMContentLoaded', Chord.autoRender, true);
} else if (window.attachEvent) {
	window.attachEvent('onload', Chord.autoRender);
}

Chord.render = function(elements) {

	for (var i = 0; i < elements.length; i++) {
		var el = elements[i];
		var chordDef = el.getAttribute('data-chord');
		var chordName = el.firstChild.nodeValue;
		if (chordDef && chordDef.match(Chord.regex)) {
			var size = Chord.defaultSize;
			if (RegExp.$3) {
				size = parseInt(RegExp.$3);
            }

			el.replaceChild(new Chord(chordName, RegExp.$1, RegExp.$2).getDiagram(size), el.firstChild);
		}
	}
}

<|endoftext|>


<commit_before>var digger;

dungeonPhase = function(game) {
    Phaser.State.call(this);

    this._game = game;
}

//Extend the dungeonPhase object to be a Phaser.State
dungeonPhase.prototype = Object.create(Phaser.State.prototype);
dungeonPhase.prototype.constructor = dungeonPhase;

dungeonPhase.prototype.update = function(){
    var map = this._game.state.getCurrentState()._map;
    var items = map._items;

    //Check whether the collectables are collected, and whether we are not yet in the last level of the phase.
        if(items.children.length == 0 && !ran && this._game._level != 9){
            ran = true;
            run = true;
            this._game._level++;
        }
}

dungeonPhase.prototype.create = function(){
    //instantiate worldmap and create layer (this displays the map)
    this._map = new WorldMap(
        this._game,             //game
        'level',                //reference to tilemap
        'tiles_dungeon',        //reference to tile images
        32,                     //tileimage dimensions
        this.generate,          //map generation function
        'collectable_dungeon',  //collectable image
        this.getItemPosition    //item position function
    );

    this._layer = this._map.createLayer(0);
    this._layer.resizeWorld();

    //add items to the game
    this._game.add.existing(this._map._items);

    //add doors to the game
    this._game.add.existing(this._map._doors);

    //Instantiate new player object
    this._player = new Player(this._game, 0.6, 'player_dungeon', this.getPlayerPosition);

    //postpone character creation for a sec to avoid rendering problems
    setTimeout((function(self) { return function() {
            self._game.add.existing(self._player);
        }})(this),200);
};

//Returns a position on the map where the player can spawn
dungeonPhase.prototype.getPlayerPosition = function(){
    //get the index of a random room
    var i = Math.floor(ROT.RNG.getUniform() * digger._rooms.length);

    //return the center of htat room
    var randomPosition = digger._rooms[i].getCenter();
    return [(randomPosition[0]+1)*32, (randomPosition[1]+1)*32]; //+1 for border tile compensation
}

//Returns a position on the map where an item can spawn
var roomObjectCount = {};
var roomDoorCount = {};

dungeonPhase.prototype.getRoom = function(condition, log){
    var i = Math.floor(ROT.RNG.getUniform() * digger._rooms.length);

    if(condition(i)){
        //increase log array
        if(typeof log[i] == "undefined"){ log[i] = 1; } else { log[i]++; }
        return i;
    } else {
        return this.getRoom(condition, log);
    }

}

dungeonPhase.prototype.getItemPosition = function(){
    //get right room index to put a door at.
    var i = this.getRoom(function(i){
        //console.log(Object.keys(roomDoorCount).length);
        console.log(Object.keys(roomObjectCount).length);

        if(Object.keys(roomObjectCount).length >= Object.keys(roomDoorCount).length){
            console.log('test');
            return ((typeof roomObjectCount[i] == "undefined"));
        } else {
            return ((roomDoorCount[i] > 0) && (typeof roomObjectCount[i] == "undefined"));
        }
    }, roomObjectCount);

    //return a tile against the wall of that room
    var room = digger._rooms[i];
    var left = room.getLeft()+1; //+1 for border tile compensation
    var right = room.getRight()+1;
    var top = room.getTop()+1;
    var bottom = room.getBottom()+1;

    var side = Math.floor(ROT.RNG.getUniform() * 4);
    var x, y;
    var prohibitedx = [];
    var prohibitedy = []; //x and y's from doors: we dont want to have chests spawning there.

    //find all the coordinates of all doors in the current room
    for (var door in room._doors){
        var coords = door.split(',');
        prohibitedx.push(coords[0]);
        prohibitedy.push(coords[1]);
    }

    //retry when the x and y match a door location.

    ////////////////////////////////NOTE: super ugly, but functional.
    while((prohibitedx.indexOf(x) != -1 && prohibitedy.contains(y) != -1) || typeof x == "undefined"){
        switch(side){
            case 0: //left wall
                x = left;
                y = top + Math.floor(ROT.RNG.getUniform() * (bottom-top));
                break;
            case 1: //right wall
                x = right;
                y = top + Math.floor(ROT.RNG.getUniform() * (bottom-top));
                break;
            case 2: //top wall
                x = left + Math.floor(ROT.RNG.getUniform() * (right-left));
                y = top;
                break;
            case 3: //bottom wall
                x = left + Math.floor(ROT.RNG.getUniform() * (right-left));
                y = bottom;
                break;
        }
    }

    return [x*32 ,y*32];
}

dungeonPhase.prototype.getDoorPosition = function(){
    //get right room index to put a door at.
    var i = this.getRoom(function(i){return ((typeof roomDoorCount[i] == "undefined") && Object.keys(digger._rooms[i]._doors).length < 2);}, roomDoorCount);

    console.log("room " + i + " has a door");
    //return a tile against the wall of that room
    var room = digger._rooms[i];
    var x,y;
    for (var door in room._doors){
        var coords = door.split(',');
        x = parseInt(coords[0])+1;
        y = parseInt(coords[1])+1;

        return [x*32 ,y*32];
    }
}

//map generation for dungeon (ROT uniform dungeon algorithm)
dungeonPhase.prototype.generate = function()
{
    roomObjectCount = {};
    roomDoorCount = {};

    var w = 80, h = 60;
    digger = new ROT.Map.Uniform(w, h, {
        roomWidth: [5,10],
        roomHeight: [5,10],
        roomDugPercentage: 0.13
    });
    //map.randomize(0.52);

    var display;
    var terrainMap = [];

    var digCallback = function(x, y, value) {
        if(terrainMap[x+1] == null){
            terrainMap[x+1] = ["border",]; //add row to the TOP of the map
        }

        terrainMap[x+1][y+1] = value; //+1 for border tile compensation

        //channel info to debug so the preview can be rendered.
        display.DEBUG(x,y,value);
    }

    display = new ROT.Display({width:w, height:h, fontSize:4});
    digger.create(digCallback.bind(this));

    //add a column to the LEFT of the map
    terrainMap[0] = [];
    for(var i = 0; i < terrainMap[1].length; i++){ terrainMap[0].push("border"); }

    //add a column to the RIGHT of the map
    terrainMap[terrainMap.length-1] = [];
    for(var i = 0; i < terrainMap[1].length; i++){ terrainMap[terrainMap.length-1].push("border"); }
        terrainMap[terrainMap.length-1] = [];
    for(var i = 0; i < terrainMap[1].length; i++){ terrainMap[terrainMap.length-1].push("border"); }

    //add a row to the BOTTOM of the map
    for(var i = 0; i < terrainMap.length; i++){ terrainMap[i].push("border"); }

    var i = Math.floor(ROT.RNG.getUniform() * digger._rooms.length);
    startLocation = digger._rooms[i].getCenter();

    //show map in canvas
    if (pixelEvolution._showMinimap){
        $('#minimap').html(display.getContainer());
    }

    var level = "";

    for (var i=0; i<terrainMap[0].length; i++) {
        for (var j=0; j<terrainMap.length; j++) {
            if (terrainMap[j][i] == "0"){
                terrainMap[j][i] = "1";
            } else if (terrainMap[j][i] == "1"){
                terrainMap[j][i] = "0";
            }
        }
    }

    //Remove single outliers
    /*for (var i=0; i<terrainMap[0].length; i++) {
      for (var j=0; j<terrainMap.length; j++) {
      var point = terrainMap[j][i]+"";

      try{
      if(terrainMap[j-1][i] == 1 && terrainMap[j+1][i] == 1 && terrainMap[j][i+1] == 1){
      terrainMap[j][i] = "1";
      } else if(terrainMap[j-1][i] == 1 && terrainMap[j+1][i] == 1 && terrainMap[j][i-1] == 1){
      terrainMap[j][i] = "1";
      }

      if(terrainMap[j][i+1] == 1 && terrainMap[j][i-1] == 1 && terrainMap[j+1][i] == 1){
      terrainMap[j][i] = "1";
      } else if(terrainMap[j][i+1] == 1 && terrainMap[j][i-1] == 1 && terrainMap[j-1][i] == 1){
      terrainMap[j][i] = "1";
      }
      } catch(e){}
      }
      }*/

    for (var i=0; i<terrainMap[0].length; i++) {
        for (var j=0; j<terrainMap.length; j++) {
            var point = terrainMap[j][i]+"";

            if(point=="0" || point=="border"){
                try{
                    if(terrainMap[j-1][i+1] == 1 && terrainMap[j-1][i] == 1 && terrainMap[j][i+1] == 1){ //bottom left corner outward
                        point = "66";
                    } else if(terrainMap[j-1][i-1] == 1 && terrainMap[j-1][i] == 1 && terrainMap[j][i-1] == 1){ //top left corner outward
                        point = "64";
                    } else if(terrainMap[j+1][i+1] == 1 && terrainMap[j+1][i] == 1 && terrainMap[j][i+1] == 1){ //bottom right corner outward
                        point = "65";
                    } else if(terrainMap[j+1][i-1] == 1 && terrainMap[j+1][i] == 1 && terrainMap[j][i-1] == 1){ //top right corner outward
                        point = "63";
                    } else if(terrainMap[j-1][i] == 1){ //left V
                        point = "59";
                        } else if(terrainMap[j+1][i] == 1){ //right V
                        point = "57";

                    } else if(terrainMap[j][i-1] == 1){ //bottom V
                        point = "61";
                    } else if(terrainMap[j][i+1] == 1){ //top V
                        point = "55";
                    } else if(terrainMap[j-1][i+1] == 1){ //bottom left corner
                        point = "56";
                    } else if(terrainMap[j-1][i-1] == 1){ //bottom right corner
                        point = "62";
                    } else if(terrainMap[j+1][i+1] == 1){ //top left corner
                        point = "54";
                    } else if(terrainMap[j+1][i-1] == 1){ //top right corner
                        point = "60";
                    } else {
                        point = "25";
                    }

                }catch(e){
                    point = "25";
                }
            } else {
                point = "0";
            }

            level += point + ",";
        }
        level = level.substring(0,level.length-1) + "\n";
    }

    return level;
}

<commit_msg>quick bug fix before I forget: actually decrease the amount of keys when opening a door.<commit_after>var digger;

dungeonPhase = function(game) {
    Phaser.State.call(this);

    this._game = game;
}

//Extend the dungeonPhase object to be a Phaser.State
dungeonPhase.prototype = Object.create(Phaser.State.prototype);
dungeonPhase.prototype.constructor = dungeonPhase;

dungeonPhase.prototype.update = function(){
    var map = this._game.state.getCurrentState()._map;
    var items = map._items;

    //Check whether the collectables are collected, and whether we are not yet in the last level of the phase.
        if(items.children.length == 0 && !ran && this._game._level != 9){
            ran = true;
            run = true;
            this._game._level++;
        }
}

dungeonPhase.prototype.create = function(){
    //instantiate worldmap and create layer (this displays the map)
    this._map = new WorldMap(
        this._game,             //game
        'level',                //reference to tilemap
        'tiles_dungeon',        //reference to tile images
        32,                     //tileimage dimensions
        this.generate,          //map generation function
        'collectable_dungeon',  //collectable image
        this.getItemPosition    //item position function
    );

    this._layer = this._map.createLayer(0);
    this._layer.resizeWorld();

    //add items, doors and keys to the game
    this._game.add.existing(this._map._items);
    this._game.add.existing(this._map._doors);
    this._game.add.existing(this._map._keys);

    //Instantiate new player object
    this._player = new Player(this._game, 0.6, 'player_dungeon', this.getPlayerPosition);

    //postpone character creation for a sec to avoid rendering problems
    setTimeout((function(self) { return function() {
            self._game.add.existing(self._player);
        }})(this),200);
};

//Returns a position on the map where an item can spawn
var roomObjectCount = {};
var roomDoorCount = {};

dungeonPhase.prototype.getRoom = function(condition, log){
    var i = Math.floor(ROT.RNG.getUniform() * digger._rooms.length);

    if(condition(i)){
        //increase log array
        if(log != null){
            if(typeof log[i] == "undefined"){ log[i] = 1; } else { log[i]++; }
        }

        return i;
    } else {
        return this.getRoom(condition, log);
    }
}

//Returns the middle of a room that has not have a locked door.
dungeonPhase.prototype.getPlayerPosition = function(){
    //get the index of a random room
    var i = this.getRoom(function(i){
        return (typeof roomDoorCount[i] == "undefined");
    }, null);

    //return the center of htat room
    var randomPosition = digger._rooms[i].getCenter();
    return [(randomPosition[0]+1)*32, (randomPosition[1]+1)*32]; //+1 for border tile compensation
}

//return the sides of a room where that has a locked door if those are available.
//this never spawns a second chest in a room either.
dungeonPhase.prototype.getItemPosition = function(){
    //get right room index to put a door at.
    var i = this.getRoom(function(i){
        if(Object.keys(roomObjectCount).length >= Object.keys(roomDoorCount).length){
            return ((typeof roomObjectCount[i] == "undefined"));
        } else {
            return ((roomDoorCount[i] > 0) && (typeof roomObjectCount[i] == "undefined"));
        }
    }, roomObjectCount);

    //return a tile against the wall of that room
    var room = digger._rooms[i];
    var left = room.getLeft()+1; //+1 for border tile compensation
    var right = room.getRight()+1;
    var top = room.getTop()+1;
    var bottom = room.getBottom()+1;

    var side = Math.floor(ROT.RNG.getUniform() * 4);
    var x, y;
    var prohibitedx = [];
    var prohibitedy = []; //x and y's from doors: we dont want to have chests spawning there.

    //find all the coordinates of all doors in the current room
    for (var door in room._doors){
        var coords = door.split(',');
        prohibitedx.push(coords[0]);
        prohibitedy.push(coords[1]);
    }

    //retry when the x and y match a door location.

    ////////////////////////////////NOTE: super ugly, but functional.
    while((prohibitedx.indexOf(x) != -1 && prohibitedy.contains(y) != -1) || typeof x == "undefined"){
        switch(side){
            case 0: //left wall
                x = left;
                y = top + Math.floor(ROT.RNG.getUniform() * (bottom-top));
                break;
            case 1: //right wall
                x = right;
                y = top + Math.floor(ROT.RNG.getUniform() * (bottom-top));
                break;
            case 2: //top wall
                x = left + Math.floor(ROT.RNG.getUniform() * (right-left));
                y = top;
                break;
            case 3: //bottom wall
                x = left + Math.floor(ROT.RNG.getUniform() * (right-left));
                y = bottom;
                break;
        }
    }

    return [x*32 ,y*32];
}

dungeonPhase.prototype.getKeyPosition = function(){
    //get right room index to put a key at.
    var i = this.getRoom(function(i){
        return ((typeof roomDoorCount[i] == "undefined") && Object.keys(digger._rooms[i]._doors).length > 1);
    }, roomDoorCount);

    //return a tile against the wall of that room
    var room = digger._rooms[i];
    var left = room.getLeft()+1; //+1 for border tile compensation
    var right = room.getRight()+1;
    var top = room.getTop()+1;
    var bottom = room.getBottom()+1;

    var x = left + Math.floor(ROT.RNG.getUniform() * (right - left));
    var y = top + Math.floor(ROT.RNG.getUniform() * (bottom - top));

    return [x*32 ,y*32];
}

dungeonPhase.prototype.getDoorPosition = function(){
    //get right room index to put a door at.
    var i = this.getRoom(function(i){
        return ((typeof roomDoorCount[i] == "undefined") && Object.keys(digger._rooms[i]._doors).length < 2);
    }, roomDoorCount);

    //return a tile against the wall of that room
    var room = digger._rooms[i];
    var x,y;
    for (var door in room._doors){
        var coords = door.split(',');
        x = parseInt(coords[0])+1;
        y = parseInt(coords[1])+1;

        return [x*32 ,y*32];
    }
}

//map generation for dungeon (ROT uniform dungeon algorithm)
dungeonPhase.prototype.generate = function()
{
    roomObjectCount = {};
    roomDoorCount = {};

    var w = 80, h = 60;
    digger = new ROT.Map.Uniform(w, h, {
        roomWidth: [5,10],
        roomHeight: [5,10],
        roomDugPercentage: 0.13
    });
    //map.randomize(0.52);

    var display;
    var terrainMap = [];

    var digCallback = function(x, y, value) {
        if(terrainMap[x+1] == null){
            terrainMap[x+1] = ["border",]; //add row to the TOP of the map
        }

        terrainMap[x+1][y+1] = value; //+1 for border tile compensation

        //channel info to debug so the preview can be rendered.
        display.DEBUG(x,y,value);
    }

    display = new ROT.Display({width:w, height:h, fontSize:4});
    digger.create(digCallback.bind(this));

    //add a column to the LEFT of the map
    terrainMap[0] = [];
    for(var i = 0; i < terrainMap[1].length; i++){ terrainMap[0].push("border"); }

    //add a column to the RIGHT of the map
    terrainMap[terrainMap.length-1] = [];
    for(var i = 0; i < terrainMap[1].length; i++){ terrainMap[terrainMap.length-1].push("border"); }
        terrainMap[terrainMap.length-1] = [];
    for(var i = 0; i < terrainMap[1].length; i++){ terrainMap[terrainMap.length-1].push("border"); }

    //add a row to the BOTTOM of the map
    for(var i = 0; i < terrainMap.length; i++){ terrainMap[i].push("border"); }

    var i = Math.floor(ROT.RNG.getUniform() * digger._rooms.length);
    startLocation = digger._rooms[i].getCenter();

    //show map in canvas
    if (pixelEvolution._showMinimap){
        $('#minimap').html(display.getContainer());
    }

    var level = "";

    for (var i=0; i<terrainMap[0].length; i++) {
        for (var j=0; j<terrainMap.length; j++) {
            if (terrainMap[j][i] == "0"){
                terrainMap[j][i] = "1";
            } else if (terrainMap[j][i] == "1"){
                terrainMap[j][i] = "0";
            }
        }
    }

    //Remove single outliers
    /*for (var i=0; i<terrainMap[0].length; i++) {
      for (var j=0; j<terrainMap.length; j++) {
      var point = terrainMap[j][i]+"";

      try{
      if(terrainMap[j-1][i] == 1 && terrainMap[j+1][i] == 1 && terrainMap[j][i+1] == 1){
      terrainMap[j][i] = "1";
      } else if(terrainMap[j-1][i] == 1 && terrainMap[j+1][i] == 1 && terrainMap[j][i-1] == 1){
      terrainMap[j][i] = "1";
      }

      if(terrainMap[j][i+1] == 1 && terrainMap[j][i-1] == 1 && terrainMap[j+1][i] == 1){
      terrainMap[j][i] = "1";
      } else if(terrainMap[j][i+1] == 1 && terrainMap[j][i-1] == 1 && terrainMap[j-1][i] == 1){
      terrainMap[j][i] = "1";
      }
      } catch(e){}
      }
      }*/

    for (var i=0; i<terrainMap[0].length; i++) {
        for (var j=0; j<terrainMap.length; j++) {
            var point = terrainMap[j][i]+"";

            if(point=="0" || point=="border"){
                try{
                    if(terrainMap[j-1][i+1] == 1 && terrainMap[j-1][i] == 1 && terrainMap[j][i+1] == 1){ //bottom left corner outward
                        point = "66";
                    } else if(terrainMap[j-1][i-1] == 1 && terrainMap[j-1][i] == 1 && terrainMap[j][i-1] == 1){ //top left corner outward
                        point = "64";
                    } else if(terrainMap[j+1][i+1] == 1 && terrainMap[j+1][i] == 1 && terrainMap[j][i+1] == 1){ //bottom right corner outward
                        point = "65";
                    } else if(terrainMap[j+1][i-1] == 1 && terrainMap[j+1][i] == 1 && terrainMap[j][i-1] == 1){ //top right corner outward
                        point = "63";
                    } else if(terrainMap[j-1][i] == 1){ //left V
                        point = "59";
                        } else if(terrainMap[j+1][i] == 1){ //right V
                        point = "57";

                    } else if(terrainMap[j][i-1] == 1){ //bottom V
                        point = "61";
                    } else if(terrainMap[j][i+1] == 1){ //top V
                        point = "55";
                    } else if(terrainMap[j-1][i+1] == 1){ //bottom left corner
                        point = "56";
                    } else if(terrainMap[j-1][i-1] == 1){ //bottom right corner
                        point = "62";
                    } else if(terrainMap[j+1][i+1] == 1){ //top left corner
                        point = "54";
                    } else if(terrainMap[j+1][i-1] == 1){ //top right corner
                        point = "60";
                    } else {
                        point = "25";
                    }

                }catch(e){
                    point = "25";
                }
            } else {
                point = "0";
            }

            level += point + ",";
        }
        level = level.substring(0,level.length-1) + "\n";
    }

    return level;
}

<|endoftext|>


<commit_before>import React                   from 'react';
import defaultServerParameters from '../../../../../../panels/run/defaults';
import RunClusterFrom          from '../../../../../../panels/run';
import ButtonBar               from '../../../../../../panels/ButtonBar';
import ClusterPayloads         from '../../../../../../utils/ClusterPayload';

import { connect }  from 'react-redux';
import get          from 'mout/src/object/get';
import { dispatch } from '../../../../../../redux';
import * as Actions from '../../../../../../redux/actions/taskflows';

const VisualizationStart = React.createClass({
  displayName: 'pvw/start-visualization',
  propTypes: {
    location: React.PropTypes.object,
    project: React.PropTypes.object,
    simulation: React.PropTypes.object,
    step: React.PropTypes.string,
    taskFlowName: React.PropTypes.string,
    primaryJob: React.PropTypes.string,
    view: React.PropTypes.string,

    error: React.PropTypes.string,
    tradClusters: React.PropTypes.object,
    ec2Clusters: React.PropTypes.object,
    onRun: React.PropTypes.func,
  },

  getInitialState() {
    return {
      serverType: 'Traditional',
      EC2: defaultServerParameters.EC2,
      Traditional: defaultServerParameters.Traditional,
      OpenStack: defaultServerParameters.OpenStack,
      error: null,
    };
  },

  dataChange(key, value, which) {
    var profile = this.state[which];
    profile[key] = value;
    this.setState({ [which]: profile });
  },

  startVisualization() {
    const sessionKey = btoa(new Float64Array(3).map(Math.random)).substring(0, 96);
    const payload = {
      sessionKey,
      input: {
        file: {
          id: this.props.simulation.metadata.inputFolder.files.dataset,
        },
      },
    };

    if (this.state.serverType === 'Traditional') {
      payload.cluster = ClusterPayloads.tradClusterPayload(this.state[this.state.serverType].profile);
    } else if (this.state.serverType === 'EC2') {
      if (!this.state.EC2.cluster) {
        payload.cluster = ClusterPayloads.ec2ClusterPayload(
          this.state.EC2.name,
          this.state.EC2.machine,
          this.state.EC2.clusterSize,
          this.state.EC2.profile
        );
      } else {
        payload.cluster = { _id: this.state.EC2.cluster };
      }
    } else {
      console.log('unrecognized serverType: ', this.state.serverType);
      return;
    }

    const simStepUpdate = {
      id: this.props.simulation._id,
      name: this.props.simulation.name,
      step: 'Visualization',
      data: {
        view: 'run',
        metadata: {
          sessionId: sessionKey,
        },
      },
    };
    const location = {
      pathname: this.props.location.pathname,
      query: Object.assign({}, this.props.location.query, { view: 'run' }),
      state: this.props.location.state,
    };

    this.props.onRun(this.props.taskFlowName, this.props.primaryJob, payload, simStepUpdate, location);
  },

  formAction(action) {
    this[action]();
  },

  updateServerType(e) {
    this.setState({ serverType: e.target.value });
  },

  render() {
    var actions = [{ name: 'startVisualization', label: 'Start Visualization', icon: '' }],
      serverProfiles = { EC2: this.state.EC2, Traditional: this.state.Traditional, OpenStack: this.state.OpenStack };

    return (

        <RunClusterFrom serverType={this.state.serverType} serverTypeChange={this.updateServerType}
          profiles={serverProfiles} dataChange={this.dataChange}
        />
        <ButtonBar
          visible={this.state[this.state.serverType].profile !== ''}
          onAction={this.formAction}
          actions={actions}
          error={this.state.error}
        />

);
  },
});

// Binding --------------------------------------------------------------------
/* eslint-disable arrow-body-style */

export default connect(
  (state, props) => {
    return {
      error: get(state, 'network.error.create_taskflow.resp.data.message')
        || get(state, 'network.error.start_taskflow.resp.data.message'),
      ec2Clusters: state.preferences.aws.mapById,
      tradClusters: state.preferences.clusters.mapById,
    };
  },
  () => {
    return {
      onRun: (taskflowName, primaryJob, payload, simulationStep, location) =>
        dispatch(Actions.createTaskflow(taskflowName, primaryJob, payload, simulationStep, location)),
    };
  }
)(VisualizationStart);

<commit_msg>Add clusterFilter to ParaViewWeb workflow<commit_after>import React                   from 'react';
import defaultServerParameters from '../../../../../../panels/run/defaults';
import RunClusterFrom          from '../../../../../../panels/run';
import ButtonBar               from '../../../../../../panels/ButtonBar';
import ClusterPayloads         from '../../../../../../utils/ClusterPayload';

import { connect }  from 'react-redux';
import get          from 'mout/src/object/get';
import { dispatch } from '../../../../../../redux';
import * as Actions from '../../../../../../redux/actions/taskflows';

const VisualizationStart = React.createClass({
  displayName: 'pvw/start-visualization',
  propTypes: {
    location: React.PropTypes.object,
    project: React.PropTypes.object,
    simulation: React.PropTypes.object,
    step: React.PropTypes.string,
    taskFlowName: React.PropTypes.string,
    primaryJob: React.PropTypes.string,
    view: React.PropTypes.string,

    error: React.PropTypes.string,
    tradClusters: React.PropTypes.object,
    ec2Clusters: React.PropTypes.object,
    onRun: React.PropTypes.func,
  },

  getInitialState() {
    return {
      serverType: 'Traditional',
      EC2: defaultServerParameters.EC2,
      Traditional: defaultServerParameters.Traditional,
      OpenStack: defaultServerParameters.OpenStack,
      error: null,
    };
  },

  dataChange(key, value, which) {
    var profile = this.state[which];
    profile[key] = value;
    this.setState({ [which]: profile });
  },

  startVisualization() {
    const sessionKey = btoa(new Float64Array(3).map(Math.random)).substring(0, 96);
    const payload = {
      sessionKey,
      input: {
        file: {
          id: this.props.simulation.metadata.inputFolder.files.dataset,
        },
      },
    };

    if (this.state.serverType === 'Traditional') {
      payload.cluster = ClusterPayloads.tradClusterPayload(this.state[this.state.serverType].profile);
    } else if (this.state.serverType === 'EC2') {
      if (!this.state.EC2.cluster) {
        payload.cluster = ClusterPayloads.ec2ClusterPayload(
          this.state.EC2.name,
          this.state.EC2.machine,
          this.state.EC2.clusterSize,
          this.state.EC2.profile
        );
      } else {
        payload.cluster = { _id: this.state.EC2.cluster };
      }
    } else {
      console.log('unrecognized serverType: ', this.state.serverType);
      return;
    }

    const simStepUpdate = {
      id: this.props.simulation._id,
      name: this.props.simulation.name,
      step: 'Visualization',
      data: {
        view: 'run',
        metadata: {
          sessionId: sessionKey,
        },
      },
    };
    const location = {
      pathname: this.props.location.pathname,
      query: Object.assign({}, this.props.location.query, { view: 'run' }),
      state: this.props.location.state,
    };

    this.props.onRun(this.props.taskFlowName, this.props.primaryJob, payload, simStepUpdate, location);
  },

  formAction(action) {
    this[action]();
  },

  updateServerType(e) {
    this.setState({ serverType: e.target.value });
  },

  clusterFilter(cluster) {
    return 'config' in cluster && 'paraview' in cluster.config &&
      'installDir' in cluster.config.paraview && cluster.config.paraview.installDir;
  },

  render() {
    var actions = [{ name: 'startVisualization', label: 'Start Visualization', icon: '' }],
      serverProfiles = { EC2: this.state.EC2, Traditional: this.state.Traditional, OpenStack: this.state.OpenStack };

    return (

        <RunClusterFrom serverType={this.state.serverType} serverTypeChange={this.updateServerType}
          profiles={serverProfiles} dataChange={this.dataChange} clusterFilter={this.clusterFilter}
        />
        <ButtonBar
          visible={this.state[this.state.serverType].profile !== ''}
          onAction={this.formAction}
          actions={actions}
          error={this.state.error}
        />

);
  },
});

// Binding --------------------------------------------------------------------
/* eslint-disable arrow-body-style */

export default connect(
  (state, props) => {
    return {
      error: get(state, 'network.error.create_taskflow.resp.data.message')
        || get(state, 'network.error.start_taskflow.resp.data.message'),
      ec2Clusters: state.preferences.aws.mapById,
      tradClusters: state.preferences.clusters.mapById,
    };
  },
  () => {
    return {
      onRun: (taskflowName, primaryJob, payload, simulationStep, location) =>
        dispatch(Actions.createTaskflow(taskflowName, primaryJob, payload, simulationStep, location)),
    };
  }
)(VisualizationStart);

<|endoftext|>


<commit_before>window.locale = { _current: 'en' };

locale.current = function(_) {
    if (!arguments.length) return locale._current;
    if (locale[_] !== undefined) locale._current = _;
    else if (locale[_.split('-')[0]]) locale._current = _.split('-')[0];
    return locale;
};

function t(s, o, loc) {
    loc = loc || locale._current;

    var path = s.split(".").reverse(),
        rep = locale[loc];

    while (rep !== undefined && path.length) rep = rep[path.pop()];

    if (rep !== undefined) {
        if (o) for (var k in o) rep = rep.replace('{' + k + '}', o[k]);
        return rep;
    } else {
        function missing() {
            var missing = 'Missing ' + loc + ' translation: ' + s;
            if (typeof console !== "undefined") console.error(missing);
            return missing;
        }

        if (loc !== 'en') {
            missing();
            return t(s, o, 'en');
        }

        if (o && 'default' in o) {
            return o['default'];
        }

        return missing();
    }
}
<commit_msg>Don't console.error missing translations (fixes #2020)<commit_after>window.locale = { _current: 'en' };

locale.current = function(_) {
    if (!arguments.length) return locale._current;
    if (locale[_] !== undefined) locale._current = _;
    else if (locale[_.split('-')[0]]) locale._current = _.split('-')[0];
    return locale;
};

function t(s, o, loc) {
    loc = loc || locale._current;

    var path = s.split(".").reverse(),
        rep = locale[loc];

    while (rep !== undefined && path.length) rep = rep[path.pop()];

    if (rep !== undefined) {
        if (o) for (var k in o) rep = rep.replace('{' + k + '}', o[k]);
        return rep;
    }

    if (loc !== 'en') {
        return t(s, o, 'en');
    }

    if (o && 'default' in o) {
        return o['default'];
    }

    var missing = 'Missing ' + loc + ' translation: ' + s;
    if (typeof console !== "undefined") console.error(missing);

    return missing;
}
<|endoftext|>


<commit_before>/**
 * WordFilter.js
 *
 * Copyright, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class parses word HTML into proper TinyMCE markup.
 *
 * @class tinymce.pasteplugin.Quirks
 * @private
 */
define("tinymce/pasteplugin/WordFilter", [
	"tinymce/util/Tools",
	"tinymce/html/DomParser",
	"tinymce/html/Schema",
	"tinymce/html/Serializer",
	"tinymce/html/Node"
], function(Tools, DomParser, Schema, Serializer, Node) {
	function isWordContent(content) {
		return (/class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i).test(content);
	}

	function WordFilter(editor) {
		var each = Tools.each, settings = editor.settings;

		editor.on('PastePreProcess', function(e) {
			var content = e.content, retainStyleProperties, validStyles;

			retainStyleProperties = settings.paste_retain_style_properties;
			if (retainStyleProperties) {
				validStyles = Tools.makeMap(retainStyleProperties);
			}

			function process(items) {
				each(items, function(v) {
					if (v.constructor == RegExp) {
						content = content.replace(v, '');
					} else {
						content = content.replace(v[0], v[1]);
					}
				});
			}

			/**
			 * Converts fake bullet and numbered lists to real semantic OL/UL.
			 *
			 * @param {tinymce.html.Node} node Root node to convert children of.
			 */
			function convertFakeListsToProperLists(node) {
				var currentListNode, prevListNode, lastLevel = 1;

				function convertParagraphToLi(paragraphNode, listStartTextNode, listName, start) {
					var level = paragraphNode._listLevel || lastLevel;

					// Handle list nesting
					if (level != lastLevel) {
						if (level < lastLevel) {
							// Move to parent list
							if (currentListNode) {
								currentListNode = currentListNode.parent.parent;
							}
						} else {
							// Create new list
							prevListNode = currentListNode;
							currentListNode = null;
						}
					}

					if (!currentListNode || currentListNode.name != listName) {
						prevListNode = prevListNode || currentListNode;
						currentListNode = new Node(listName, 1);

						if (start > 1) {
							currentListNode.attr('start', '' + start);
						}

						paragraphNode.wrap(currentListNode);
					} else {
						currentListNode.append(paragraphNode);
					}

					paragraphNode.name = 'li';
					listStartTextNode.value = '';

					var nextNode = listStartTextNode.next;
					if (nextNode && nextNode.type == 3) {
						nextNode.value = nextNode.value.replace(/^\u00a0+/, '');
					}

					// Append list to previous list if it exists
					if (level > lastLevel && prevListNode) {
						prevListNode.lastChild.append(currentListNode);
					}

					lastLevel = level;
				}

				var paragraphs = node.getAll('p');

				for (var i = 0; i < paragraphs.length; i++) {
					node = paragraphs[i];

					if (node.name == 'p' && node.firstChild) {
						// Find first text node in paragraph
						var nodeText = '';
						var listStartTextNode = node.firstChild;

						while (listStartTextNode) {
							nodeText = listStartTextNode.value;
							if (nodeText) {
								break;
							}

							listStartTextNode = listStartTextNode.firstChild;
						}

						// Detect unordered lists look for bullets
						if (/^\s*[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*$/.test(nodeText)) {
							convertParagraphToLi(node, listStartTextNode, 'ul');
							continue;
						}

						// Detect ordered lists 1., a. or ixv.
						if (/^\s*\w+\.$/.test(nodeText)) {
							// Parse OL start number
							var matches = /([0-9])\./.exec(nodeText);
							var start = 1;
							if (matches) {
								start = parseInt(matches[1], 10);
							}

							convertParagraphToLi(node, listStartTextNode, 'ol', start);
							continue;
						}

						currentListNode = null;
					}
				}
			}

			function filterStyles(node, styleValue) {
				// Parse out list indent level for lists
				if (node.name === 'p') {
					var matches = /mso-list:\w+ \w+([0-9]+)/.exec(styleValue);

					if (matches) {
						node._listLevel = parseInt(matches[1], 10);
					}
				}

				if (editor.getParam("paste_retain_style_properties", "none")) {
					var outputStyle = "";

					Tools.each(editor.dom.parseStyle(styleValue), function(value, name) {
						// Convert various MS styles to W3C styles
						switch (name) {
							case "horiz-align":
								name = "text-align";
								return;

							case "vert-align":
								name = "vertical-align";
								return;

							case "font-color":
							case "mso-foreground":
								name = "color";
								return;

							case "mso-background":
							case "mso-highlight":
								name = "background";
								break;
						}

						// Output only valid styles
						if (retainStyleProperties == "all" || (validStyles && validStyles[name])) {
							outputStyle += name + ':' + value + ';';
						}
					});

					if (outputStyle) {
						return outputStyle;
					}
				}

				return null;
			}

			if (settings.paste_enable_default_filters === false) {
				return;
			}

			// Detect is the contents is Word junk HTML
			if (isWordContent(e.content)) {
				e.wordContent = true; // Mark it for other processors

				// Remove basic Word junk
				process([
					// Word comments like conditional comments etc
					//gi,

					// Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
					// MS Office namespaced tags, and a few other tags
					/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,

					// Convert <s> into  for line-though
					[/<(\/?)s>/gi, "<$1strike>"],

					// Replace nsbp entites to char since it's easier to handle
					[/ /gi, "\u00a0"],

					// Convert ___ to string of alternating
					// breaking/non-breaking spaces of same length
					[/([\s\u00a0]*)<\/span>/gi,
						function(str, spaces) {
							return (spaces.length > 0) ?
								spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : "";
						}
					]
				]);

				var validElements = settings.paste_word_valid_elements;
				if (!validElements) {
					validElements = '@[style],-strong/b,-em/i,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' +
						'-table,-tr,-td[colspan|rowspan],-th,-thead,-tfoot,-tbody,-a[!href],sub,sup,strike,br';
				}

				// Setup strict schema
				var schema = new Schema({
					valid_elements: validElements
				});

				// Parse HTML into DOM structure
				var domParser = new DomParser({}, schema);

				// Filte element style attributes
				domParser.addAttributeFilter('style', function(nodes) {
					var i = nodes.length, node;

					while (i--) {
						node = nodes[i];
						node.attr('style', filterStyles(node, node.attr('style')));

						// Remove pointess spans
						if (node.name == 'span' && !node.attributes.length) {
							node.unwrap();
						}
					}
				});

				// Parse into DOM structure
				var rootNode = domParser.parse(content);

				// Process DOM
				convertFakeListsToProperLists(rootNode);

				// Serialize DOM back to HTML
				e.content = new Serializer({}, schema).serialize(rootNode);
			}
		});
	}

	WordFilter.isWordContent = isWordContent;

	return WordFilter;
});<commit_msg>Fixed typo in unordered char list regexp<commit_after>/**
 * WordFilter.js
 *
 * Copyright, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class parses word HTML into proper TinyMCE markup.
 *
 * @class tinymce.pasteplugin.Quirks
 * @private
 */
define("tinymce/pasteplugin/WordFilter", [
	"tinymce/util/Tools",
	"tinymce/html/DomParser",
	"tinymce/html/Schema",
	"tinymce/html/Serializer",
	"tinymce/html/Node"
], function(Tools, DomParser, Schema, Serializer, Node) {
	function isWordContent(content) {
		return (/class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i).test(content);
	}

	function WordFilter(editor) {
		var each = Tools.each, settings = editor.settings;

		editor.on('PastePreProcess', function(e) {
			var content = e.content, retainStyleProperties, validStyles;

			retainStyleProperties = settings.paste_retain_style_properties;
			if (retainStyleProperties) {
				validStyles = Tools.makeMap(retainStyleProperties);
			}

			function process(items) {
				each(items, function(v) {
					if (v.constructor == RegExp) {
						content = content.replace(v, '');
					} else {
						content = content.replace(v[0], v[1]);
					}
				});
			}

			/**
			 * Converts fake bullet and numbered lists to real semantic OL/UL.
			 *
			 * @param {tinymce.html.Node} node Root node to convert children of.
			 */
			function convertFakeListsToProperLists(node) {
				var currentListNode, prevListNode, lastLevel = 1;

				function convertParagraphToLi(paragraphNode, listStartTextNode, listName, start) {
					var level = paragraphNode._listLevel || lastLevel;

					// Handle list nesting
					if (level != lastLevel) {
						if (level < lastLevel) {
							// Move to parent list
							if (currentListNode) {
								currentListNode = currentListNode.parent.parent;
							}
						} else {
							// Create new list
							prevListNode = currentListNode;
							currentListNode = null;
						}
					}

					if (!currentListNode || currentListNode.name != listName) {
						prevListNode = prevListNode || currentListNode;
						currentListNode = new Node(listName, 1);

						if (start > 1) {
							currentListNode.attr('start', '' + start);
						}

						paragraphNode.wrap(currentListNode);
					} else {
						currentListNode.append(paragraphNode);
					}

					paragraphNode.name = 'li';
					listStartTextNode.value = '';

					var nextNode = listStartTextNode.next;
					if (nextNode && nextNode.type == 3) {
						nextNode.value = nextNode.value.replace(/^\u00a0+/, '');
					}

					// Append list to previous list if it exists
					if (level > lastLevel && prevListNode) {
						prevListNode.lastChild.append(currentListNode);
					}

					lastLevel = level;
				}

				var paragraphs = node.getAll('p');

				for (var i = 0; i < paragraphs.length; i++) {
					node = paragraphs[i];

					if (node.name == 'p' && node.firstChild) {
						// Find first text node in paragraph
						var nodeText = '';
						var listStartTextNode = node.firstChild;

						while (listStartTextNode) {
							nodeText = listStartTextNode.value;
							if (nodeText) {
								break;
							}

							listStartTextNode = listStartTextNode.firstChild;
						}

						// Detect unordered lists look for bullets
						if (/^\s*[\u2022\u00b7\u00a7\u00d8\u25CF]\s*$/.test(nodeText)) {
							convertParagraphToLi(node, listStartTextNode, 'ul');
							continue;
						}

						// Detect ordered lists 1., a. or ixv.
						if (/^\s*\w+\.$/.test(nodeText)) {
							// Parse OL start number
							var matches = /([0-9])\./.exec(nodeText);
							var start = 1;
							if (matches) {
								start = parseInt(matches[1], 10);
							}

							convertParagraphToLi(node, listStartTextNode, 'ol', start);
							continue;
						}

						currentListNode = null;
					}
				}
			}

			function filterStyles(node, styleValue) {
				// Parse out list indent level for lists
				if (node.name === 'p') {
					var matches = /mso-list:\w+ \w+([0-9]+)/.exec(styleValue);

					if (matches) {
						node._listLevel = parseInt(matches[1], 10);
					}
				}

				if (editor.getParam("paste_retain_style_properties", "none")) {
					var outputStyle = "";

					Tools.each(editor.dom.parseStyle(styleValue), function(value, name) {
						// Convert various MS styles to W3C styles
						switch (name) {
							case "horiz-align":
								name = "text-align";
								return;

							case "vert-align":
								name = "vertical-align";
								return;

							case "font-color":
							case "mso-foreground":
								name = "color";
								return;

							case "mso-background":
							case "mso-highlight":
								name = "background";
								break;
						}

						// Output only valid styles
						if (retainStyleProperties == "all" || (validStyles && validStyles[name])) {
							outputStyle += name + ':' + value + ';';
						}
					});

					if (outputStyle) {
						return outputStyle;
					}
				}

				return null;
			}

			if (settings.paste_enable_default_filters === false) {
				return;
			}

			// Detect is the contents is Word junk HTML
			if (isWordContent(e.content)) {
				e.wordContent = true; // Mark it for other processors

				// Remove basic Word junk
				process([
					// Word comments like conditional comments etc
					//gi,

					// Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
					// MS Office namespaced tags, and a few other tags
					/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,

					// Convert <s> into  for line-though
					[/<(\/?)s>/gi, "<$1strike>"],

					// Replace nsbp entites to char since it's easier to handle
					[/ /gi, "\u00a0"],

					// Convert ___ to string of alternating
					// breaking/non-breaking spaces of same length
					[/([\s\u00a0]*)<\/span>/gi,
						function(str, spaces) {
							return (spaces.length > 0) ?
								spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : "";
						}
					]
				]);

				var validElements = settings.paste_word_valid_elements;
				if (!validElements) {
					validElements = '@[style],-strong/b,-em/i,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' +
						'-table,-tr,-td[colspan|rowspan],-th,-thead,-tfoot,-tbody,-a[!href],sub,sup,strike,br';
				}

				// Setup strict schema
				var schema = new Schema({
					valid_elements: validElements
				});

				// Parse HTML into DOM structure
				var domParser = new DomParser({}, schema);

				// Filte element style attributes
				domParser.addAttributeFilter('style', function(nodes) {
					var i = nodes.length, node;

					while (i--) {
						node = nodes[i];
						node.attr('style', filterStyles(node, node.attr('style')));

						// Remove pointess spans
						if (node.name == 'span' && !node.attributes.length) {
							node.unwrap();
						}
					}
				});

				// Parse into DOM structure
				var rootNode = domParser.parse(content);

				// Process DOM
				convertFakeListsToProperLists(rootNode);

				// Serialize DOM back to HTML
				e.content = new Serializer({}, schema).serialize(rootNode);
			}
		});
	}

	WordFilter.isWordContent = isWordContent;

	return WordFilter;
});<|endoftext|>


<commit_before>function LevelRoundState() {}

var playerLives, playerBall, smallerEnemies, largerEnemies, enemiesCollisionGroup, playerCollisionGroup, gameOverScreen;

var playerScale = 0.1;
var gamePlayed = false;
var winScreenDisplayed;

//accelerometer controls

var ax = 0, ay = 0,
vx = 0, vy = 0;

window.ondevicemotion = function(e) {

  ax = e.accelerationIncludingGravity.x * inputSensitivity; //acceleration along x axis
  ay = e.accelerationIncludingGravity.y * inputSensitivity; //acceleration along y axis

  //TODO: make tilt increase logarithimacally

  vx = vx + ax;
  vy = vy + ay;

};

function createPlayer() {
    playerBall = game.add.sprite(centerx, centery, 'player');

    if (!gamePlayed) {
        playerBall.scale.setTo(1, 1);

        gamePlayed = true;
        var getReadyScreen = game.add.sprite(centerx, centery + 50, 'getready');
        getReadyScreen.scale.setTo(0.5,0.5);
        var getReadyAnimation = game.add.tween(getReadyScreen);
        getReadyAnimation.to({alpha: 0}, 500, Phaser.Easing.Linear.None, true, 0, 7, false);
    }

    else {
        playerBall.scale.setTo(playerScale, playerScale);
    }

    game.physics.p2.enable(playerBall);

    // //adding invicibility to the ball for 4 seconds
    playerBall.invincible = true;

    var invincibleAnimation = game.add.tween(playerBall);
    invincibleAnimation.to({alpha: 0}, 500, Phaser.Easing.Linear.None, true, 0, 7, false).to({alpha: 1}, 500);

    game.time.events.add(4000, (function() {
        playerBall.invincible = false;
    }), this);

    //setting the collision group for the player
    playerBall.body.setCollisionGroup(playerCollisionGroup);
    playerBall.body.collides(enemiesCollisionGroup, hitEnemy, this);
}

function createSmallerEnemies() {
    for (var x = 1; x < 18; x++) {
        var enemySpriteColors = ['blue_ball', 'red_ball', 'green_ball'];
        var enemy = smallerEnemies.create(game.world.randomX, game.world.randomY, game.rnd.pick(enemySpriteColors));
        var smallerEnemy = game.rnd.realInRange(0.015, playerScale);

        //making enemies smaller than current player size
        enemy.scale.setTo(smallerEnemy, smallerEnemy);
        game.physics.p2.enable(enemy, false);

        //initiating enemy velocity.

        var randv = game.rnd.realInRange(-300, 300);
        var randv2 = game.rnd.realInRange(-300, 300);
        enemy.body.velocity.x = randv;
        enemy.body.velocity.y = randv2;

        //setting the collision group and having it collide with the player.
        enemy.body.setCollisionGroup(enemiesCollisionGroup);
        enemy.body.collides([enemiesCollisionGroup, playerCollisionGroup]);
    }
}

function createLargerEnemies() {
    for (var x = 1; x < 4; x++) {
        var enemy = largerEnemies.create(game.world.randomX, game.world.randomY, 'ball');
        var largerEnemy = game.rnd.realInRange(playerScale, playerScale * 1.5);
        enemy.scale.setTo(largerEnemy, largerEnemy);
        game.physics.p2.enable(enemy, false);

         //initiating enemy velocity.

        var randv = game.rnd.realInRange(-300, 300);
        var randv2 = game.rnd.realInRange(-300, 300);

        enemy.body.velocity.x = randv;
        enemy.body.velocity.y = randv2;

        //setting the collision group and having it collide with the player.
        enemy.body.setCollisionGroup(enemiesCollisionGroup);
        enemy.body.collides([enemiesCollisionGroup, playerCollisionGroup]);

    }
}

function moveLargerTowardPlayer (enemy) {
    accelerateToObject(enemy, playerBall, playerDifficulty * 75);
}

function moveSmallerTowardPlayer (enemy) {
    accelerateToObject(enemy, playerBall, 50);
}

function accelerateToObject(obj1, obj2, speed) {
    if (typeof speed === 'undefined') { speed = 60; }
    var angle = Math.atan2(obj2.y - obj1.y, obj2.x - obj1.x);
    obj1.body.rotation = angle + game.math.degToRad(90);  // correct angle of angry balls (depends on the sprite used)
    obj1.body.force.x = Math.cos(angle) * speed;    // accelerateToObject
    obj1.body.force.y = Math.sin(angle) * speed;
}

function restartGame() {
  game.state.start('level_round');
}

function levelUp(playerBall) {
  var newSize = playerBall.sprite.scale.x * 1.022;
  playerBall.sprite.scale.x = newSize;
  playerBall.sprite.scale.y = newSize;
  playerScale = newSize;
  game.add.tween(playerBall.sprite.scale).to({x:newSize * 1.2, y:newSize * 1.2}, 25,Phaser.Easing.Linear.None, true, 0, 0, true);
}

function hitEnemy(playerBall, enemy) {
    //  body1 is the playerBall (as it's the body that owns the callback)
    //  body2 is the body it impacted with, the enemy balls
    //  As body2 is a Phaser.Physics.P2.Body object, you access its own (the sprite) via the sprite property:

    if (playerBall.sprite.invincible) {
        return;
    }

    else if (enemy.sprite.scale.x > playerBall.sprite.scale.x) {

        if (playerLives.countLiving() !== 0) {
            game.add.tween(playerBall.sprite.scale).to({ x: 0, y: 0}, 100, Phaser.Easing.Quadratic.InOut, true, 0).onComplete.add(function() {
                playerBall.sprite.kill();
                    if (!playerBall.sprite.hasCollided) {
                        playerBall.sprite.hasCollided = true;
                        playerLives.next().kill();

                        if (playerLives.countDead() === 1) {
                            var respawnMessage = game.add.sprite(centerx, centery + 50, 'respawn');
                            respawnMessage.scale.setTo(0.25,0.25);
                            var respawnMessageAnimation = game.add.tween(respawnMessage);
                            respawnMessageAnimation.to({alpha: 0}, 500, Phaser.Easing.Linear.None, true, 0, 7, false);
                        }

                        game.time.events.add(2000, (function() {
                            createPlayer();
                        }), this);
                    }
            }, this);
        }

        if (playerLives.countLiving() === 0) {
            if (!playerBall.sprite.hasCollided) {
                playerBall.sprite.hasCollided = true;
                game.add.tween(playerBall.sprite.scale).to({ x: 0, y: 0}, 100, Phaser.Easing.Quadratic.InOut, true, 0);
                var gameOverScreen = game.add.sprite(centerx, centery, 'gameogre');
                gameOverScreen.anchor.setTo(0.5,0.5);
                gameOverScreen.inputEnabled = true;
                gameOverScreen.events.onInputDown.add(restartGame, this);
                }
        }

      }

    else {
        game.add.tween(enemy.sprite.scale).to({ x: 0, y: 0}, 75, Phaser.Easing.Quadratic.InOut, true, 0).onComplete.add(function(){
        enemy.sprite.kill();
            if (!enemy.sprite.hasCollided) {
                levelUp(playerBall);
                enemy.sprite.hasCollided = true;
            }
        }, this);

    }

}

function createLives() {
    playerLives = game.add.group();
    var firstLifeIconX = game.width - 50;
    for (var i = 0; i < 2; i++) {
        var lifeIcons = playerLives.create(firstLifeIconX - (60 * i), 50, 'player');
        lifeIcons.scale.setTo(0.1,0.1);
        lifeIcons.anchor.setTo(0.5, 0.5);
        lifeIcons.alpha = 0.6;
    }

}

LevelRoundState.prototype = {

  preload: function() {
    // This function will be executed at the beginning

  },

  create: function() {

    // starting the P2JS system
    game.physics.startSystem(Phaser.Physics.P2JS);

    // starting collision events
    game.physics.p2.setImpactEvents(true);
    game.physics.p2.restitution = 0.95;

    //creating a collision group for player and enemies

    playerCollisionGroup = game.physics.p2.createCollisionGroup();

    enemiesCollisionGroup = game.physics.p2.createCollisionGroup();

    game.physics.p2.updateBoundsCollisionGroup();

    smallerEnemies = game.add.group();
    largerEnemies = game.add.group();

    //setting initial playerscale and winScreenDisplayed

    winScreenDisplayed = false;
    playerScale = 0.1;

    createPlayer();

    createLives();

    createSmallerEnemies();

    createLargerEnemies();

    //this could be a prefab
    backButton = game.add.sprite(100, game.height - 100, 'back_button');
    backButton.anchor.setTo(0.5,0.5);
    backButton.scale.setTo(0.2,0.2);
    backButton.alpha = 0;
    backButton.inputEnabled = true;
    backButtonAnimation = game.add.tween(backButton).to({alpha: 0.1}, 1000, Phaser.Easing.Quadratic.InOut, true, 2000);

    function backToDifficulty() {
      this.game.state.start('level_master');
    }

    backButton.events.onInputDown.add(backToDifficulty, this);

  },

  update: function() {
    // This function is called 60 times per second
    // It contains the game's logic

    ballMovement(playerBall, ax, ay, inputSensitivity, cursors);

    //larger enemies move faster towards you.

    largerEnemies.forEachAlive(moveLargerTowardPlayer, this);
    smallerEnemies.forEachAlive(moveSmallerTowardPlayer, this);

    //checking for the game win condition

    if (smallerEnemies.countLiving() === 0 && largerEnemies.countLiving() === 0) {
        if (!winScreenDisplayed) {
            winScreenDisplayed = true;
            var winScreen = game.add.sprite(centerx, centery, 'youwin');
            winScreen.scale.setTo(0.5,0.5);
            winScreen.anchor.setTo(0.5,0.5);
        }
    }

  }
};<commit_msg>added a delay to gamewin condition<commit_after>function LevelRoundState() {}

var playerLives, playerBall, smallerEnemies, largerEnemies, enemiesCollisionGroup, playerCollisionGroup, gameOverScreen;

var playerScale = 0.1;
var gamePlayed = false;
var winScreenDisplayed;

//accelerometer controls

var ax = 0, ay = 0,
vx = 0, vy = 0;

window.ondevicemotion = function(e) {

  ax = e.accelerationIncludingGravity.x * inputSensitivity; //acceleration along x axis
  ay = e.accelerationIncludingGravity.y * inputSensitivity; //acceleration along y axis

  //TODO: make tilt increase logarithimacally

  vx = vx + ax;
  vy = vy + ay;

};

function createPlayer() {
    playerBall = game.add.sprite(centerx, centery, 'player');

    if (!gamePlayed) {
        playerBall.scale.setTo(1, 1);

        var getReadyScreen = game.add.sprite(centerx, centery + 50, 'getready');
        getReadyScreen.scale.setTo(0.5,0.5);
        var getReadyAnimation = game.add.tween(getReadyScreen);
        getReadyAnimation.to({alpha: 0}, 500, Phaser.Easing.Linear.None, true, 0, 7, false);
        game.time.events.add(5000, (function() {
            gamePlayed = true;
        }), this);
    }

    else {
        playerBall.scale.setTo(playerScale, playerScale);
    }

    game.physics.p2.enable(playerBall);

    // //adding invicibility to the ball for 4 seconds
    playerBall.invincible = true;

    var invincibleAnimation = game.add.tween(playerBall);
    invincibleAnimation.to({alpha: 0}, 500, Phaser.Easing.Linear.None, true, 0, 7, false).to({alpha: 1}, 500);

    game.time.events.add(4000, (function() {
        playerBall.invincible = false;
    }), this);

    //setting the collision group for the player
    playerBall.body.setCollisionGroup(playerCollisionGroup);
    playerBall.body.collides(enemiesCollisionGroup, hitEnemy, this);
}

function createSmallerEnemies() {
    for (var x = 1; x < 18; x++) {
        var enemySpriteColors = ['blue_ball', 'red_ball', 'green_ball'];
        var enemy = smallerEnemies.create(game.world.randomX, game.world.randomY, game.rnd.pick(enemySpriteColors));
        var smallerEnemy = game.rnd.realInRange(0.015, playerScale);

        //making enemies smaller than current player size
        enemy.scale.setTo(smallerEnemy, smallerEnemy);
        game.physics.p2.enable(enemy, false);

        //initiating enemy velocity.

        var randv = game.rnd.realInRange(-300, 300);
        var randv2 = game.rnd.realInRange(-300, 300);
        enemy.body.velocity.x = randv;
        enemy.body.velocity.y = randv2;

        //setting the collision group and having it collide with the player.
        enemy.body.setCollisionGroup(enemiesCollisionGroup);
        enemy.body.collides([enemiesCollisionGroup, playerCollisionGroup]);
    }
}

function createLargerEnemies() {
    for (var x = 1; x < 4; x++) {
        var enemy = largerEnemies.create(game.world.randomX, game.world.randomY, 'ball');
        var largerEnemy = game.rnd.realInRange(playerScale, playerScale * 1.5);
        enemy.scale.setTo(largerEnemy, largerEnemy);
        game.physics.p2.enable(enemy, false);

         //initiating enemy velocity.

        var randv = game.rnd.realInRange(-300, 300);
        var randv2 = game.rnd.realInRange(-300, 300);

        enemy.body.velocity.x = randv;
        enemy.body.velocity.y = randv2;

        //setting the collision group and having it collide with the player.
        enemy.body.setCollisionGroup(enemiesCollisionGroup);
        enemy.body.collides([enemiesCollisionGroup, playerCollisionGroup]);

    }
}

function moveLargerTowardPlayer (enemy) {
    accelerateToObject(enemy, playerBall, playerDifficulty * 75);
}

function moveSmallerTowardPlayer (enemy) {
    accelerateToObject(enemy, playerBall, 50);
}

function accelerateToObject(obj1, obj2, speed) {
    if (typeof speed === 'undefined') { speed = 60; }
    var angle = Math.atan2(obj2.y - obj1.y, obj2.x - obj1.x);
    obj1.body.rotation = angle + game.math.degToRad(90);  // correct angle of angry balls (depends on the sprite used)
    obj1.body.force.x = Math.cos(angle) * speed;    // accelerateToObject
    obj1.body.force.y = Math.sin(angle) * speed;
}

function restartGame() {
  game.state.start('level_round');
}

function levelUp(playerBall) {
  var newSize = playerBall.sprite.scale.x * 1.022;
  playerBall.sprite.scale.x = newSize;
  playerBall.sprite.scale.y = newSize;
  playerScale = newSize;
  game.add.tween(playerBall.sprite.scale).to({x:newSize * 1.2, y:newSize * 1.2}, 25,Phaser.Easing.Linear.None, true, 0, 0, true);
}

function hitEnemy(playerBall, enemy) {
    //  body1 is the playerBall (as it's the body that owns the callback)
    //  body2 is the body it impacted with, the enemy balls
    //  As body2 is a Phaser.Physics.P2.Body object, you access its own (the sprite) via the sprite property:

    if (playerBall.sprite.invincible) {
        return;
    }

    else if (enemy.sprite.scale.x > playerBall.sprite.scale.x) {

        if (playerLives.countLiving() !== 0) {
            game.add.tween(playerBall.sprite.scale).to({ x: 0, y: 0}, 100, Phaser.Easing.Quadratic.InOut, true, 0).onComplete.add(function() {
                playerBall.sprite.kill();
                    if (!playerBall.sprite.hasCollided) {
                        playerBall.sprite.hasCollided = true;
                        playerLives.next().kill();

                        if (playerLives.countDead() === 1) {
                            var respawnMessage = game.add.sprite(centerx, centery + 50, 'respawn');
                            respawnMessage.scale.setTo(0.25,0.25);
                            var respawnMessageAnimation = game.add.tween(respawnMessage);
                            respawnMessageAnimation.to({alpha: 0}, 500, Phaser.Easing.Linear.None, true, 0, 7, false);
                        }

                        game.time.events.add(2000, (function() {
                            createPlayer();
                        }), this);
                    }
            }, this);
        }

        if (playerLives.countLiving() === 0) {
            if (!playerBall.sprite.hasCollided) {
                playerBall.sprite.hasCollided = true;
                game.add.tween(playerBall.sprite.scale).to({ x: 0, y: 0}, 100, Phaser.Easing.Quadratic.InOut, true, 0);
                var gameOverScreen = game.add.sprite(centerx, centery, 'gameogre');
                gameOverScreen.anchor.setTo(0.5,0.5);
                gameOverScreen.inputEnabled = true;
                gameOverScreen.events.onInputDown.add(restartGame, this);
                }
        }

      }

    else {
        game.add.tween(enemy.sprite.scale).to({ x: 0, y: 0}, 75, Phaser.Easing.Quadratic.InOut, true, 0).onComplete.add(function(){
        enemy.sprite.kill();
            if (!enemy.sprite.hasCollided) {
                levelUp(playerBall);
                enemy.sprite.hasCollided = true;
            }
        }, this);

    }

}

function createLives() {
    playerLives = game.add.group();
    var firstLifeIconX = game.width - 50;
    for (var i = 0; i < 2; i++) {
        var lifeIcons = playerLives.create(firstLifeIconX - (60 * i), 50, 'player');
        lifeIcons.scale.setTo(0.1,0.1);
        lifeIcons.anchor.setTo(0.5, 0.5);
        lifeIcons.alpha = 0.6;
    }

}

LevelRoundState.prototype = {

  preload: function() {
    // This function will be executed at the beginning

  },

  create: function() {

    // starting the P2JS system
    game.physics.startSystem(Phaser.Physics.P2JS);

    // starting collision events
    game.physics.p2.setImpactEvents(true);
    game.physics.p2.restitution = 0.95;

    //creating a collision group for player and enemies

    playerCollisionGroup = game.physics.p2.createCollisionGroup();

    enemiesCollisionGroup = game.physics.p2.createCollisionGroup();

    game.physics.p2.updateBoundsCollisionGroup();

    smallerEnemies = game.add.group();
    largerEnemies = game.add.group();

    //setting initial playerscale and winScreenDisplayed

    winScreenDisplayed = false;
    playerScale = 0.1;

    createPlayer();

    createLives();

    //adding a delay to creating enemies.

    game.time.events.add(4000, (function() {
        createSmallerEnemies();
        createLargerEnemies();

        this.update = function() {
                        // This function is called 60 times per second
            // It contains the game's logic

            ballMovement(playerBall, ax, ay, inputSensitivity, cursors);

            //larger enemies move faster towards you.

            largerEnemies.forEachAlive(moveLargerTowardPlayer, this);
            smallerEnemies.forEachAlive(moveSmallerTowardPlayer, this);

            //checking for the game win condition

            if (smallerEnemies.countLiving() === 0 && largerEnemies.countLiving() === 0) {
                if (!winScreenDisplayed) {
                    winScreenDisplayed = true;
                    var winScreen = game.add.sprite(centerx, centery, 'youwin');
                    winScreen.scale.setTo(0.5,0.5);
                    winScreen.anchor.setTo(0.5,0.5);
                }
            }
        };
    }), this);

    //this could be a prefab
    backButton = game.add.sprite(100, game.height - 100, 'back_button');
    backButton.anchor.setTo(0.5,0.5);
    backButton.scale.setTo(0.2,0.2);
    backButton.alpha = 0;
    backButton.inputEnabled = true;
    backButtonAnimation = game.add.tween(backButton).to({alpha: 0.1}, 1000, Phaser.Easing.Quadratic.InOut, true, 2000);

    function backToDifficulty() {
      this.game.state.start('level_master');
    }

    backButton.events.onInputDown.add(backToDifficulty, this);

  },

  update: function() {
    // This function is called 60 times per second
    // It contains the game's logic

    ballMovement(playerBall, ax, ay, inputSensitivity, cursors);

    //larger enemies move faster towards you.

    largerEnemies.forEachAlive(moveLargerTowardPlayer, this);
    smallerEnemies.forEachAlive(moveSmallerTowardPlayer, this);

    //checking for the game win condition

    if (smallerEnemies.countLiving() === 0 && largerEnemies.countLiving() === 0 && gamePlayed) {
        if (!winScreenDisplayed) {
            winScreenDisplayed = true;
            var winScreen = game.add.sprite(centerx, centery, 'youwin');
            winScreen.scale.setTo(0.5,0.5);
            winScreen.anchor.setTo(0.5,0.5);
        }
    }

  }
};<|endoftext|>


<commit_before>import omit from 'lodash/omit';

export default (
  log = (_, args, { app, req }, info, data) => {
    if (app.modules.hasModule('oors.logger')) {
      app.modules.get('oors.logger')[data.error ? 'error' : 'info'](data.message, {
        ...omit(data, ['message']),
        userId: req.user ? req.user._id : null,
        IP: req.ip,
      });
    } else {
      console.log(data);
    }
  },
) => message => resolver => async (_, args, ctx, info) => {
  let data;
  let result;
  let error;

  try {
    result = await resolver(_, args, ctx, info);
    data =
      typeof message === 'function'
        ? await message(_, args, ctx, info, { result })
        : {
            message,
            args,
            result,
          };
  } catch (err) {
    error = err;
    data =
      typeof message === 'function'
        ? await message(_, args, ctx, info, { error })
        : {
            message,
            args,
            error,
          };
  }

  if (data) {
    log(_, args, ctx, info, data);
  }

  if (error) {
    throw error;
  }

  return result;
};
<commit_msg>[oors-graphql] withLogger default message wil be resolver name<commit_after>import omit from 'lodash/omit';

export default (
  log = (_, args, { app, req }, info, data) => {
    if (app.modules.hasModule('oors.logger')) {
      app.modules.get('oors.logger')[data.error ? 'error' : 'info'](data.message, {
        ...omit(data, ['message']),
        userId: req.user ? req.user._id : null,
        IP: req.ip,
      });
    } else {
      console.log(data);
    }
  },
) => message => resolver => async (_, args, ctx, info) => {
  let data;
  let result;
  let error;

  try {
    result = await resolver(_, args, ctx, info);
    data =
      typeof message === 'function'
        ? await message(_, args, ctx, info, { result })
        : {
            message: message || info.fieldName,
            args,
            result,
          };
  } catch (err) {
    error = err;
    data =
      typeof message === 'function'
        ? await message(_, args, ctx, info, { error })
        : {
            message: message || info.fieldName,
            args,
            error,
          };
  }

  if (data) {
    log(_, args, ctx, info, data);
  }

  if (error) {
    throw error;
  }

  return result;
};
<|endoftext|>