var _typeof2=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};/*! * pixi.js - v4.3.2 * Compiled Mon, 09 Jan 2017 14:35:08 UTC * * pixi.js is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */(function(f){if((typeof exports==="undefined"?"undefined":_typeof2(exports))==="object"&&typeof module!=="undefined"){module.exports=f();}else if(typeof define==="function"&&define.amd){define([],f);}else{var g;if(typeof window!=="undefined"){g=window;}else if(typeof global!=="undefined"){g=global;}else if(typeof self!=="undefined"){g=self;}else{g=this;}g.PIXI=f();}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f;}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e);},l,l.exports,e,t,n,r);}return n[o].exports;}var i=typeof require=="function"&&require;for(var o=0;o0)-(v<0);};//Computes absolute value of integer exports.abs=function(v){var mask=v>>INT_BITS-1;return(v^mask)-mask;};//Computes minimum of integers x and y exports.min=function(x,y){return y^(x^y)&-(x0xFFFF)<<4;v>>>=r;shift=(v>0xFF)<<3;v>>>=shift;r|=shift;shift=(v>0xF)<<2;v>>>=shift;r|=shift;shift=(v>0x3)<<1;v>>>=shift;r|=shift;return r|v>>1;};//Computes log base 10 of v exports.log10=function(v){return v>=1000000000?9:v>=100000000?8:v>=10000000?7:v>=1000000?6:v>=100000?5:v>=10000?4:v>=1000?3:v>=100?2:v>=10?1:0;};//Counts number of bits exports.popCount=function(v){v=v-(v>>>1&0x55555555);v=(v&0x33333333)+(v>>>2&0x33333333);return(v+(v>>>4)&0xF0F0F0F)*0x1010101>>>24;};//Counts number of trailing zeros function countTrailingZeros(v){var c=32;v&=-v;if(v)c--;if(v&0x0000FFFF)c-=16;if(v&0x00FF00FF)c-=8;if(v&0x0F0F0F0F)c-=4;if(v&0x33333333)c-=2;if(v&0x55555555)c-=1;return c;}exports.countTrailingZeros=countTrailingZeros;//Rounds to next power of 2 exports.nextPow2=function(v){v+=v===0;--v;v|=v>>>1;v|=v>>>2;v|=v>>>4;v|=v>>>8;v|=v>>>16;return v+1;};//Rounds down to previous power of 2 exports.prevPow2=function(v){v|=v>>>1;v|=v>>>2;v|=v>>>4;v|=v>>>8;v|=v>>>16;return v-(v>>>1);};//Computes parity of word exports.parity=function(v){v^=v>>>16;v^=v>>>8;v^=v>>>4;v&=0xf;return 0x6996>>>v&1;};var REVERSE_TABLE=new Array(256);(function(tab){for(var i=0;i<256;++i){var v=i,r=i,s=7;for(v>>>=1;v;v>>>=1){r<<=1;r|=v&1;--s;}tab[i]=r<>>8&0xff]<<16|REVERSE_TABLE[v>>>16&0xff]<<8|REVERSE_TABLE[v>>>24&0xff];};//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes exports.interleave2=function(x,y){x&=0xFFFF;x=(x|x<<8)&0x00FF00FF;x=(x|x<<4)&0x0F0F0F0F;x=(x|x<<2)&0x33333333;x=(x|x<<1)&0x55555555;y&=0xFFFF;y=(y|y<<8)&0x00FF00FF;y=(y|y<<4)&0x0F0F0F0F;y=(y|y<<2)&0x33333333;y=(y|y<<1)&0x55555555;return x|y<<1;};//Extracts the nth interleaved component exports.deinterleave2=function(v,n){v=v>>>n&0x55555555;v=(v|v>>>1)&0x33333333;v=(v|v>>>2)&0x0F0F0F0F;v=(v|v>>>4)&0x00FF00FF;v=(v|v>>>16)&0x000FFFF;return v<<16>>16;};//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes exports.interleave3=function(x,y,z){x&=0x3FF;x=(x|x<<16)&4278190335;x=(x|x<<8)&251719695;x=(x|x<<4)&3272356035;x=(x|x<<2)&1227133513;y&=0x3FF;y=(y|y<<16)&4278190335;y=(y|y<<8)&251719695;y=(y|y<<4)&3272356035;y=(y|y<<2)&1227133513;x|=y<<1;z&=0x3FF;z=(z|z<<16)&4278190335;z=(z|z<<8)&251719695;z=(z|z<<4)&3272356035;z=(z|z<<2)&1227133513;return x|z<<2;};//Extracts nth interleaved component of a 3-tuple exports.deinterleave3=function(v,n){v=v>>>n&1227133513;v=(v|v>>>2)&3272356035;v=(v|v>>>4)&251719695;v=(v|v>>>8)&4278190335;v=(v|v>>>16)&0x3FF;return v<<22>>22;};//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) exports.nextCombination=function(v){var t=v|v-1;return t+1|(~t&-~t)-1>>>countTrailingZeros(v)+1;};},{}],2:[function(require,module,exports){'use strict';module.exports=earcut;function earcut(data,holeIndices,dim){dim=dim||2;var hasHoles=holeIndices&&holeIndices.length,outerLen=hasHoles?holeIndices[0]*dim:data.length,outerNode=linkedList(data,0,outerLen,dim,true),triangles=[];if(!outerNode)return triangles;var minX,minY,maxX,maxY,x,y,size;if(hasHoles)outerNode=eliminateHoles(data,holeIndices,outerNode,dim);// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox if(data.length>80*dim){minX=maxX=data[0];minY=maxY=data[1];for(var i=dim;imaxX)maxX=x;if(y>maxY)maxY=y;}// minX, minY and size are later used to transform coords into integers for z-order calculation size=Math.max(maxX-minX,maxY-minY);}earcutLinked(outerNode,triangles,dim,minX,minY,size);return triangles;}// create a circular doubly linked list from polygon points in the specified winding order function linkedList(data,start,end,dim,clockwise){var i,last;if(clockwise===signedArea(data,start,end,dim)>0){for(i=start;i=start;i-=dim){last=insertNode(i,data[i],data[i+1],last);}}if(last&&equals(last,last.next)){removeNode(last);last=last.next;}return last;}// eliminate colinear or duplicate points function filterPoints(start,end){if(!start)return start;if(!end)end=start;var p=start,again;do{again=false;if(!p.steiner&&(equals(p,p.next)||area(p.prev,p,p.next)===0)){removeNode(p);p=end=p.prev;if(p===p.next)return null;again=true;}else{p=p.next;}}while(again||p!==end);return end;}// main ear slicing loop which triangulates a polygon (given as a linked list) function earcutLinked(ear,triangles,dim,minX,minY,size,pass){if(!ear)return;// interlink polygon nodes in z-order if(!pass&&size)indexCurve(ear,minX,minY,size);var stop=ear,prev,next;// iterate through ears, slicing them one by one while(ear.prev!==ear.next){prev=ear.prev;next=ear.next;if(size?isEarHashed(ear,minX,minY,size):isEar(ear)){// cut off the triangle triangles.push(prev.i/dim);triangles.push(ear.i/dim);triangles.push(next.i/dim);removeNode(ear);// skipping the next vertice leads to less sliver triangles ear=next.next;stop=next.next;continue;}ear=next;// if we looped through the whole remaining polygon and can't find any more ears if(ear===stop){// try filtering points and slicing again if(!pass){earcutLinked(filterPoints(ear),triangles,dim,minX,minY,size,1);// if this didn't work, try curing all small self-intersections locally }else if(pass===1){ear=cureLocalIntersections(ear,triangles,dim);earcutLinked(ear,triangles,dim,minX,minY,size,2);// as a last resort, try splitting the remaining polygon into two }else if(pass===2){splitEarcut(ear,triangles,dim,minX,minY,size);}break;}}}// check whether a polygon node forms a valid ear with adjacent nodes function isEar(ear){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;// reflex, can't be an ear // now make sure we don't have other points inside the potential ear var p=ear.next.next;while(p!==ear.prev){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.next;}return true;}function isEarHashed(ear,minX,minY,size){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;// reflex, can't be an ear // triangle bbox; min & max are calculated like this for speed var minTX=a.xb.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y;// z-order range for the current triangle bbox; var minZ=zOrder(minTX,minTY,minX,minY,size),maxZ=zOrder(maxTX,maxTY,minX,minY,size);// first look for points inside the triangle in increasing z-order var p=ear.nextZ;while(p&&p.z<=maxZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.nextZ;}// then look for points in decreasing z-order p=ear.prevZ;while(p&&p.z>=minZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;}return true;}// go through all polygon nodes and cure small local self-intersections function cureLocalIntersections(start,triangles,dim){var p=start;do{var a=p.prev,b=p.next.next;if(!equals(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)){triangles.push(a.i/dim);triangles.push(p.i/dim);triangles.push(b.i/dim);// remove two nodes involved removeNode(p);removeNode(p.next);p=start=b;}p=p.next;}while(p!==start);return p;}// try splitting polygon into two and triangulate them independently function splitEarcut(start,triangles,dim,minX,minY,size){// look for a valid diagonal that divides the polygon into two var a=start;do{var b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){// split the polygon in two by the diagonal var c=splitPolygon(a,b);// filter colinear points around the cuts a=filterPoints(a,a.next);c=filterPoints(c,c.next);// run earcut on each half earcutLinked(a,triangles,dim,minX,minY,size);earcutLinked(c,triangles,dim,minX,minY,size);return;}b=b.next;}a=a.next;}while(a!==start);}// link every hole into the outer loop, producing a single-ring polygon without holes function eliminateHoles(data,holeIndices,outerNode,dim){var queue=[],i,len,start,end,list;for(i=0,len=holeIndices.length;i=p.next.y){var x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){qx=x;if(x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next;}m=p.x=p.x&&p.x>=mx&&pointInTriangle(hym.x)&&locallyInside(p,hole)){m=p;tanMin=tan;}}p=p.next;}return m;}// interlink polygon nodes in z-order function indexCurve(start,minX,minY,size){var p=start;do{if(p.z===null)p.z=zOrder(p.x,p.y,minX,minY,size);p.prevZ=p.prev;p.nextZ=p.next;p=p.next;}while(p!==start);p.prevZ.nextZ=null;p.prevZ=null;sortLinked(p);}// Simon Tatham's linked list merge sort algorithm // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html function sortLinked(list){var i,p,q,e,tail,numMerges,pSize,qSize,inSize=1;do{p=list;list=null;tail=null;numMerges=0;while(p){numMerges++;q=p;pSize=0;for(i=0;i0||qSize>0&&q){if(pSize===0){e=q;q=q.nextZ;qSize--;}else if(qSize===0||!q){e=p;p=p.nextZ;pSize--;}else if(p.z<=q.z){e=p;p=p.nextZ;pSize--;}else{e=q;q=q.nextZ;qSize--;}if(tail)tail.nextZ=e;else list=e;e.prevZ=tail;tail=e;}p=q;}tail.nextZ=null;inSize*=2;}while(numMerges>1);return list;}// z-order of a point given coords and size of the data bounding box function zOrder(x,y,minX,minY,size){// coords are transformed into non-negative 15-bit integer range x=32767*(x-minX)/size;y=32767*(y-minY)/size;x=(x|x<<8)&0x00FF00FF;x=(x|x<<4)&0x0F0F0F0F;x=(x|x<<2)&0x33333333;x=(x|x<<1)&0x55555555;y=(y|y<<8)&0x00FF00FF;y=(y|y<<4)&0x0F0F0F0F;y=(y|y<<2)&0x33333333;y=(y|y<<1)&0x55555555;return x|y<<1;}// find the leftmost node of a polygon ring function getLeftmost(start){var p=start,leftmost=start;do{if(p.x=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0;}// check if a diagonal between two polygon nodes is valid (lies in polygon interior) function isValidDiagonal(a,b){return a.next.i!==b.i&&a.prev.i!==b.i&&!intersectsPolygon(a,b)&&locallyInside(a,b)&&locallyInside(b,a)&&middleInside(a,b);}// signed area of a triangle function area(p,q,r){return(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y);}// check if two points are equal function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y;}// check if two segments intersect function intersects(p1,q1,p2,q2){if(equals(p1,q1)&&equals(p2,q2)||equals(p1,q2)&&equals(p2,q1))return true;return area(p1,q1,p2)>0!==area(p1,q1,q2)>0&&area(p2,q2,p1)>0!==area(p2,q2,q1)>0;}// check if a polygon diagonal intersects any polygon segments function intersectsPolygon(a,b){var p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return true;p=p.next;}while(p!==a);return false;}// check if a polygon diagonal is locally inside the polygon function locallyInside(a,b){return area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0;}// check if the middle point of a polygon diagonal is inside the polygon function middleInside(a,b){var p=a,inside=false,px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{if(p.y>py!==p.next.y>py&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x)inside=!inside;p=p.next;}while(p!==a);return inside;}// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; // if one belongs to the outer ring and another to a hole, it merges it into a single ring function splitPolygon(a,b){var a2=new Node(a.i,a.x,a.y),b2=new Node(b.i,b.x,b.y),an=a.next,bp=b.prev;a.next=b;b.prev=a;a2.next=an;an.prev=a2;b2.next=a2;a2.prev=b2;bp.next=b2;b2.prev=bp;return b2;}// create a node and optionally link it with previous one (in a circular doubly linked list) function insertNode(i,x,y,last){var p=new Node(i,x,y);if(!last){p.prev=p;p.next=p;}else{p.next=last.next;p.prev=last;last.next.prev=p;last.next=p;}return p;}function removeNode(p){p.next.prev=p.prev;p.prev.next=p.next;if(p.prevZ)p.prevZ.nextZ=p.nextZ;if(p.nextZ)p.nextZ.prevZ=p.prevZ;}function Node(i,x,y){// vertice index in coordinates array this.i=i;// vertex coordinates this.x=x;this.y=y;// previous and next vertice nodes in a polygon ring this.prev=null;this.next=null;// z-order curve value this.z=null;// previous and next nodes in z-order this.prevZ=null;this.nextZ=null;// indicates whether this is a steiner point this.steiner=false;}// return a percentage difference between the polygon area and its triangulation area; // used to verify correctness of triangulation earcut.deviation=function(data,holeIndices,dim,triangles){var hasHoles=holeIndices&&holeIndices.length;var outerLen=hasHoles?holeIndices[0]*dim:data.length;var polygonArea=Math.abs(signedArea(data,0,outerLen,dim));if(hasHoles){for(var i=0,len=holeIndices.length;i0){holeIndex+=data[i-1].length;result.holes.push(holeIndex);}}return result;};},{}],3:[function(require,module,exports){'use strict';var has=Object.prototype.hasOwnProperty,prefix='~';/** * Constructor to create a storage for our `EE` objects. * An `Events` instance is a plain object whose properties are event names. * * @constructor * @api private */function Events(){}// // We try to not inherit from `Object.prototype`. In some engines creating an // instance in this way is faster than calling `Object.create(null)` directly. // If `Object.create(null)` is not supported we prefix the event names with a // character to make sure that the built-in object properties are not // overridden or used as an attack vector. // if(Object.create){Events.prototype=Object.create(null);// // This hack is needed because the `__proto__` property is still inherited in // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. // if(!new Events().__proto__)prefix=false;}/** * Representation of a single event listener. * * @param {Function} fn The listener function. * @param {Mixed} context The context to invoke the listener with. * @param {Boolean} [once=false] Specify if the listener is a one-time listener. * @constructor * @api private */function EE(fn,context,once){this.fn=fn;this.context=context;this.once=once||false;}/** * Minimal `EventEmitter` interface that is molded against the Node.js * `EventEmitter` interface. * * @constructor * @api public */function EventEmitter(){this._events=new Events();this._eventsCount=0;}/** * Return an array listing the events for which the emitter has registered * listeners. * * @returns {Array} * @api public */EventEmitter.prototype.eventNames=function eventNames(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events){if(has.call(events,name))names.push(prefix?name.slice(1):name);}if(Object.getOwnPropertySymbols){return names.concat(Object.getOwnPropertySymbols(events));}return names;};/** * Return the listeners registered for a given event. * * @param {String|Symbol} event The event name. * @param {Boolean} exists Only check if there are listeners. * @returns {Array|Boolean} * @api public */EventEmitter.prototype.listeners=function listeners(event,exists){var evt=prefix?prefix+event:event,available=this._events[evt];if(exists)return!!available;if(!available)return[];if(available.fn)return[available.fn];for(var i=0,l=available.length,ee=new Array(l);i=data.byteLength){gl.bufferSubData(this.type,offset,data);}else{gl.bufferData(this.type,data,this.drawType);}this.data=data;};/** * Binds the buffer * */Buffer.prototype.bind=function(){var gl=this.gl;gl.bindBuffer(this.type,this.buffer);};Buffer.createVertexBuffer=function(gl,data,drawType){return new Buffer(gl,gl.ARRAY_BUFFER,data,drawType);};Buffer.createIndexBuffer=function(gl,data,drawType){return new Buffer(gl,gl.ELEMENT_ARRAY_BUFFER,data,drawType);};Buffer.create=function(gl,type,data,drawType){return new Buffer(gl,type,data,drawType);};/** * Destroys the buffer * */Buffer.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer);};module.exports=Buffer;},{}],7:[function(require,module,exports){var Texture=require('./GLTexture');/** * Helper class to create a webGL Framebuffer * * @class * @memberof PIXI.glCore * @param gl {WebGLRenderingContext} The current WebGL rendering context * @param width {Number} the width of the drawing area of the frame buffer * @param height {Number} the height of the drawing area of the frame buffer */var Framebuffer=function Framebuffer(gl,width,height){/** * The current WebGL rendering context * * @member {WebGLRenderingContext} */this.gl=gl;/** * The frame buffer * * @member {WebGLFramebuffer} */this.framebuffer=gl.createFramebuffer();/** * The stencil buffer * * @member {WebGLRenderbuffer} */this.stencil=null;/** * The stencil buffer * * @member {PIXI.glCore.GLTexture} */this.texture=null;/** * The width of the drawing area of the buffer * * @member {Number} */this.width=width||100;/** * The height of the drawing area of the buffer * * @member {Number} */this.height=height||100;};/** * Adds a texture to the frame buffer * @param texture {PIXI.glCore.GLTexture} */Framebuffer.prototype.enableTexture=function(texture){var gl=this.gl;this.texture=texture||new Texture(gl);this.texture.bind();//gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); this.bind();gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,this.texture.texture,0);};/** * Initialises the stencil buffer */Framebuffer.prototype.enableStencil=function(){if(this.stencil)return;var gl=this.gl;this.stencil=gl.createRenderbuffer();gl.bindRenderbuffer(gl.RENDERBUFFER,this.stencil);// TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_STENCIL_ATTACHMENT,gl.RENDERBUFFER,this.stencil);gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_STENCIL,this.width,this.height);};/** * Erases the drawing area and fills it with a colour * @param r {Number} the red value of the clearing colour * @param g {Number} the green value of the clearing colour * @param b {Number} the blue value of the clearing colour * @param a {Number} the alpha value of the clearing colour */Framebuffer.prototype.clear=function(r,g,b,a){this.bind();var gl=this.gl;gl.clearColor(r,g,b,a);gl.clear(gl.COLOR_BUFFER_BIT);};/** * Binds the frame buffer to the WebGL context */Framebuffer.prototype.bind=function(){var gl=this.gl;gl.bindFramebuffer(gl.FRAMEBUFFER,this.framebuffer);};/** * Unbinds the frame buffer to the WebGL context */Framebuffer.prototype.unbind=function(){var gl=this.gl;gl.bindFramebuffer(gl.FRAMEBUFFER,null);};/** * Resizes the drawing area of the buffer to the given width and height * @param width {Number} the new width * @param height {Number} the new height */Framebuffer.prototype.resize=function(width,height){var gl=this.gl;this.width=width;this.height=height;if(this.texture){this.texture.uploadData(null,width,height);}if(this.stencil){// update the stencil buffer width and height gl.bindRenderbuffer(gl.RENDERBUFFER,this.stencil);gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_STENCIL,width,height);}};/** * Destroys this buffer */Framebuffer.prototype.destroy=function(){var gl=this.gl;//TODO if(this.texture){this.texture.destroy();}gl.deleteFramebuffer(this.framebuffer);this.gl=null;this.stencil=null;this.texture=null;};/** * Creates a frame buffer with a texture containing the given data * @static * @param gl {WebGLRenderingContext} The current WebGL rendering context * @param width {Number} the width of the drawing area of the frame buffer * @param height {Number} the height of the drawing area of the frame buffer * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data */Framebuffer.createRGBA=function(gl,width,height,data){var texture=Texture.fromData(gl,null,width,height);texture.enableNearestScaling();texture.enableWrapClamp();//now create the framebuffer object and attach the texture to it. var fbo=new Framebuffer(gl,width,height);fbo.enableTexture(texture);fbo.unbind();return fbo;};/** * Creates a frame buffer with a texture containing the given data * @static * @param gl {WebGLRenderingContext} The current WebGL rendering context * @param width {Number} the width of the drawing area of the frame buffer * @param height {Number} the height of the drawing area of the frame buffer * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data */Framebuffer.createFloat32=function(gl,width,height,data){// create a new texture.. var texture=new Texture.fromData(gl,data,width,height);texture.enableNearestScaling();texture.enableWrapClamp();//now create the framebuffer object and attach the texture to it. var fbo=new Framebuffer(gl,width,height);fbo.enableTexture(texture);fbo.unbind();return fbo;};module.exports=Framebuffer;},{"./GLTexture":9}],8:[function(require,module,exports){var compileProgram=require('./shader/compileProgram'),extractAttributes=require('./shader/extractAttributes'),extractUniforms=require('./shader/extractUniforms'),generateUniformAccessObject=require('./shader/generateUniformAccessObject');/** * Helper class to create a webGL Shader * * @class * @memberof PIXI.glCore * @param gl {WebGLRenderingContext} * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. */var Shader=function Shader(gl,vertexSrc,fragmentSrc){/** * The current WebGL rendering context * * @member {WebGLRenderingContext} */this.gl=gl;/** * The shader program * * @member {WebGLProgram} */// First compile the program.. this.program=compileProgram(gl,vertexSrc,fragmentSrc);/** * The attributes of the shader as an object containing the following properties * { * type, * size, * location, * pointer * } * @member {Object} */// next extract the attributes this.attributes=extractAttributes(gl,this.program);var uniformData=extractUniforms(gl,this.program);/** * The uniforms of the shader as an object containing the following properties * { * gl, * data * } * @member {Object} */this.uniforms=generateUniformAccessObject(gl,uniformData);};/** * Uses this shader */Shader.prototype.bind=function(){this.gl.useProgram(this.program);};/** * Destroys this shader * TODO */Shader.prototype.destroy=function(){// var gl = this.gl; };module.exports=Shader;},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(require,module,exports){/** * Helper class to create a WebGL Texture * * @class * @memberof PIXI.glCore * @param gl {WebGLRenderingContext} The current WebGL context * @param width {number} the width of the texture * @param height {number} the height of the texture * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */var Texture=function Texture(gl,width,height,format,type){/** * The current WebGL rendering context * * @member {WebGLRenderingContext} */this.gl=gl;/** * The WebGL texture * * @member {WebGLTexture} */this.texture=gl.createTexture();/** * If mipmapping was used for this texture, enable and disable with enableMipmap() * * @member {Boolean} */// some settings.. this.mipmap=false;/** * Set to true to enable pre-multiplied alpha * * @member {Boolean} */this.premultiplyAlpha=false;/** * The width of texture * * @member {Number} */this.width=width||-1;/** * The height of texture * * @member {Number} */this.height=height||-1;/** * The pixel format of the texture. defaults to gl.RGBA * * @member {Number} */this.format=format||gl.RGBA;/** * The gl type of the texture. defaults to gl.UNSIGNED_BYTE * * @member {Number} */this.type=type||gl.UNSIGNED_BYTE;};/** * Uploads this texture to the GPU * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture */Texture.prototype.upload=function(source){this.bind();var gl=this.gl;gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var newWidth=source.videoWidth||source.width;var newHeight=source.videoHeight||source.height;if(newHeight!==this.height||newWidth!==this.width){gl.texImage2D(gl.TEXTURE_2D,0,this.format,this.format,this.type,source);}else{gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,this.format,this.type,source);}// if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. this.width=newWidth;this.height=newHeight;};var FLOATING_POINT_AVAILABLE=false;/** * Use a data source and uploads this texture to the GPU * @param data {TypedArray} the data to upload to the texture * @param width {number} the new width of the texture * @param height {number} the new height of the texture */Texture.prototype.uploadData=function(data,width,height){this.bind();var gl=this.gl;if(data instanceof Float32Array){if(!FLOATING_POINT_AVAILABLE){var ext=gl.getExtension("OES_texture_float");if(ext){FLOATING_POINT_AVAILABLE=true;}else{throw new Error('floating point textures not available');}}this.type=gl.FLOAT;}else{// TODO support for other types this.type=gl.UNSIGNED_BYTE;}// what type of data? gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);if(width!==this.width||height!==this.height){gl.texImage2D(gl.TEXTURE_2D,0,this.format,width,height,0,this.format,this.type,data||null);}else{gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,width,height,this.format,this.type,data||null);}this.width=width;this.height=height;// texSubImage2D };/** * Binds the texture * @param location */Texture.prototype.bind=function(location){var gl=this.gl;if(location!==undefined){gl.activeTexture(gl.TEXTURE0+location);}gl.bindTexture(gl.TEXTURE_2D,this.texture);};/** * Unbinds the texture */Texture.prototype.unbind=function(){var gl=this.gl;gl.bindTexture(gl.TEXTURE_2D,null);};/** * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation */Texture.prototype.minFilter=function(linear){var gl=this.gl;this.bind();if(this.mipmap){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,linear?gl.LINEAR_MIPMAP_LINEAR:gl.NEAREST_MIPMAP_NEAREST);}else{gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,linear?gl.LINEAR:gl.NEAREST);}};/** * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation */Texture.prototype.magFilter=function(linear){var gl=this.gl;this.bind();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,linear?gl.LINEAR:gl.NEAREST);};/** * Enables mipmapping */Texture.prototype.enableMipmap=function(){var gl=this.gl;this.bind();this.mipmap=true;gl.generateMipmap(gl.TEXTURE_2D);};/** * Enables linear filtering */Texture.prototype.enableLinearScaling=function(){this.minFilter(true);this.magFilter(true);};/** * Enables nearest neighbour interpolation */Texture.prototype.enableNearestScaling=function(){this.minFilter(false);this.magFilter(false);};/** * Enables clamping on the texture so WebGL will not repeat it */Texture.prototype.enableWrapClamp=function(){var gl=this.gl;this.bind();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);};/** * Enable tiling on the texture */Texture.prototype.enableWrapRepeat=function(){var gl=this.gl;this.bind();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.REPEAT);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.REPEAT);};Texture.prototype.enableWrapMirrorRepeat=function(){var gl=this.gl;this.bind();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.MIRRORED_REPEAT);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.MIRRORED_REPEAT);};/** * Destroys this texture */Texture.prototype.destroy=function(){var gl=this.gl;//TODO gl.deleteTexture(this.texture);};/** * @static * @param gl {WebGLRenderingContext} The current WebGL context * @param source {HTMLImageElement|ImageData} the source image of the texture * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha */Texture.fromSource=function(gl,source,premultiplyAlpha){var texture=new Texture(gl);texture.premultiplyAlpha=premultiplyAlpha||false;texture.upload(source);return texture;};/** * @static * @param gl {WebGLRenderingContext} The current WebGL context * @param data {TypedArray} the data to upload to the texture * @param width {number} the new width of the texture * @param height {number} the new height of the texture */Texture.fromData=function(gl,data,width,height){//console.log(data, width, height); var texture=new Texture(gl);texture.uploadData(data,width,height);return texture;};module.exports=Texture;},{}],10:[function(require,module,exports){// state object// var setVertexAttribArrays=require('./setVertexAttribArrays');/** * Helper class to work with WebGL VertexArrayObjects (vaos) * Only works if WebGL extensions are enabled (they usually are) * * @class * @memberof PIXI.glCore * @param gl {WebGLRenderingContext} The current WebGL rendering context */function VertexArrayObject(gl,state){this.nativeVaoExtension=null;if(!VertexArrayObject.FORCE_NATIVE){this.nativeVaoExtension=gl.getExtension('OES_vertex_array_object')||gl.getExtension('MOZ_OES_vertex_array_object')||gl.getExtension('WEBKIT_OES_vertex_array_object');}this.nativeState=state;if(this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var maxAttribs=gl.getParameter(gl.MAX_VERTEX_ATTRIBS);// VAO - overwrite the state.. this.nativeState={tempAttribState:new Array(maxAttribs),attribState:new Array(maxAttribs)};}/** * The current WebGL rendering context * * @member {WebGLRenderingContext} */this.gl=gl;/** * An array of attributes * * @member {Array} */this.attributes=[];/** * @member {PIXI.glCore.GLBuffer} */this.indexBuffer=null;/** * A boolean flag * * @member {Boolean} */this.dirty=false;}VertexArrayObject.prototype.constructor=VertexArrayObject;module.exports=VertexArrayObject;/** * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) * If you find on older devices that things have gone a bit weird then set this to true. *//** * Lets the VAO know if you should use the WebGL extension or the native methods. * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) * If you find on older devices that things have gone a bit weird then set this to true. * @static * @property {Boolean} FORCE_NATIVE */VertexArrayObject.FORCE_NATIVE=false;/** * Binds the buffer */VertexArrayObject.prototype.bind=function(){if(this.nativeVao){this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao);if(this.dirty){this.dirty=false;this.activate();}}else{this.activate();}return this;};/** * Unbinds the buffer */VertexArrayObject.prototype.unbind=function(){if(this.nativeVao){this.nativeVaoExtension.bindVertexArrayOES(null);}return this;};/** * Uses this vao */VertexArrayObject.prototype.activate=function(){var gl=this.gl;var lastBuffer=null;for(var i=0;i 0 var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==='.'){parts.splice(i,1);}else if(last==='..'){parts.splice(i,1);up++;}else if(up){parts.splice(i,1);up--;}}// if the path is allowed to go above the root, restore leading ..s if(allowAboveRoot){for(;up--;up){parts.unshift('..');}}return parts;}// Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function splitPath(filename){return splitPathRe.exec(filename).slice(1);};// path.resolve([from ...], to) // posix version exports.resolve=function(){var resolvedPath='',resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();// Skip empty and invalid entries if(typeof path!=='string'){throw new TypeError('Arguments to path.resolve must be strings');}else if(!path){continue;}resolvedPath=path+'/'+resolvedPath;resolvedAbsolute=path.charAt(0)==='/';}// At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath=normalizeArray(filter(resolvedPath.split('/'),function(p){return!!p;}),!resolvedAbsolute).join('/');return(resolvedAbsolute?'/':'')+resolvedPath||'.';};// path.normalize(path) // posix version exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==='/';// Normalize the path path=normalizeArray(filter(path.split('/'),function(p){return!!p;}),!isAbsolute).join('/');if(!path&&!isAbsolute){path='.';}if(path&&trailingSlash){path+='/';}return(isAbsolute?'/':'')+path;};// posix version exports.isAbsolute=function(path){return path.charAt(0)==='/';};// posix version exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=='string'){throw new TypeError('Arguments to path.join must be strings');}return p;}).join('/'));};// path.relative(from, to) // posix version exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=='')break;}if(start>end)return[];return arr.slice(start,end-start+1);}var fromParts=trim(from.split('/'));var toParts=trim(to.split('/'));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i1){for(var i=1;i= 0x80 (not a basic code point)','invalid-input':'Invalid input'},/** Convenience shortcuts */baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,/** Temporary variable */key;/*--------------------------------------------------------------------------*//** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */function error(type){throw new RangeError(errors[type]);}/** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length]);}return result;}/** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */function mapDomain(string,fn){var parts=string.split('@');var result='';if(parts.length>1){// In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result=parts[0]+'@';string=parts[1];}// Avoid `split(regex)` for IE8 compatibility. See #17. string=string.replace(regexSeparators,'\x2E');var labels=string.split('.');var encoded=map(labels,fn).join('.');return result+encoded;}/** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter=0xD800&&value<=0xDBFF&&counter0xFFFF){value-=0x10000;output+=stringFromCharCode(value>>>10&0x3FF|0xD800);value=0xDC00|value&0x3FF;}output+=stringFromCharCode(value);return output;}).join('');}/** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22;}if(codePoint-65<26){return codePoint-65;}if(codePoint-97<26){return codePoint-97;}return base;}/** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */function digitToBasic(digit,flag){// 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit+22+75*(digit<26)-((flag!=0)<<5);}/** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}/** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */function decode(input){// Don't use UCS-2 var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,/** Cached calculation results */baseMinusT;// Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic=input.lastIndexOf(delimiter);if(basic<0){basic=0;}for(j=0;j=0x80){error('not-basic');}output.push(input.charCodeAt(j));}// Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for(index=basic>0?basic+1:0;index=inputLength){error('invalid-input');}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error('overflow');}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digitfloor(maxInt/baseMinusT)){error('overflow');}w*=baseMinusT;}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);// `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if(floor(i/out)>maxInt-n){error('overflow');}n+=floor(i/out);i%=out;// Insert `n` at position `i` of the output output.splice(i++,0,n);}return ucs2encode(output);}/** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],/** `inputLength` will hold the number of code points in `input`. */inputLength,/** Cached calculation results */handledCPCountPlusOne,baseMinusT,qMinusT;// Convert the input in UCS-2 to Unicode input=ucs2decode(input);// Cache the length inputLength=input.length;// Initialize the state n=initialN;delta=0;bias=initialBias;// Handle the basic code points for(j=0;j=n&¤tValue state to , // but guard against overflow handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error('overflow');}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;jmaxInt){error('overflow');}if(currentValue==n){// Represent delta as a generalized variable-length integer for(q=delta,k=base;;/* no condition */k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q * @memberOf punycode * @type Object */'ucs2':{'decode':ucs2decode,'encode':ucs2encode},'decode':decode,'encode':encode,'toASCII':toASCII,'toUnicode':toUnicode};/** Expose `punycode` */// Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if(typeof define=='function'&&_typeof2(define.amd)=='object'&&define.amd){define('punycode',function(){return punycode;});}else if(freeExports&&freeModule){if(module.exports==freeExports){// in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports=punycode;}else{// in Narwhal or RingoJS v0.7.0- for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key]);}}}else{// in Rhino or a web browser root.punycode=punycode;}})(this);}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{}],25:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict';// If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop);}module.exports=function(qs,sep,eq,options){sep=sep||'&';eq=eq||'=';var obj={};if(typeof qs!=='string'||qs.length===0){return obj;}var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1000;if(options&&typeof options.maxKeys==='number'){maxKeys=options.maxKeys;}var len=qs.length;// maxKeys <= 0 means that we should not limit keys count if(maxKeys>0&&len>maxKeys){len=maxKeys;}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1);}else{kstr=x;vstr='';}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v;}else if(isArray(obj[k])){obj[k].push(v);}else{obj[k]=[obj[k],v];}}return obj;};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};},{}],26:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict';var stringifyPrimitive=function stringifyPrimitive(v){switch(typeof v==="undefined"?"undefined":_typeof2(v)){case'string':return v;case'boolean':return v?'true':'false';case'number':return isFinite(v)?v:'';default:return'';}};module.exports=function(obj,sep,eq,name){sep=sep||'&';eq=eq||'=';if(obj===null){obj=undefined;}if((typeof obj==="undefined"?"undefined":_typeof2(obj))==='object'){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v));}).join(sep);}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]));}}).join(sep);}if(!name)return'';return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj));};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i','"','`',' ','\r','\n','\t'],// RFC 2396: characters not allowed for various reasons. unwise=['{','}','|','\\','^','`'].concat(delims),// Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape=['\''].concat(unwise),// Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars=['%','/','?',';','#'].concat(autoEscape),hostEndingChars=['/','?','#'],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,// protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol={'javascript':true,'javascript:':true},// protocols that never have a hostname. hostlessProtocol={'javascript':true,'javascript:':true},// protocols that always contain a // bit. slashedProtocol={'http':true,'https':true,'ftp':true,'gopher':true,'file':true,'http:':true,'https:':true,'ftp:':true,'gopher:':true,'file:':true},querystring=require('querystring');function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url();u.parse(url,parseQueryString,slashesDenoteHost);return u;}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+(typeof url==="undefined"?"undefined":_typeof2(url)));}// Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 var queryIndex=url.indexOf('?'),splitter=queryIndex!==-1&&queryIndex user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd=-1;for(var i=0;i host:b auth:a path:/c@d atSign=rest.lastIndexOf('@',hostEnd);}// Now we have a portion which is definitely the auth. // Pull that off. if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth);}// the host is the remaining to the left of the first non-host char hostEnd=-1;for(var i=0;i127){// we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart+='x';}else{newpart+=part[j];}}// we test again with ASCII char only if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2]);}if(notHost.length){rest='/'+notHost.join('.')+rest;}this.hostname=validParts.join('.');break;}}}}if(this.hostname.length>hostnameMaxLen){this.hostname='';}else{// hostnames are always lower case. this.hostname=this.hostname.toLowerCase();}if(!ipv6Hostname){// IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that // have non-ASCII characters, i.e. it doesn't matter if // you call it with a domain that already is ASCII-only. this.hostname=punycode.toASCII(this.hostname);}var p=this.port?':'+this.port:'';var h=this.hostname||'';this.host=h+p;this.href+=this.host;// strip [ and ] from the hostname // the host field still retains them, though if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=='/'){rest='/'+rest;}}}// now rest is set to the post-host stuff. // chop off any delim chars. if(!unsafeProtocol[lowerProto]){// First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for(var i=0,l=autoEscape.length;i0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift();}}result.search=relative.search;result.query=relative.query;//to support http.request if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.href=result.format();return result;}if(!srcPath.length){// no path at all. easy. // we've already handled the other stuff above. result.pathname=null;//to support http.request if(result.search){result.path='/'+result.search;}else{result.path=null;}result.href=result.format();return result;}// if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last==='.'||last==='..')||last==='';// strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last==='.'){srcPath.splice(i,1);}else if(last==='..'){srcPath.splice(i,1);up++;}else if(up){srcPath.splice(i,1);up--;}}// if the path is allowed to go above the root, restore leading ..s if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift('..');}}if(mustEndAbs&&srcPath[0]!==''&&(!srcPath[0]||srcPath[0].charAt(0)!=='/')){srcPath.unshift('');}if(hasTrailingSlash&&srcPath.join('/').substr(-1)!=='/'){srcPath.push('');}var isAbsolute=srcPath[0]===''||srcPath[0]&&srcPath[0].charAt(0)==='/';// put the host back if(psychotic){result.hostname=result.host=isAbsolute?'':srcPath.length?srcPath.shift():'';//occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost=result.host&&result.host.indexOf('@')>0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift();}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift('');}if(!srcPath.length){result.pathname=null;result.path=null;}else{result.pathname=srcPath.join('/');}//to support request.http if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result;};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==':'){this.port=port.substr(1);}host=host.substr(0,host.length-port.length);}if(host)this.hostname=host;};},{"./util":29,"punycode":24,"querystring":27}],29:[function(require,module,exports){'use strict';module.exports={isString:function isString(arg){return typeof arg==='string';},isObject:function isObject(arg){return(typeof arg==="undefined"?"undefined":_typeof2(arg))==='object'&&arg!==null;},isNull:function isNull(arg){return arg===null;},isNullOrUndefined:function isNullOrUndefined(arg){return arg==null;}};},{}],30:[function(require,module,exports){'use strict';exports.__esModule=true;var _typeof=typeof Symbol==="function"&&_typeof2(Symbol.iterator)==="symbol"?function(obj){return typeof obj==="undefined"?"undefined":_typeof2(obj);}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj==="undefined"?"undefined":_typeof2(obj);};var _miniSignals=require('mini-signals');var _miniSignals2=_interopRequireDefault(_miniSignals);var _parseUri=require('parse-uri');var _parseUri2=_interopRequireDefault(_parseUri);var _async=require('./async');var async=_interopRequireWildcard(_async);var _Resource=require('./Resource');var _Resource2=_interopRequireDefault(_Resource);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}// some constants var MAX_PROGRESS=100;var rgxExtractUrlHash=/(#[\w\-]+)?$/;/** * Manages the state and loading of multiple resources to load. * * @class */var Loader=function(){/** * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. * @param {number} [concurrency=10] - The number of resources to load concurrently. */function Loader(){var _this=this;var baseUrl=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var concurrency=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;_classCallCheck(this,Loader);/** * The base url for all resources loaded by this loader. * * @member {string} */this.baseUrl=baseUrl;/** * The progress percent of the loader going through the queue. * * @member {number} */this.progress=0;/** * Loading state of the loader, true if it is currently loading resources. * * @member {boolean} */this.loading=false;/** * A querystring to append to every URL added to the loader. * * This should be a valid query string *without* the question-mark (`?`). The loader will * also *not* escape values for you. Make sure to escape your parameters with * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. * * @example * * ```js * const loader = new Loader(); * * loader.defaultQueryString = 'user=me&password=secret'; * * // This will request 'image.png?user=me&password=secret' * loader.add('image.png').load(); * * loader.reset(); * * // This will request 'image.png?v=1&user=me&password=secret' * loader.add('iamge.png?v=1').load(); * ``` */this.defaultQueryString='';/** * The middleware to run before loading each resource. * * @member {function[]} */this._beforeMiddleware=[];/** * The middleware to run after loading each resource. * * @member {function[]} */this._afterMiddleware=[];/** * The `_loadResource` function bound with this object context. * * @private * @member {function} * @param {Resource} r - The resource to load * @param {Function} d - The dequeue function * @return {undefined} */this._boundLoadResource=function(r,d){return _this._loadResource(r,d);};/** * The resources waiting to be loaded. * * @private * @member {Resource[]} */this._queue=async.queue(this._boundLoadResource,concurrency);this._queue.pause();/** * All the resources for this loader keyed by name. * * @member {object} */this.resources={};/** * Dispatched once per loaded or errored resource. * * The callback looks like {@link Loader.OnProgressSignal}. * * @member {Signal} */this.onProgress=new _miniSignals2.default();/** * Dispatched once per errored resource. * * The callback looks like {@link Loader.OnErrorSignal}. * * @member {Signal} */this.onError=new _miniSignals2.default();/** * Dispatched once per loaded resource. * * The callback looks like {@link Loader.OnLoadSignal}. * * @member {Signal} */this.onLoad=new _miniSignals2.default();/** * Dispatched when the loader begins to process the queue. * * The callback looks like {@link Loader.OnStartSignal}. * * @member {Signal} */this.onStart=new _miniSignals2.default();/** * Dispatched when the queued resources all load. * * The callback looks like {@link Loader.OnCompleteSignal}. * * @member {Signal} */this.onComplete=new _miniSignals2.default();/** * When the progress changes the loader and resource are disaptched. * * @memberof Loader * @callback OnProgressSignal * @param {Loader} loader - The loader the progress is advancing on. * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. *//** * When an error occurrs the loader and resource are disaptched. * * @memberof Loader * @callback OnErrorSignal * @param {Loader} loader - The loader the error happened in. * @param {Resource} resource - The resource that caused the error. *//** * When a load completes the loader and resource are disaptched. * * @memberof Loader * @callback OnLoadSignal * @param {Loader} loader - The loader that laoded the resource. * @param {Resource} resource - The resource that has completed loading. *//** * When the loader starts loading resources it dispatches this callback. * * @memberof Loader * @callback OnStartSignal * @param {Loader} loader - The loader that has started loading resources. *//** * When the loader completes loading resources it dispatches this callback. * * @memberof Loader * @callback OnCompleteSignal * @param {Loader} loader - The loader that has finished loading resources. */}/** * Adds a resource (or multiple resources) to the loader queue. * * This function can take a wide variety of different parameters. The only thing that is always * required the url to load. All the following will work: * * ```js * loader * // normal param syntax * .add('key', 'http://...', function () {}) * .add('http://...', function () {}) * .add('http://...') * * // object syntax * .add({ * name: 'key2', * url: 'http://...' * }, function () {}) * .add({ * url: 'http://...' * }, function () {}) * .add({ * name: 'key3', * url: 'http://...' * onComplete: function () {} * }) * .add({ * url: 'https://...', * onComplete: function () {}, * crossOrigin: true * }) * * // you can also pass an array of objects or urls or both * .add([ * { name: 'key4', url: 'http://...', onComplete: function () {} }, * { url: 'http://...', onComplete: function () {} }, * 'http://...' * ]) * * // and you can use both params and options * .add('key', 'http://...', { crossOrigin: true }, function () {}) * .add('http://...', { crossOrigin: true }, function () {}); * ``` * * @param {string} [name] - The name of the resource to load, if not passed the url is used. * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. * @param {object} [options] - The options for the load. * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should * the data being loaded be interpreted when using XHR? * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The * element to use for loading, instead of creating one. * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This * is useful if you want to pass in a `loadElement` that you already added load sources to. * @param {function} [cb] - Function to call when this specific resource completes loading. * @return {Loader} Returns itself. */Loader.prototype.add=function add(name,url,options,cb){// special case of an array of objects or urls if(Array.isArray(name)){for(var i=0;i0){// if text, just return it if(this.xhrType===Resource.XHR_RESPONSE_TYPE.TEXT){this.data=xhr.responseText;this.type=Resource.TYPE.TEXT;}// if json, parse into json object else if(this.xhrType===Resource.XHR_RESPONSE_TYPE.JSON){try{this.data=JSON.parse(xhr.responseText);this.type=Resource.TYPE.JSON;}catch(e){this.abort('Error trying to parse loaded json: '+e);return;}}// if xml, parse into an xml document or div element else if(this.xhrType===Resource.XHR_RESPONSE_TYPE.DOCUMENT){try{if(window.DOMParser){var domparser=new DOMParser();this.data=domparser.parseFromString(xhr.responseText,'text/xml');}else{var div=document.createElement('div');div.innerHTML=xhr.responseText;this.data=div;}this.type=Resource.TYPE.XML;}catch(e){this.abort('Error trying to parse loaded xml: '+e);return;}}// other types just return the response else{this.data=xhr.response||xhr.responseText;}}else{this.abort('['+xhr.status+'] '+xhr.statusText+': '+xhr.responseURL);return;}this.complete();};/** * Sets the `crossOrigin` property for this resource based on if the url * for this resource is cross-origin. If crossOrigin was manually set, this * function does nothing. * * @private * @param {string} url - The url to test. * @param {object} [loc=window.location] - The location object to test against. * @return {string} The crossOrigin value to use (or empty string for none). */Resource.prototype._determineCrossOrigin=function _determineCrossOrigin(url,loc){// data: and javascript: urls are considered same-origin if(url.indexOf('data:')===0){return'';}// default is window.location loc=loc||window.location;if(!tempAnchor){tempAnchor=document.createElement('a');}// let the browser determine the full href for the url of this resource and then // parse with the node url lib, we can't use the properties of the anchor element // because they don't work in IE9 :( tempAnchor.href=url;url=(0,_parseUri2.default)(tempAnchor.href,{strictMode:true});var samePort=!url.port&&loc.port===''||url.port===loc.port;var protocol=url.protocol?url.protocol+':':'';// if cross origin if(url.host!==loc.hostname||!samePort||protocol!==loc.protocol){return'anonymous';}return'';};/** * Determines the responseType of an XHR request based on the extension of the * resource being loaded. * * @private * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. */Resource.prototype._determineXhrType=function _determineXhrType(){return Resource._xhrTypeMap[this._getExtension()]||Resource.XHR_RESPONSE_TYPE.TEXT;};/** * Determines the loadType of a resource based on the extension of the * resource being loaded. * * @private * @return {Resource.LOAD_TYPE} The loadType to use. */Resource.prototype._determineLoadType=function _determineLoadType(){return Resource._loadTypeMap[this._getExtension()]||Resource.LOAD_TYPE.XHR;};/** * Extracts the extension (sans '.') of the file being loaded by the resource. * * @private * @return {string} The extension. */Resource.prototype._getExtension=function _getExtension(){var url=this.url;var ext='';if(this.isDataUrl){var slashIndex=url.indexOf('/');ext=url.substring(slashIndex+1,url.indexOf(';',slashIndex));}else{var queryStart=url.indexOf('?');if(queryStart!==-1){url=url.substring(0,queryStart);}ext=url.substring(url.lastIndexOf('.')+1);}return ext.toLowerCase();};/** * Determines the mime type of an XHR request based on the responseType of * resource being loaded. * * @private * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. * @return {string} The mime type to use. */Resource.prototype._getMimeFromXhrType=function _getMimeFromXhrType(type){switch(type){case Resource.XHR_RESPONSE_TYPE.BUFFER:return'application/octet-binary';case Resource.XHR_RESPONSE_TYPE.BLOB:return'application/blob';case Resource.XHR_RESPONSE_TYPE.DOCUMENT:return'application/xml';case Resource.XHR_RESPONSE_TYPE.JSON:return'application/json';case Resource.XHR_RESPONSE_TYPE.DEFAULT:case Resource.XHR_RESPONSE_TYPE.TEXT:/* falls through */default:return'text/plain';}};_createClass(Resource,[{key:'isDataUrl',get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL);}/** * Describes if this resource has finished loading. Is true when the resource has completely * loaded. * * @member {boolean} * @readonly */},{key:'isComplete',get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE);}/** * Describes if this resource is currently loading. Is true when the resource starts loading, * and is false again when complete. * * @member {boolean} * @readonly */},{key:'isLoading',get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.LOADING);}}]);return Resource;}();/** * The types of resources a resource could represent. * * @static * @readonly * @enum {number} */exports.default=Resource;Resource.STATUS_FLAGS={NONE:0,DATA_URL:1<<0,COMPLETE:1<<1,LOADING:1<<2};/** * The types of resources a resource could represent. * * @static * @readonly * @enum {number} */Resource.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6};/** * The types of loading a resource can use. * * @static * @readonly * @enum {number} */Resource.LOAD_TYPE={/** Uses XMLHttpRequest to load the resource. */XHR:1,/** Uses an `Image` object to load the resource. */IMAGE:2,/** Uses an `Audio` object to load the resource. */AUDIO:3,/** Uses a `Video` object to load the resource. */VIDEO:4};/** * The XHR ready states, used internally. * * @static * @readonly * @enum {string} */Resource.XHR_RESPONSE_TYPE={/** string */DEFAULT:'text',/** ArrayBuffer */BUFFER:'arraybuffer',/** Blob */BLOB:'blob',/** Document */DOCUMENT:'document',/** Object */JSON:'json',/** String */TEXT:'text'};Resource._loadTypeMap={// images gif:Resource.LOAD_TYPE.IMAGE,png:Resource.LOAD_TYPE.IMAGE,bmp:Resource.LOAD_TYPE.IMAGE,jpg:Resource.LOAD_TYPE.IMAGE,jpeg:Resource.LOAD_TYPE.IMAGE,tif:Resource.LOAD_TYPE.IMAGE,tiff:Resource.LOAD_TYPE.IMAGE,webp:Resource.LOAD_TYPE.IMAGE,tga:Resource.LOAD_TYPE.IMAGE,svg:Resource.LOAD_TYPE.IMAGE,'svg+xml':Resource.LOAD_TYPE.IMAGE,// for SVG data urls // audio mp3:Resource.LOAD_TYPE.AUDIO,ogg:Resource.LOAD_TYPE.AUDIO,wav:Resource.LOAD_TYPE.AUDIO,// videos mp4:Resource.LOAD_TYPE.VIDEO,webm:Resource.LOAD_TYPE.VIDEO};Resource._xhrTypeMap={// xml xhtml:Resource.XHR_RESPONSE_TYPE.DOCUMENT,html:Resource.XHR_RESPONSE_TYPE.DOCUMENT,htm:Resource.XHR_RESPONSE_TYPE.DOCUMENT,xml:Resource.XHR_RESPONSE_TYPE.DOCUMENT,tmx:Resource.XHR_RESPONSE_TYPE.DOCUMENT,svg:Resource.XHR_RESPONSE_TYPE.DOCUMENT,// This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, // this should probably be fine. tsx:Resource.XHR_RESPONSE_TYPE.DOCUMENT,// images gif:Resource.XHR_RESPONSE_TYPE.BLOB,png:Resource.XHR_RESPONSE_TYPE.BLOB,bmp:Resource.XHR_RESPONSE_TYPE.BLOB,jpg:Resource.XHR_RESPONSE_TYPE.BLOB,jpeg:Resource.XHR_RESPONSE_TYPE.BLOB,tif:Resource.XHR_RESPONSE_TYPE.BLOB,tiff:Resource.XHR_RESPONSE_TYPE.BLOB,webp:Resource.XHR_RESPONSE_TYPE.BLOB,tga:Resource.XHR_RESPONSE_TYPE.BLOB,// json json:Resource.XHR_RESPONSE_TYPE.JSON,// text text:Resource.XHR_RESPONSE_TYPE.TEXT,txt:Resource.XHR_RESPONSE_TYPE.TEXT,// fonts ttf:Resource.XHR_RESPONSE_TYPE.BUFFER,otf:Resource.XHR_RESPONSE_TYPE.BUFFER};// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif Resource.EMPTY_GIF='data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';/** * Quick helper to set a value on one of the extension maps. Ensures there is no * dot at the start of the extension. * * @ignore * @param {object} map - The map to set on. * @param {string} extname - The extension (or key) to set. * @param {number} val - The value to set. */function setExtMap(map,extname,val){if(extname&&extname.indexOf('.')===0){extname=extname.substring(1);}if(!extname){return;}map[extname]=val;}/** * Quick helper to get string xhr type. * * @ignore * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. * @return {string} The type. */function reqType(xhr){return xhr.toString().replace('object ','');}},{"mini-signals":36,"parse-uri":37}],32:[function(require,module,exports){'use strict';exports.__esModule=true;exports.eachSeries=eachSeries;exports.queue=queue;/** * Smaller version of the async library constructs. * */function _noop(){}/* empty *//** * Iterates an array in series. * * @param {*[]} array - Array to iterate. * @param {function} iterator - Function to call for each element. * @param {function} callback - Function to call when done, or on error. */function eachSeries(array,iterator,callback){var i=0;var len=array.length;(function next(err){if(err||i===len){if(callback){callback(err);}return;}iterator(array[i++],next);})();}/** * Ensures a function is only called once. * * @param {function} fn - The function to wrap. * @return {function} The wrapping function. */function onlyOnce(fn){return function onceWrapper(){if(fn===null){throw new Error('Callback was already called.');}var callFn=fn;fn=null;callFn.apply(this,arguments);};}/** * Async queue implementation, * * @param {function} worker - The worker function to call for each task. * @param {number} concurrency - How many workers to run in parrallel. * @return {*} The async queue object. */function queue(worker,concurrency){if(concurrency==null){// eslint-disable-line no-eq-null,eqeqeq concurrency=1;}else if(concurrency===0){throw new Error('Concurrency must not be zero');}var workers=0;var q={_tasks:[],concurrency:concurrency,saturated:_noop,unsaturated:_noop,buffer:concurrency/4,empty:_noop,drain:_noop,error:_noop,started:false,paused:false,push:function push(data,callback){_insert(data,false,callback);},kill:function kill(){workers=0;q.drain=_noop;q.started=false;q._tasks=[];},unshift:function unshift(data,callback){_insert(data,true,callback);},process:function process(){while(!q.paused&&workers>2;// index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) encodedCharIndexes[1]=(bytebuffer[0]&0x3)<<4|bytebuffer[1]>>4;// index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) encodedCharIndexes[2]=(bytebuffer[1]&0x0f)<<2|bytebuffer[2]>>6;// index 3: forth 6 bits (6 least significant bits from input byte 3) encodedCharIndexes[3]=bytebuffer[2]&0x3f;// Determine whether padding happened, and adjust accordingly var paddingBytes=inx-(input.length-1);switch(paddingBytes){case 2:// Set last 2 characters to padding char encodedCharIndexes[3]=64;encodedCharIndexes[2]=64;break;case 1:// Set last character to padding char encodedCharIndexes[3]=64;break;default:break;// No padding - proceed }// Now we will grab each appropriate character out of our keystring // based on our index array and append it to the output string for(var _jnx=0;_jnx} * @private */this.children=[];/** * pre-bind the functions * * @private */this._onKeyDown=this._onKeyDown.bind(this);this._onMouseMove=this._onMouseMove.bind(this);/** * stores the state of the manager. If there are no accessible objects or the mouse is moving the will be false. * * @member {Array<*>} * @private */this.isActive=false;this.isMobileAccessabillity=false;// let listen for tab.. once pressed we can fire up and show the accessibility layer window.addEventListener('keydown',this._onKeyDown,false);}/** * Creates the touch hooks. * */AccessibilityManager.prototype.createTouchHook=function createTouchHook(){var _this=this;var hookDiv=document.createElement('button');hookDiv.style.width=DIV_HOOK_SIZE+'px';hookDiv.style.height=DIV_HOOK_SIZE+'px';hookDiv.style.position='absolute';hookDiv.style.top=DIV_HOOK_POS_X+'px';hookDiv.style.left=DIV_HOOK_POS_Y+'px';hookDiv.style.zIndex=DIV_HOOK_ZINDEX;hookDiv.style.backgroundColor='#FF0000';hookDiv.title='HOOK DIV';hookDiv.addEventListener('focus',function(){_this.isMobileAccessabillity=true;_this.activate();document.body.removeChild(hookDiv);});document.body.appendChild(hookDiv);};/** * Activating will cause the Accessibility layer to be shown. This is called when a user * preses the tab key * * @private */AccessibilityManager.prototype.activate=function activate(){if(this.isActive){return;}this.isActive=true;window.document.addEventListener('mousemove',this._onMouseMove,true);window.removeEventListener('keydown',this._onKeyDown,false);this.renderer.on('postrender',this.update,this);if(this.renderer.view.parentNode){this.renderer.view.parentNode.appendChild(this.div);}};/** * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves * the mouse * * @private */AccessibilityManager.prototype.deactivate=function deactivate(){if(!this.isActive||this.isMobileAccessabillity){return;}this.isActive=false;window.document.removeEventListener('mousemove',this._onMouseMove);window.addEventListener('keydown',this._onKeyDown,false);this.renderer.off('postrender',this.update);if(this.div.parentNode){this.div.parentNode.removeChild(this.div);}};/** * This recursive function will run throught he scene graph and add any new accessible objects to the DOM layer. * * @private * @param {PIXI.Container} displayObject - The DisplayObject to check. */AccessibilityManager.prototype.updateAccessibleObjects=function updateAccessibleObjects(displayObject){if(!displayObject.visible){return;}if(displayObject.accessible&&displayObject.interactive){if(!displayObject._accessibleActive){this.addChild(displayObject);}displayObject.renderId=this.renderId;}var children=displayObject.children;for(var i=children.length-1;i>=0;i--){this.updateAccessibleObjects(children[i]);}};/** * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. * * @private */AccessibilityManager.prototype.update=function update(){if(!this.renderer.renderingToScreen){return;}// update children... this.updateAccessibleObjects(this.renderer._lastObjectRendered);var rect=this.renderer.view.getBoundingClientRect();var sx=rect.width/this.renderer.width;var sy=rect.height/this.renderer.height;var div=this.div;div.style.left=rect.left+'px';div.style.top=rect.top+'px';div.style.width=this.renderer.width+'px';div.style.height=this.renderer.height+'px';for(var i=0;ithis.renderer.width){hitArea.width=this.renderer.width-hitArea.x;}if(hitArea.y+hitArea.height>this.renderer.height){hitArea.height=this.renderer.height-hitArea.y;}};/** * Adds a DisplayObject to the accessibility manager * * @private * @param {DisplayObject} displayObject - The child to make accessible. */AccessibilityManager.prototype.addChild=function addChild(displayObject){// this.activate(); var div=this.pool.pop();if(!div){div=document.createElement('button');div.style.width=DIV_TOUCH_SIZE+'px';div.style.height=DIV_TOUCH_SIZE+'px';div.style.backgroundColor=this.debug?'rgba(255,0,0,0.5)':'transparent';div.style.position='absolute';div.style.zIndex=DIV_TOUCH_ZINDEX;div.style.borderStyle='none';div.addEventListener('click',this._onClick.bind(this));div.addEventListener('focus',this._onFocus.bind(this));div.addEventListener('focusout',this._onFocusOut.bind(this));}if(displayObject.accessibleTitle){div.title=displayObject.accessibleTitle;}else if(!displayObject.accessibleTitle&&!displayObject.accessibleHint){div.title='displayObject '+this.tabIndex;}if(displayObject.accessibleHint){div.setAttribute('aria-label',displayObject.accessibleHint);}// displayObject._accessibleActive=true;displayObject._accessibleDiv=div;div.displayObject=displayObject;this.children.push(displayObject);this.div.appendChild(displayObject._accessibleDiv);displayObject._accessibleDiv.tabIndex=displayObject.tabIndex;};/** * Maps the div button press to pixi's InteractionManager (click) * * @private * @param {MouseEvent} e - The click event. */AccessibilityManager.prototype._onClick=function _onClick(e){var interactionManager=this.renderer.plugins.interaction;interactionManager.dispatchEvent(e.target.displayObject,'click',interactionManager.eventData);};/** * Maps the div focus events to pixis InteractionManager (mouseover) * * @private * @param {FocusEvent} e - The focus event. */AccessibilityManager.prototype._onFocus=function _onFocus(e){var interactionManager=this.renderer.plugins.interaction;interactionManager.dispatchEvent(e.target.displayObject,'mouseover',interactionManager.eventData);};/** * Maps the div focus events to pixis InteractionManager (mouseout) * * @private * @param {FocusEvent} e - The focusout event. */AccessibilityManager.prototype._onFocusOut=function _onFocusOut(e){var interactionManager=this.renderer.plugins.interaction;interactionManager.dispatchEvent(e.target.displayObject,'mouseout',interactionManager.eventData);};/** * Is called when a key is pressed * * @private * @param {KeyboardEvent} e - The keydown event. */AccessibilityManager.prototype._onKeyDown=function _onKeyDown(e){if(e.keyCode!==KEY_CODE_TAB){return;}this.activate();};/** * Is called when the mouse moves across the renderer element * * @private */AccessibilityManager.prototype._onMouseMove=function _onMouseMove(){this.deactivate();};/** * Destroys the accessibility manager * */AccessibilityManager.prototype.destroy=function destroy(){this.div=null;for(var i=0;i]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i;// eslint-disable-line max-len /** * Constants that identify shapes, mainly to prevent `instanceof` calls. * * @static * @constant * @name SHAPES * @memberof PIXI * @type {object} * @property {number} POLY Polygon * @property {number} RECT Rectangle * @property {number} CIRC Circle * @property {number} ELIP Ellipse * @property {number} RREC Rounded Rectangle */var SHAPES=exports.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4};/** * Constants that specify float precision in shaders. * * @static * @constant * @name PRECISION * @memberof PIXI * @type {object} * @property {string} LOW='lowp' * @property {string} MEDIUM='mediump' * @property {string} HIGH='highp' */var PRECISION=exports.PRECISION={LOW:'lowp',MEDIUM:'mediump',HIGH:'highp'};/** * Constants that specify the transform type. * * @static * @constant * @name TRANSFORM_MODE * @memberof PIXI * @type {object} * @property {number} STATIC * @property {number} DYNAMIC */var TRANSFORM_MODE=exports.TRANSFORM_MODE={STATIC:0,DYNAMIC:1};/** * Constants that define the type of gradient on text. * * @static * @constant * @name TEXT_GRADIENT * @memberof PIXI * @type {object} * @property {number} LINEAR_VERTICAL Vertical gradient * @property {number} LINEAR_HORIZONTAL Linear gradient */var TEXT_GRADIENT=exports.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1};},{}],43:[function(require,module,exports){'use strict';exports.__esModule=true;var _math=require('../math');function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/** * 'Builder' pattern for bounds rectangles * Axis-Aligned Bounding Box * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems * * @class * @memberof PIXI */var Bounds=function(){/** * */function Bounds(){_classCallCheck(this,Bounds);/** * @member {number} * @default 0 */this.minX=Infinity;/** * @member {number} * @default 0 */this.minY=Infinity;/** * @member {number} * @default 0 */this.maxX=-Infinity;/** * @member {number} * @default 0 */this.maxY=-Infinity;this.rect=null;}/** * Checks if bounds are empty. * * @return {boolean} True if empty. */Bounds.prototype.isEmpty=function isEmpty(){return this.minX>this.maxX||this.minY>this.maxY;};/** * Clears the bounds and resets. * */Bounds.prototype.clear=function clear(){this.updateID++;this.minX=Infinity;this.minY=Infinity;this.maxX=-Infinity;this.maxY=-Infinity;};/** * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle * It is not guaranteed that it will return tempRect * * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty * @returns {PIXI.Rectangle} A rectangle of the bounds */Bounds.prototype.getRectangle=function getRectangle(rect){if(this.minX>this.maxX||this.minY>this.maxY){return _math.Rectangle.EMPTY;}rect=rect||new _math.Rectangle(0,0,1,1);rect.x=this.minX;rect.y=this.minY;rect.width=this.maxX-this.minX;rect.height=this.maxY-this.minY;return rect;};/** * This function should be inlined when its possible. * * @param {PIXI.Point} point - The point to add. */Bounds.prototype.addPoint=function addPoint(point){this.minX=Math.min(this.minX,point.x);this.maxX=Math.max(this.maxX,point.x);this.minY=Math.min(this.minY,point.y);this.maxY=Math.max(this.maxY,point.y);};/** * Adds a quad, not transformed * * @param {Float32Array} vertices - The verts to add. */Bounds.prototype.addQuad=function addQuad(vertices){var minX=this.minX;var minY=this.minY;var maxX=this.maxX;var maxY=this.maxY;var x=vertices[0];var y=vertices[1];minX=xmaxX?x:maxX;maxY=y>maxY?y:maxY;x=vertices[2];y=vertices[3];minX=xmaxX?x:maxX;maxY=y>maxY?y:maxY;x=vertices[4];y=vertices[5];minX=xmaxX?x:maxX;maxY=y>maxY?y:maxY;x=vertices[6];y=vertices[7];minX=xmaxX?x:maxX;maxY=y>maxY?y:maxY;this.minX=minX;this.minY=minY;this.maxX=maxX;this.maxY=maxY;};/** * Adds sprite frame, transformed. * * @param {PIXI.TransformBase} transform - TODO * @param {number} x0 - TODO * @param {number} y0 - TODO * @param {number} x1 - TODO * @param {number} y1 - TODO */Bounds.prototype.addFrame=function addFrame(transform,x0,y0,x1,y1){var matrix=transform.worldTransform;var a=matrix.a;var b=matrix.b;var c=matrix.c;var d=matrix.d;var tx=matrix.tx;var ty=matrix.ty;var minX=this.minX;var minY=this.minY;var maxX=this.maxX;var maxY=this.maxY;var x=a*x0+c*y0+tx;var y=b*x0+d*y0+ty;minX=xmaxX?x:maxX;maxY=y>maxY?y:maxY;x=a*x1+c*y0+tx;y=b*x1+d*y0+ty;minX=xmaxX?x:maxX;maxY=y>maxY?y:maxY;x=a*x0+c*y1+tx;y=b*x0+d*y1+ty;minX=xmaxX?x:maxX;maxY=y>maxY?y:maxY;x=a*x1+c*y1+tx;y=b*x1+d*y1+ty;minX=xmaxX?x:maxX;maxY=y>maxY?y:maxY;this.minX=minX;this.minY=minY;this.maxX=maxX;this.maxY=maxY;};/** * Add an array of vertices * * @param {PIXI.TransformBase} transform - TODO * @param {Float32Array} vertices - TODO * @param {number} beginOffset - TODO * @param {number} endOffset - TODO */Bounds.prototype.addVertices=function addVertices(transform,vertices,beginOffset,endOffset){var matrix=transform.worldTransform;var a=matrix.a;var b=matrix.b;var c=matrix.c;var d=matrix.d;var tx=matrix.tx;var ty=matrix.ty;var minX=this.minX;var minY=this.minY;var maxX=this.maxX;var maxY=this.maxY;for(var i=beginOffset;imaxX?x:maxX;maxY=y>maxY?y:maxY;}this.minX=minX;this.minY=minY;this.maxX=maxX;this.maxY=maxY;};/** * Adds other Bounds * * @param {PIXI.Bounds} bounds - TODO */Bounds.prototype.addBounds=function addBounds(bounds){var minX=this.minX;var minY=this.minY;var maxX=this.maxX;var maxY=this.maxY;this.minX=bounds.minXmaxX?bounds.maxX:maxX;this.maxY=bounds.maxY>maxY?bounds.maxY:maxY;};/** * Adds other Bounds, masked with Bounds * * @param {PIXI.Bounds} bounds - TODO * @param {PIXI.Bounds} mask - TODO */Bounds.prototype.addBoundsMask=function addBoundsMask(bounds,mask){var _minX=bounds.minX>mask.minX?bounds.minX:mask.minX;var _minY=bounds.minY>mask.minY?bounds.minY:mask.minY;var _maxX=bounds.maxXmaxX?_maxX:maxX;this.maxY=_maxY>maxY?_maxY:maxY;}};/** * Adds other Bounds, masked with Rectangle * * @param {PIXI.Bounds} bounds - TODO * @param {PIXI.Rectangle} area - TODO */Bounds.prototype.addBoundsArea=function addBoundsArea(bounds,area){var _minX=bounds.minX>area.x?bounds.minX:area.x;var _minY=bounds.minY>area.y?bounds.minY:area.y;var _maxX=bounds.maxXmaxX?_maxX:maxX;this.maxY=_maxY>maxY?_maxY:maxY;}};return Bounds;}();exports.default=Bounds;},{"../math":66}],44:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i1){// loop through the arguments property and add all children // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes for(var i=0;ithis.children.length){throw new Error(child+'addChildAt: The index '+index+' supplied is out of bounds '+this.children.length);}if(child.parent){child.parent.removeChild(child);}child.parent=this;this.children.splice(index,0,child);// TODO - lets either do all callbacks or all events.. not both! this.onChildrenChange(index);child.emit('added',this);return child;};/** * Swaps the position of 2 Display Objects within this container. * * @param {PIXI.DisplayObject} child - First display object to swap * @param {PIXI.DisplayObject} child2 - Second display object to swap */Container.prototype.swapChildren=function swapChildren(child,child2){if(child===child2){return;}var index1=this.getChildIndex(child);var index2=this.getChildIndex(child2);this.children[index1]=child2;this.children[index2]=child;this.onChildrenChange(index1=this.children.length){throw new Error('The supplied index is out of bounds');}var currentIndex=this.getChildIndex(child);(0,_utils.removeItems)(this.children,currentIndex,1);// remove from old position this.children.splice(index,0,child);// add at new position this.onChildrenChange(index);};/** * Returns the child at the specified index * * @param {number} index - The index to get the child at * @return {PIXI.DisplayObject} The child at the given index, if any. */Container.prototype.getChildAt=function getChildAt(index){if(index<0||index>=this.children.length){throw new Error('getChildAt: Index ('+index+') does not exist.');}return this.children[index];};/** * Removes one or more children from the container. * * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove * @return {PIXI.DisplayObject} The first child that was removed. */Container.prototype.removeChild=function removeChild(child){var argumentsLength=arguments.length;// if there is only one argument we can bypass looping through the them if(argumentsLength>1){// loop through the arguments property and add all children // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes for(var i=0;i0&&range<=end){removed=this.children.splice(begin,range);for(var i=0;i} * @private */// TODO - _webgl should use a prototype object, not a random undocumented object... _this._webGL={};/** * Whether this shape is being used as a mask. * * @member {boolean} */_this.isMask=false;/** * The bounds' padding used for bounds calculation. * * @member {number} */_this.boundsPadding=0;/** * A cache of the local bounds to prevent recalculation. * * @member {PIXI.Rectangle} * @private */_this._localBounds=new _Bounds2.default();/** * Used to detect if the graphics object has changed. If this is set to true then the graphics * object will be recalculated. * * @member {boolean} * @private */_this.dirty=0;/** * Used to detect if we need to do a fast rect check using the id compare method * @type {Number} */_this.fastRectDirty=-1;/** * Used to detect if we clear the graphics webGL data * @type {Number} */_this.clearDirty=0;/** * Used to detect if we we need to recalculate local bounds * @type {Number} */_this.boundsDirty=-1;/** * Used to detect if the cached sprite object needs to be updated. * * @member {boolean} * @private */_this.cachedSpriteDirty=false;_this._spriteRect=null;_this._fastRect=false;/** * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. * This is useful if your graphics element does not change often, as it will speed up the rendering * of the object in exchange for taking up texture memory. It is also useful if you need the graphics * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if * you are constantly redrawing the graphics element. * * @name cacheAsBitmap * @member {boolean} * @memberof PIXI.Graphics# * @default false */return _this;}/** * Creates a new Graphics object with the same values as this one. * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) * * @return {PIXI.Graphics} A clone of the graphics object */Graphics.prototype.clone=function clone(){var clone=new Graphics();clone.renderable=this.renderable;clone.fillAlpha=this.fillAlpha;clone.lineWidth=this.lineWidth;clone.lineColor=this.lineColor;clone.tint=this.tint;clone.blendMode=this.blendMode;clone.isMask=this.isMask;clone.boundsPadding=this.boundsPadding;clone.dirty=0;clone.cachedSpriteDirty=this.cachedSpriteDirty;// copy graphics data for(var i=0;ib2*a1);}this.dirty++;return this;};/** * The arc method creates an arc/curve (used to create circles, or parts of circles). * * @param {number} cx - The x-coordinate of the center of the circle * @param {number} cy - The y-coordinate of the center of the circle * @param {number} radius - The radius of the circle * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position * of the arc's circle) * @param {number} endAngle - The ending angle, in radians * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be * counter-clockwise or clockwise. False is default, and indicates clockwise, while true * indicates counter-clockwise. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */Graphics.prototype.arc=function arc(cx,cy,radius,startAngle,endAngle){var anticlockwise=arguments.length<=5||arguments[5]===undefined?false:arguments[5];if(startAngle===endAngle){return this;}if(!anticlockwise&&endAngle<=startAngle){endAngle+=Math.PI*2;}else if(anticlockwise&&startAngle<=endAngle){startAngle+=Math.PI*2;}var sweep=endAngle-startAngle;var segs=Math.ceil(Math.abs(sweep)/(Math.PI*2))*40;if(sweep===0){return this;}var startX=cx+Math.cos(startAngle)*radius;var startY=cy+Math.sin(startAngle)*radius;// If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. var points=this.currentPath?this.currentPath.shape.points:null;if(points){if(points[points.length-2]!==startX||points[points.length-1]!==startY){points.push(startX,startY);}}else{this.moveTo(startX,startY);points=this.currentPath.shape.points;}var theta=sweep/(segs*2);var theta2=theta*2;var cTheta=Math.cos(theta);var sTheta=Math.sin(theta);var segMinus=segs-1;var remainder=segMinus%1/segMinus;for(var i=0;i<=segMinus;++i){var real=i+remainder*i;var angle=theta+startAngle+theta2*real;var c=Math.cos(angle);var s=-Math.sin(angle);points.push((cTheta*c+sTheta*s)*radius+cx,(cTheta*-s+sTheta*c)*radius+cy);}this.dirty++;return this;};/** * Specifies a simple one-color fill that subsequent calls to other Graphics methods * (such as lineTo() or drawCircle()) use when drawing. * * @param {number} [color=0] - the color of the fill * @param {number} [alpha=1] - the alpha of the fill * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */Graphics.prototype.beginFill=function beginFill(){var color=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var alpha=arguments.length<=1||arguments[1]===undefined?1:arguments[1];this.filling=true;this.fillColor=color;this.fillAlpha=alpha;if(this.currentPath){if(this.currentPath.shape.points.length<=2){this.currentPath.fill=this.filling;this.currentPath.fillColor=this.fillColor;this.currentPath.fillAlpha=this.fillAlpha;}}return this;};/** * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. * * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */Graphics.prototype.endFill=function endFill(){this.filling=false;this.fillColor=null;this.fillAlpha=1;return this;};/** * * @param {number} x - The X coord of the top-left of the rectangle * @param {number} y - The Y coord of the top-left of the rectangle * @param {number} width - The width of the rectangle * @param {number} height - The height of the rectangle * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */Graphics.prototype.drawRect=function drawRect(x,y,width,height){this.drawShape(new _math.Rectangle(x,y,width,height));return this;};/** * * @param {number} x - The X coord of the top-left of the rectangle * @param {number} y - The Y coord of the top-left of the rectangle * @param {number} width - The width of the rectangle * @param {number} height - The height of the rectangle * @param {number} radius - Radius of the rectangle corners * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */Graphics.prototype.drawRoundedRect=function drawRoundedRect(x,y,width,height,radius){this.drawShape(new _math.RoundedRectangle(x,y,width,height,radius));return this;};/** * Draws a circle. * * @param {number} x - The X coordinate of the center of the circle * @param {number} y - The Y coordinate of the center of the circle * @param {number} radius - The radius of the circle * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */Graphics.prototype.drawCircle=function drawCircle(x,y,radius){this.drawShape(new _math.Circle(x,y,radius));return this;};/** * Draws an ellipse. * * @param {number} x - The X coordinate of the center of the ellipse * @param {number} y - The Y coordinate of the center of the ellipse * @param {number} width - The half width of the ellipse * @param {number} height - The half height of the ellipse * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */Graphics.prototype.drawEllipse=function drawEllipse(x,y,width,height){this.drawShape(new _math.Ellipse(x,y,width,height));return this;};/** * Draws a polygon using the given path. * * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls */Graphics.prototype.drawPolygon=function drawPolygon(path){// prevents an argument assignment deopt // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments var points=path;var closed=true;if(points instanceof _math.Polygon){closed=points.closed;points=points.points;}if(!Array.isArray(points)){// prevents an argument leak deopt // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments points=new Array(arguments.length);for(var i=0;i0){this.lineWidth=0;this.filling=false;this.boundsDirty=-1;this.dirty++;this.clearDirty++;this.graphicsData.length=0;}this.currentPath=null;this._spriteRect=null;return this;};/** * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and * masked with gl.scissor. * * @returns {boolean} True if only 1 rect. */Graphics.prototype.isFastRect=function isFastRect(){return this.graphicsData.length===1&&this.graphicsData[0].shape.type===_const.SHAPES.RECT&&!this.graphicsData[0].lineWidth;};/** * Renders the object using the WebGL renderer * * @private * @param {PIXI.WebGLRenderer} renderer - The renderer */Graphics.prototype._renderWebGL=function _renderWebGL(renderer){// if the sprite is not visible or the alpha is 0 then no need to render this element if(this.dirty!==this.fastRectDirty){this.fastRectDirty=this.dirty;this._fastRect=this.isFastRect();}// TODO this check can be moved to dirty? if(this._fastRect){this._renderSpriteRect(renderer);}else{renderer.setObjectRenderer(renderer.plugins.graphics);renderer.plugins.graphics.render(this);}};/** * Renders a sprite rectangle. * * @private * @param {PIXI.WebGLRenderer} renderer - The renderer */Graphics.prototype._renderSpriteRect=function _renderSpriteRect(renderer){var rect=this.graphicsData[0].shape;if(!this._spriteRect){if(!Graphics._SPRITE_TEXTURE){Graphics._SPRITE_TEXTURE=_RenderTexture2.default.create(10,10);var canvas=document.createElement('canvas');canvas.width=10;canvas.height=10;var context=canvas.getContext('2d');context.fillStyle='white';context.fillRect(0,0,10,10);Graphics._SPRITE_TEXTURE=_Texture2.default.fromCanvas(canvas);}this._spriteRect=new _Sprite2.default(Graphics._SPRITE_TEXTURE);}if(this.tint===0xffffff){this._spriteRect.tint=this.graphicsData[0].fillColor;}else{var t1=tempColor1;var t2=tempColor2;(0,_utils.hex2rgb)(this.graphicsData[0].fillColor,t1);(0,_utils.hex2rgb)(this.tint,t2);t1[0]*=t2[0];t1[1]*=t2[1];t1[2]*=t2[2];this._spriteRect.tint=(0,_utils.rgb2hex)(t1);}this._spriteRect.alpha=this.graphicsData[0].fillAlpha;this._spriteRect.worldAlpha=this.worldAlpha*this._spriteRect.alpha;Graphics._SPRITE_TEXTURE._frame.width=rect.width;Graphics._SPRITE_TEXTURE._frame.height=rect.height;this._spriteRect.transform.worldTransform=this.transform.worldTransform;this._spriteRect.anchor.set(-rect.x/rect.width,-rect.y/rect.height);this._spriteRect._onAnchorUpdate();this._spriteRect._renderWebGL(renderer);};/** * Renders the object using the Canvas renderer * * @private * @param {PIXI.CanvasRenderer} renderer - The renderer */Graphics.prototype._renderCanvas=function _renderCanvas(renderer){if(this.isMask===true){return;}renderer.plugins.graphics.render(this);};/** * Retrieves the bounds of the graphic shape as a rectangle object * * @private */Graphics.prototype._calculateBounds=function _calculateBounds(){if(this.boundsDirty!==this.dirty){this.boundsDirty=this.dirty;this.updateLocalBounds();this.cachedSpriteDirty=true;}var lb=this._localBounds;this._bounds.addFrame(this.transform,lb.minX,lb.minY,lb.maxX,lb.maxY);};/** * Tests if a point is inside this graphics object * * @param {PIXI.Point} point - the point to test * @return {boolean} the result of the test */Graphics.prototype.containsPoint=function containsPoint(point){this.worldTransform.applyInverse(point,tempPoint);var graphicsData=this.graphicsData;for(var i=0;imaxX?x+w:maxX;minY=ymaxY?y+h:maxY;}else if(type===_const.SHAPES.CIRC){x=shape.x;y=shape.y;w=shape.radius+lineWidth/2;h=shape.radius+lineWidth/2;minX=x-wmaxX?x+w:maxX;minY=y-hmaxY?y+h:maxY;}else if(type===_const.SHAPES.ELIP){x=shape.x;y=shape.y;w=shape.width+lineWidth/2;h=shape.height+lineWidth/2;minX=x-wmaxX?x+w:maxX;minY=y-hmaxY?y+h:maxY;}else{// POLY var points=shape.points;var x2=0;var y2=0;var dx=0;var dy=0;var rw=0;var rh=0;var cx=0;var cy=0;for(var j=0;j+2maxX?cx+rw:maxX;minY=cy-rhmaxY?cy+rh:maxY;}}}}else{minX=0;maxX=0;minY=0;maxY=0;}var padding=this.boundsPadding;this._localBounds.minX=minX-padding;this._localBounds.maxX=maxX+padding*2;this._localBounds.minY=minY-padding;this._localBounds.maxY=maxY+padding*2;};/** * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. * * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. * @return {PIXI.GraphicsData} The generated GraphicsData object. */Graphics.prototype.drawShape=function drawShape(shape){if(this.currentPath){// check current path! if(this.currentPath.shape.points.length<=2){this.graphicsData.pop();}}this.currentPath=null;var data=new _GraphicsData2.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,shape);this.graphicsData.push(data);if(data.type===_const.SHAPES.POLY){data.shape.closed=data.shape.closed||this.filling;this.currentPath=data;}this.dirty++;return data;};/** * Generates a canvas texture. * * @param {number} scaleMode - The scale mode of the texture. * @param {number} resolution - The resolution of the texture. * @return {PIXI.Texture} The new texture. */Graphics.prototype.generateCanvasTexture=function generateCanvasTexture(scaleMode){var resolution=arguments.length<=1||arguments[1]===undefined?1:arguments[1];var bounds=this.getLocalBounds();var canvasBuffer=_RenderTexture2.default.create(bounds.width,bounds.height,scaleMode,resolution);if(!canvasRenderer){canvasRenderer=new _CanvasRenderer2.default();}tempMatrix.tx=-bounds.x;tempMatrix.ty=-bounds.y;canvasRenderer.render(this,canvasBuffer,false,tempMatrix);var texture=_Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas,scaleMode);texture.baseTexture.resolution=resolution;texture.baseTexture.update();return texture;};/** * Closes the current path. * * @return {PIXI.Graphics} Returns itself. */Graphics.prototype.closePath=function closePath(){// ok so close path assumes next one is a hole! var currentPath=this.currentPath;if(currentPath&¤tPath.shape){currentPath.shape.close();}return this;};/** * Adds a hole in the current path. * * @return {PIXI.Graphics} Returns itself. */Graphics.prototype.addHole=function addHole(){// this is a hole! var hole=this.graphicsData.pop();this.currentPath=this.graphicsData[this.graphicsData.length-1];this.currentPath.addHole(hole.shape);this.currentPath=null;return this;};/** * Destroys the Graphics object. * * @param {object|boolean} [options] - Options parameter. A boolean will act as if all * options have been set to that value * @param {boolean} [options.children=false] - if set to true, all the children will have * their destroy method called as well. 'options' will be passed on to those calls. */Graphics.prototype.destroy=function destroy(options){_Container.prototype.destroy.call(this,options);// destroy each of the GraphicsData objects for(var i=0;i https://github.com/mattdesl/ * for creating the original pixi version! * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they * now share 4 bytes on the vertex buffer * * Heavily inspired by LibGDX's CanvasGraphicsRenderer: * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasGraphicsRenderer.java *//** * Renderer dedicated to drawing and batching graphics objects. * * @class * @private * @memberof PIXI */var CanvasGraphicsRenderer=function(){/** * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. */function CanvasGraphicsRenderer(renderer){_classCallCheck(this,CanvasGraphicsRenderer);this.renderer=renderer;}/** * Renders a Graphics object to a canvas. * * @param {PIXI.Graphics} graphics - the actual graphics object to render */CanvasGraphicsRenderer.prototype.render=function render(graphics){var renderer=this.renderer;var context=renderer.context;var worldAlpha=graphics.worldAlpha;var transform=graphics.transform.worldTransform;var resolution=renderer.resolution;// if the tint has changed, set the graphics object to dirty. if(this._prevTint!==this.tint){this.dirty=true;}context.setTransform(transform.a*resolution,transform.b*resolution,transform.c*resolution,transform.d*resolution,transform.tx*resolution,transform.ty*resolution);if(graphics.dirty){this.updateGraphicsTint(graphics);graphics.dirty=false;}renderer.setBlendMode(graphics.blendMode);for(var i=0;imaxRadius?maxRadius:radius;context.beginPath();context.moveTo(rx,ry+radius);context.lineTo(rx,ry+height-radius);context.quadraticCurveTo(rx,ry+height,rx+radius,ry+height);context.lineTo(rx+width-radius,ry+height);context.quadraticCurveTo(rx+width,ry+height,rx+width,ry+height-radius);context.lineTo(rx+width,ry+radius);context.quadraticCurveTo(rx+width,ry,rx+width-radius,ry);context.lineTo(rx+radius,ry);context.quadraticCurveTo(rx,ry,rx,ry+radius);context.closePath();if(data.fillColor||data.fillColor===0){context.globalAlpha=data.fillAlpha*worldAlpha;context.fillStyle='#'+('00000'+(fillColor|0).toString(16)).substr(-6);context.fill();}if(data.lineWidth){context.globalAlpha=data.lineAlpha*worldAlpha;context.strokeStyle='#'+('00000'+(lineColor|0).toString(16)).substr(-6);context.stroke();}}}};/** * Updates the tint of a graphics object * * @private * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated */CanvasGraphicsRenderer.prototype.updateGraphicsTint=function updateGraphicsTint(graphics){graphics._prevTint=graphics.tint;var tintR=(graphics.tint>>16&0xFF)/255;var tintG=(graphics.tint>>8&0xFF)/255;var tintB=(graphics.tint&0xFF)/255;for(var i=0;i>16&0xFF)/255*tintR*255<<16)+((fillColor>>8&0xFF)/255*tintG*255<<8)+(fillColor&0xFF)/255*tintB*255;data._lineTint=((lineColor>>16&0xFF)/255*tintR*255<<16)+((lineColor>>8&0xFF)/255*tintG*255<<8)+(lineColor&0xFF)/255*tintB*255;}};/** * Renders a polygon. * * @param {PIXI.Point[]} points - The points to render * @param {boolean} close - Should the polygon be closed * @param {CanvasRenderingContext2D} context - The rendering context to use */CanvasGraphicsRenderer.prototype.renderPolygon=function renderPolygon(points,close,context){context.moveTo(points[0],points[1]);for(var j=1;j320000){webGLData=this.graphicsDataPool.pop()||new _WebGLGraphicsData2.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState);webGLData.reset(type);gl.data.push(webGLData);}webGLData.dirty=true;return webGLData;};return GraphicsRenderer;}(_ObjectRenderer3.default);exports.default=GraphicsRenderer;_WebGLRenderer2.default.registerPlugin('graphics',GraphicsRenderer);},{"../../const":42,"../../renderers/webgl/WebGLRenderer":80,"../../renderers/webgl/utils/ObjectRenderer":90,"../../utils":117,"./WebGLGraphicsData":54,"./shaders/PrimitiveShader":55,"./utils/buildCircle":56,"./utils/buildPoly":58,"./utils/buildRectangle":59,"./utils/buildRoundedRectangle":60}],54:[function(require,module,exports){'use strict';exports.__esModule=true;var _pixiGlCore=require('pixi-gl-core');var _pixiGlCore2=_interopRequireDefault(_pixiGlCore);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/** * An object containing WebGL specific properties to be used by the WebGL renderer * * @class * @private * @memberof PIXI */var WebGLGraphicsData=function(){/** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader * @param {object} attribsState - The state for the VAO */function WebGLGraphicsData(gl,shader,attribsState){_classCallCheck(this,WebGLGraphicsData);/** * The current WebGL drawing context * * @member {WebGLRenderingContext} */this.gl=gl;// TODO does this need to be split before uploading?? /** * An array of color components (r,g,b) * @member {number[]} */this.color=[0,0,0];// color split! /** * An array of points to draw * @member {PIXI.Point[]} */this.points=[];/** * The indices of the vertices * @member {number[]} */this.indices=[];/** * The main buffer * @member {WebGLBuffer} */this.buffer=_pixiGlCore2.default.GLBuffer.createVertexBuffer(gl);/** * The index buffer * @member {WebGLBuffer} */this.indexBuffer=_pixiGlCore2.default.GLBuffer.createIndexBuffer(gl);/** * Whether this graphics is dirty or not * @member {boolean} */this.dirty=true;this.glPoints=null;this.glIndices=null;/** * * @member {PIXI.Shader} */this.shader=shader;this.vao=new _pixiGlCore2.default.VertexArrayObject(gl,attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer,shader.attributes.aVertexPosition,gl.FLOAT,false,4*6,0).addAttribute(this.buffer,shader.attributes.aColor,gl.FLOAT,false,4*6,2*4);}/** * Resets the vertices and the indices */WebGLGraphicsData.prototype.reset=function reset(){this.points.length=0;this.indices.length=0;};/** * Binds the buffers and uploads the data */WebGLGraphicsData.prototype.upload=function upload(){this.glPoints=new Float32Array(this.points);this.buffer.upload(this.glPoints);this.glIndices=new Uint16Array(this.indices);this.indexBuffer.upload(this.glIndices);this.dirty=false;};/** * Empties all the data */WebGLGraphicsData.prototype.destroy=function destroy(){this.color=null;this.points=null;this.indices=null;this.vao.destroy();this.buffer.destroy();this.indexBuffer.destroy();this.gl=null;this.buffer=null;this.indexBuffer=null;this.glPoints=null;this.glIndices=null;};return WebGLGraphicsData;}();exports.default=WebGLGraphicsData;},{"pixi-gl-core":12}],55:[function(require,module,exports){'use strict';exports.__esModule=true;var _Shader2=require('../../../Shader');var _Shader3=_interopRequireDefault(_Shader2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. * * @class * @memberof PIXI * @extends PIXI.Shader */var PrimitiveShader=function(_Shader){_inherits(PrimitiveShader,_Shader);/** * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. */function PrimitiveShader(gl){_classCallCheck(this,PrimitiveShader);return _possibleConstructorReturn(this,_Shader.call(this,gl,// vertex shader ['attribute vec2 aVertexPosition;','attribute vec4 aColor;','uniform mat3 translationMatrix;','uniform mat3 projectionMatrix;','uniform float alpha;','uniform vec3 tint;','varying vec4 vColor;','void main(void){',' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);',' vColor = aColor * vec4(tint * alpha, alpha);','}'].join('\n'),// fragment shader ['varying vec4 vColor;','void main(void){',' gl_FragColor = vColor;','}'].join('\n')));}return PrimitiveShader;}(_Shader3.default);exports.default=PrimitiveShader;},{"../../../Shader":41}],56:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=buildCircle;var _buildLine=require('./buildLine');var _buildLine2=_interopRequireDefault(_buildLine);var _const=require('../../../const');var _utils=require('../../../utils');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/** * Builds a circle to draw * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw * @param {object} webGLData - an object containing all the webGL-specific information to create this shape */function buildCircle(graphicsData,webGLData){// need to convert points to a nice regular data var circleData=graphicsData.shape;var x=circleData.x;var y=circleData.y;var width=void 0;var height=void 0;// TODO - bit hacky?? if(graphicsData.type===_const.SHAPES.CIRC){width=circleData.radius;height=circleData.radius;}else{width=circleData.width;height=circleData.height;}var totalSegs=Math.floor(30*Math.sqrt(circleData.radius))||Math.floor(15*Math.sqrt(circleData.width+circleData.height));var seg=Math.PI*2/totalSegs;if(graphicsData.fill){var color=(0,_utils.hex2rgb)(graphicsData.fillColor);var alpha=graphicsData.fillAlpha;var r=color[0]*alpha;var g=color[1]*alpha;var b=color[2]*alpha;var verts=webGLData.points;var indices=webGLData.indices;var vecPos=verts.length/6;indices.push(vecPos);for(var i=0;i196*width*width){perp3x=perpx-perp2x;perp3y=perpy-perp2y;dist=Math.sqrt(perp3x*perp3x+perp3y*perp3y);perp3x/=dist;perp3y/=dist;perp3x*=width;perp3y*=width;verts.push(p2x-perp3x,p2y-perp3y);verts.push(r,g,b,alpha);verts.push(p2x+perp3x,p2y+perp3y);verts.push(r,g,b,alpha);verts.push(p2x-perp3x,p2y-perp3y);verts.push(r,g,b,alpha);indexCount++;}else{verts.push(px,py);verts.push(r,g,b,alpha);verts.push(p2x-(px-p2x),p2y-(py-p2y));verts.push(r,g,b,alpha);}}p1x=points[(length-2)*2];p1y=points[(length-2)*2+1];p2x=points[(length-1)*2];p2y=points[(length-1)*2+1];perpx=-(p1y-p2y);perpy=p1x-p2x;dist=Math.sqrt(perpx*perpx+perpy*perpy);perpx/=dist;perpy/=dist;perpx*=width;perpy*=width;verts.push(p2x-perpx,p2y-perpy);verts.push(r,g,b,alpha);verts.push(p2x+perpx,p2y+perpy);verts.push(r,g,b,alpha);indices.push(indexStart);for(var _i=0;_i=6){var holeArray=[];// Process holes.. var holes=graphicsData.holes;for(var i=0;i0){(0,_buildLine2.default)(graphicsData,webGLData);}}},{"../../../utils":117,"./buildLine":57,"earcut":2}],59:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=buildRectangle;var _buildLine=require('./buildLine');var _buildLine2=_interopRequireDefault(_buildLine);var _utils=require('../../../utils');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/** * Builds a rectangle to draw * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties * @param {object} webGLData - an object containing all the webGL-specific information to create this shape */function buildRectangle(graphicsData,webGLData){// --- // // need to convert points to a nice regular data // var rectData=graphicsData.shape;var x=rectData.x;var y=rectData.y;var width=rectData.width;var height=rectData.height;if(graphicsData.fill){var color=(0,_utils.hex2rgb)(graphicsData.fillColor);var alpha=graphicsData.fillAlpha;var r=color[0]*alpha;var g=color[1]*alpha;var b=color[2]*alpha;var verts=webGLData.points;var indices=webGLData.indices;var vertPos=verts.length/6;// start verts.push(x,y);verts.push(r,g,b,alpha);verts.push(x+width,y);verts.push(r,g,b,alpha);verts.push(x,y+height);verts.push(r,g,b,alpha);verts.push(x+width,y+height);verts.push(r,g,b,alpha);// insert 2 dead triangles.. indices.push(vertPos,vertPos,vertPos+1,vertPos+2,vertPos+3,vertPos+3);}if(graphicsData.lineWidth){var tempPoints=graphicsData.points;graphicsData.points=[x,y,x+width,y,x+width,y+height,x,y+height,x,y];(0,_buildLine2.default)(graphicsData,webGLData);graphicsData.points=tempPoints;}}},{"../../../utils":117,"./buildLine":57}],60:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=buildRoundedRectangle;var _earcut=require('earcut');var _earcut2=_interopRequireDefault(_earcut);var _buildLine=require('./buildLine');var _buildLine2=_interopRequireDefault(_buildLine);var _utils=require('../../../utils');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/** * Builds a rounded rectangle to draw * * Ignored from docs since it is not directly exposed. * * @ignore * @private * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties * @param {object} webGLData - an object containing all the webGL-specific information to create this shape */function buildRoundedRectangle(graphicsData,webGLData){var rrectData=graphicsData.shape;var x=rrectData.x;var y=rrectData.y;var width=rrectData.width;var height=rrectData.height;var radius=rrectData.radius;var recPoints=[];recPoints.push(x,y+radius);quadraticBezierCurve(x,y+height-radius,x,y+height,x+radius,y+height,recPoints);quadraticBezierCurve(x+width-radius,y+height,x+width,y+height,x+width,y+height-radius,recPoints);quadraticBezierCurve(x+width,y+radius,x+width,y,x+width-radius,y,recPoints);quadraticBezierCurve(x+radius,y,x,y,x,y+radius+0.0000000001,recPoints);// this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. // TODO - fix this properly, this is not very elegant.. but it works for now. if(graphicsData.fill){var color=(0,_utils.hex2rgb)(graphicsData.fillColor);var alpha=graphicsData.fillAlpha;var r=color[0]*alpha;var g=color[1]*alpha;var b=color[2]*alpha;var verts=webGLData.points;var indices=webGLData.indices;var vecPos=verts.length/6;var triangles=(0,_earcut2.default)(recPoints,null,2);for(var i=0,j=triangles.length;i0){return 1;}return 0;}function init(){for(var i=0;i<16;i++){var row=[];mul.push(row);for(var j=0;j<16;j++){var _ux=signum(ux[i]*ux[j]+vx[i]*uy[j]);var _uy=signum(uy[i]*ux[j]+vy[i]*uy[j]);var _vx=signum(ux[i]*vx[j]+vx[i]*vy[j]);var _vy=signum(uy[i]*vx[j]+vy[i]*vy[j]);for(var k=0;k<16;k++){if(ux[k]===_ux&&uy[k]===_uy&&vx[k]===_vx&&vy[k]===_vy){row.push(k);break;}}}}for(var _i=0;_i<16;_i++){var mat=new _Matrix2.default();mat.set(ux[_i],uy[_i],vx[_i],vy[_i],0,0);tempMatrices.push(mat);}}init();/** * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, * D8 is the same but with diagonals. Used for texture rotations. * * Vector xX(i), xY(i) is U-axis of sprite with rotation i * Vector yY(i), yY(i) is V-axis of sprite with rotation i * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) * This is the small part of gameofbombs.com portal system. It works. * * @author Ivan @ivanpopelyshev * * @namespace PIXI.GroupD8 */var GroupD8={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function uX(ind){return ux[ind];},uY:function uY(ind){return uy[ind];},vX:function vX(ind){return vx[ind];},vY:function vY(ind){return vy[ind];},inv:function inv(rotation){if(rotation&8){return rotation&15;}return-rotation&7;},add:function add(rotationSecond,rotationFirst){return mul[rotationSecond][rotationFirst];},sub:function sub(rotationSecond,rotationFirst){return mul[rotationSecond][GroupD8.inv(rotationFirst)];},/** * Adds 180 degrees to rotation. Commutative operation. * * @method * @param {number} rotation - The number to rotate. * @returns {number} rotated number */rotate180:function rotate180(rotation){return rotation^4;},/** * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. * * @param {number} rotation - The number to check. * @returns {boolean} Whether or not the width/height should be swapped. */isSwapWidthHeight:function isSwapWidthHeight(rotation){return(rotation&3)===2;},/** * @param {number} dx - TODO * @param {number} dy - TODO * * @return {number} TODO */byDirection:function byDirection(dx,dy){if(Math.abs(dx)*2<=Math.abs(dy)){if(dy>=0){return GroupD8.S;}return GroupD8.N;}else if(Math.abs(dy)*2<=Math.abs(dx)){if(dx>0){return GroupD8.E;}return GroupD8.W;}else if(dy>0){if(dx>0){return GroupD8.SE;}return GroupD8.SW;}else if(dx>0){return GroupD8.NE;}return GroupD8.NW;},/** * Helps sprite to compensate texture packer rotation. * * @param {PIXI.Matrix} matrix - sprite world matrix * @param {number} rotation - The rotation factor to use. * @param {number} tx - sprite anchoring * @param {number} ty - sprite anchoring */matrixAppendRotationInv:function matrixAppendRotationInv(matrix,rotation){var tx=arguments.length<=2||arguments[2]===undefined?0:arguments[2];var ty=arguments.length<=3||arguments[3]===undefined?0:arguments[3];// Packer used "rotation", we use "inv(rotation)" var mat=tempMatrices[GroupD8.inv(rotation)];mat.tx=tx;mat.ty=ty;matrix.append(mat);}};exports.default=GroupD8;},{"./Matrix":63}],63:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i=0){transform.rotation+=transform.rotation<=0?Math.PI:-Math.PI;}transform.skew.x=transform.skew.y=0;}else{transform.skew.x=skewX;transform.skew.y=skewY;}// next set scale transform.scale.x=Math.sqrt(a*a+b*b);transform.scale.y=Math.sqrt(c*c+d*d);// next set position transform.position.x=this.tx;transform.position.y=this.ty;return transform;};/** * Inverts this matrix * * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */Matrix.prototype.invert=function invert(){var a1=this.a;var b1=this.b;var c1=this.c;var d1=this.d;var tx1=this.tx;var n=a1*d1-b1*c1;this.a=d1/n;this.b=-b1/n;this.c=-c1/n;this.d=a1/n;this.tx=(c1*this.ty-d1*tx1)/n;this.ty=-(a1*this.ty-b1*tx1)/n;return this;};/** * Resets this Matix to an identity (default) matrix. * * @return {PIXI.Matrix} This matrix. Good for chaining method calls. */Matrix.prototype.identity=function identity(){this.a=1;this.b=0;this.c=0;this.d=1;this.tx=0;this.ty=0;return this;};/** * Creates a new Matrix object with the same values as this one. * * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. */Matrix.prototype.clone=function clone(){var matrix=new Matrix();matrix.a=this.a;matrix.b=this.b;matrix.c=this.c;matrix.d=this.d;matrix.tx=this.tx;matrix.ty=this.ty;return matrix;};/** * Changes the values of the given matrix to be the same as the ones in this matrix * * @param {PIXI.Matrix} matrix - The matrix to copy from. * @return {PIXI.Matrix} The matrix given in parameter with its values updated. */Matrix.prototype.copy=function copy(matrix){matrix.a=this.a;matrix.b=this.b;matrix.c=this.c;matrix.d=this.d;matrix.tx=this.tx;matrix.ty=this.ty;return matrix;};/** * A default (identity) matrix * * @static * @const */_createClass(Matrix,null,[{key:'IDENTITY',get:function get(){return new Matrix();}/** * A temp matrix * * @static * @const */},{key:'TEMP_MATRIX',get:function get(){return new Matrix();}}]);return Matrix;}();exports.default=Matrix;},{"./Point":65}],64:[function(require,module,exports){"use strict";exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;iy!==yj>y&&x<(xj-xi)*((y-yi)/(yj-yi))+xi;if(intersect){inside=!inside;}}return inside;};return Polygon;}();exports.default=Polygon;},{"../../const":42,"../Point":65}],70:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i=this.x&&x=this.y&&yrectangle.x+rectangle.width){this.width=rectangle.width-this.x;if(this.width<0){this.width=0;}}if(this.y+this.height>rectangle.y+rectangle.height){this.height=rectangle.height-this.y;if(this.height<0){this.height=0;}}};/** * Enlarges this rectangle to include the passed rectangle. * * @param {PIXI.Rectangle} rect - The rectangle to include. */Rectangle.prototype.enlarge=function enlarge(rect){if(rect===Rectangle.EMPTY){return;}var x1=Math.min(this.x,rect.x);var x2=Math.max(this.x+this.width,rect.x+rect.width);var y1=Math.min(this.y,rect.y);var y2=Math.max(this.y+this.height,rect.y+rect.height);this.x=x1;this.width=x2-x1;this.y=y1;this.height=y2-y1;};_createClass(Rectangle,[{key:'left',get:function get(){return this.x;}/** * returns the right edge of the rectangle * * @member {number} * @memberof PIXI.Rectangle */},{key:'right',get:function get(){return this.x+this.width;}/** * returns the top edge of the rectangle * * @member {number} * @memberof PIXI.Rectangle */},{key:'top',get:function get(){return this.y;}/** * returns the bottom edge of the rectangle * * @member {number} * @memberof PIXI.Rectangle */},{key:'bottom',get:function get(){return this.y+this.height;}/** * A constant empty rectangle. * * @static * @constant */}],[{key:'EMPTY',get:function get(){return new Rectangle(0,0,0,0);}}]);return Rectangle;}();exports.default=Rectangle;},{"../../const":42}],71:[function(require,module,exports){'use strict';exports.__esModule=true;var _const=require('../../const');function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/** * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its * top-left corner point (x, y) and by its width and its height and its radius. * * @class * @memberof PIXI */var RoundedRectangle=function(){/** * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle * @param {number} [width=0] - The overall width of this rounded rectangle * @param {number} [height=0] - The overall height of this rounded rectangle * @param {number} [radius=20] - Controls the radius of the rounded corners */function RoundedRectangle(){var x=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var y=arguments.length<=1||arguments[1]===undefined?0:arguments[1];var width=arguments.length<=2||arguments[2]===undefined?0:arguments[2];var height=arguments.length<=3||arguments[3]===undefined?0:arguments[3];var radius=arguments.length<=4||arguments[4]===undefined?20:arguments[4];_classCallCheck(this,RoundedRectangle);/** * @member {number} * @default 0 */this.x=x;/** * @member {number} * @default 0 */this.y=y;/** * @member {number} * @default 0 */this.width=width;/** * @member {number} * @default 0 */this.height=height;/** * @member {number} * @default 20 */this.radius=radius;/** * The type of the object, mainly used to avoid `instanceof` checks * * @member {number} * @readonly * @default PIXI.SHAPES.RREC * @see PIXI.SHAPES */this.type=_const.SHAPES.RREC;}/** * Creates a clone of this Rounded Rectangle * * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle */RoundedRectangle.prototype.clone=function clone(){return new RoundedRectangle(this.x,this.y,this.width,this.height,this.radius);};/** * Checks whether the x and y coordinates given are contained within this Rounded Rectangle * * @param {number} x - The X coordinate of the point to test * @param {number} y - The Y coordinate of the point to test * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle */RoundedRectangle.prototype.contains=function contains(x,y){if(this.width<=0||this.height<=0){return false;}if(x>=this.x&&x<=this.x+this.width){if(y>=this.y&&y<=this.y+this.height){if(y>=this.y+this.radius&&y<=this.y+this.height-this.radius||x>=this.x+this.radius&&x<=this.x+this.width-this.radius){return true;}var dx=x-(this.x+this.radius);var dy=y-(this.y+this.radius);var radius2=this.radius*this.radius;if(dx*dx+dy*dy<=radius2){return true;}dx=x-(this.x+this.width-this.radius);if(dx*dx+dy*dy<=radius2){return true;}dy=y-(this.y+this.height-this.radius);if(dx*dx+dy*dy<=radius2){return true;}dx=x-(this.x+this.radius);if(dx*dx+dy*dy<=radius2){return true;}}}return false;};return RoundedRectangle;}();exports.default=RoundedRectangle;},{"../../const":42}],72:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i} */_this.blendModes=null;/** * The value of the preserveDrawingBuffer flag affects whether or not the contents of * the stencil buffer is retained after rendering. * * @member {boolean} */_this.preserveDrawingBuffer=options.preserveDrawingBuffer;/** * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every * frame to set the canvas background color. If the scene is transparent Pixi will use clearRect * to clear the canvas every frame. Disable this by setting this to false. For example if * your game has a canvas filling background image you often don't need this set. * * @member {boolean} * @default */_this.clearBeforeRender=options.clearBeforeRender;/** * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. * Handy for crisp pixel art and speed on legacy devices. * * @member {boolean} */_this.roundPixels=options.roundPixels;/** * The background color as a number. * * @member {number} * @private */_this._backgroundColor=0x000000;/** * The background color as an [R, G, B] array. * * @member {number[]} * @private */_this._backgroundColorRgba=[0,0,0,0];/** * The background color as a string. * * @member {string} * @private */_this._backgroundColorString='#000000';_this.backgroundColor=options.backgroundColor||_this._backgroundColor;// run bg color setter /** * This temporary display object used as the parent of the currently being rendered item * * @member {PIXI.DisplayObject} * @private */_this._tempDisplayObjectParent=new _Container2.default();/** * The last root object that the renderer tried to render. * * @member {PIXI.DisplayObject} * @private */_this._lastObjectRendered=_this._tempDisplayObjectParent;return _this;}/** * Resizes the canvas view to the specified width and height * * @param {number} width - the new width of the canvas view * @param {number} height - the new height of the canvas view */SystemRenderer.prototype.resize=function resize(width,height){this.width=width*this.resolution;this.height=height*this.resolution;this.view.width=this.width;this.view.height=this.height;if(this.autoResize){this.view.style.width=this.width/this.resolution+'px';this.view.style.height=this.height/this.resolution+'px';}};/** * Useful function that returns a texture of the display object that can then be used to create sprites * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. * * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from * @param {number} scaleMode - Should be one of the scaleMode consts * @param {number} resolution - The resolution / device pixel ratio of the texture being generated * @return {PIXI.Texture} a texture of the graphics object */SystemRenderer.prototype.generateTexture=function generateTexture(displayObject,scaleMode,resolution){var bounds=displayObject.getLocalBounds();var renderTexture=_RenderTexture2.default.create(bounds.width|0,bounds.height|0,scaleMode,resolution);tempMatrix.tx=-bounds.x;tempMatrix.ty=-bounds.y;this.render(displayObject,renderTexture,false,tempMatrix,true);return renderTexture;};/** * Removes everything from the renderer and optionally removes the Canvas DOM element. * * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. */SystemRenderer.prototype.destroy=function destroy(removeView){if(removeView&&this.view.parentNode){this.view.parentNode.removeChild(this.view);}this.type=_const.RENDERER_TYPE.UNKNOWN;this.width=0;this.height=0;this.view=null;this.resolution=0;this.transparent=false;this.autoResize=false;this.blendModes=null;this.preserveDrawingBuffer=false;this.clearBeforeRender=false;this.roundPixels=false;this._backgroundColor=0;this._backgroundColorRgba=null;this._backgroundColorString=null;this.backgroundColor=0;this._tempDisplayObjectParent=null;this._lastObjectRendered=null;};/** * The background color to fill if not transparent * * @member {number} * @memberof PIXI.SystemRenderer# */_createClass(SystemRenderer,[{key:'backgroundColor',get:function get(){return this._backgroundColor;}/** * Sets the background color. * * @param {number} value - The value to set to. */,set:function set(value){this._backgroundColor=value;this._backgroundColorString=(0,_utils.hex2string)(value);(0,_utils.hex2rgb)(value,this._backgroundColorRgba);}}]);return SystemRenderer;}(_eventemitter2.default);exports.default=SystemRenderer;},{"../const":42,"../display/Container":44,"../math":66,"../settings":97,"../textures/RenderTexture":108,"../utils":117,"eventemitter3":3}],73:[function(require,module,exports){'use strict';exports.__esModule=true;var _SystemRenderer2=require('../SystemRenderer');var _SystemRenderer3=_interopRequireDefault(_SystemRenderer2);var _CanvasMaskManager=require('./utils/CanvasMaskManager');var _CanvasMaskManager2=_interopRequireDefault(_CanvasMaskManager);var _CanvasRenderTarget=require('./utils/CanvasRenderTarget');var _CanvasRenderTarget2=_interopRequireDefault(_CanvasRenderTarget);var _mapCanvasBlendModesToPixi=require('./utils/mapCanvasBlendModesToPixi');var _mapCanvasBlendModesToPixi2=_interopRequireDefault(_mapCanvasBlendModesToPixi);var _utils=require('../../utils');var _const=require('../../const');var _settings=require('../../settings');var _settings2=_interopRequireDefault(_settings);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/** * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to * your DOM or you will not see anything :) * * @class * @memberof PIXI * @extends PIXI.SystemRenderer */var CanvasRenderer=function(_SystemRenderer){_inherits(CanvasRenderer,_SystemRenderer);/** * @param {number} [width=800] - the width of the canvas view * @param {number} [height=600] - the height of the canvas view * @param {object} [options] - The optional renderer parameters * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional * @param {boolean} [options.transparent=false] - If the render view is transparent, default false * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The * resolution of the renderer retina would be 2. * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or * not before the new render pass. * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area * (shown if not transparent). * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, * stopping pixel interpolation. */function CanvasRenderer(width,height){var options=arguments.length<=2||arguments[2]===undefined?{}:arguments[2];_classCallCheck(this,CanvasRenderer);var _this=_possibleConstructorReturn(this,_SystemRenderer.call(this,'Canvas',width,height,options));_this.type=_const.RENDERER_TYPE.CANVAS;/** * The canvas 2d context that everything is drawn with. * * @member {CanvasRenderingContext2D} */_this.rootContext=_this.view.getContext('2d',{alpha:_this.transparent});/** * Boolean flag controlling canvas refresh. * * @member {boolean} */_this.refresh=true;/** * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. * * @member {PIXI.CanvasMaskManager} */_this.maskManager=new _CanvasMaskManager2.default(_this);/** * The canvas property used to set the canvas smoothing property. * * @member {string} */_this.smoothProperty='imageSmoothingEnabled';if(!_this.rootContext.imageSmoothingEnabled){if(_this.rootContext.webkitImageSmoothingEnabled){_this.smoothProperty='webkitImageSmoothingEnabled';}else if(_this.rootContext.mozImageSmoothingEnabled){_this.smoothProperty='mozImageSmoothingEnabled';}else if(_this.rootContext.oImageSmoothingEnabled){_this.smoothProperty='oImageSmoothingEnabled';}else if(_this.rootContext.msImageSmoothingEnabled){_this.smoothProperty='msImageSmoothingEnabled';}}_this.initPlugins();_this.blendModes=(0,_mapCanvasBlendModesToPixi2.default)();_this._activeBlendMode=null;_this.context=null;_this.renderingToScreen=false;_this.resize(width,height);return _this;}/** * Renders the object to this canvas view * * @param {PIXI.DisplayObject} displayObject - The object to be rendered * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. * If unset, it will render to the root context. * @param {boolean} [clear=false] - Whether to clear the canvas before drawing * @param {PIXI.Transform} [transform] - A transformation to be applied * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform */CanvasRenderer.prototype.render=function render(displayObject,renderTexture,clear,transform,skipUpdateTransform){if(!this.view){return;}// can be handy to know! this.renderingToScreen=!renderTexture;this.emit('prerender');var rootResolution=this.resolution;if(renderTexture){renderTexture=renderTexture.baseTexture||renderTexture;if(!renderTexture._canvasRenderTarget){renderTexture._canvasRenderTarget=new _CanvasRenderTarget2.default(renderTexture.width,renderTexture.height,renderTexture.resolution);renderTexture.source=renderTexture._canvasRenderTarget.canvas;renderTexture.valid=true;}this.context=renderTexture._canvasRenderTarget.context;this.resolution=renderTexture._canvasRenderTarget.resolution;}else{this.context=this.rootContext;}var context=this.context;if(!renderTexture){this._lastObjectRendered=displayObject;}if(!skipUpdateTransform){// update the scene graph var cacheParent=displayObject.parent;var tempWt=this._tempDisplayObjectParent.transform.worldTransform;if(transform){transform.copy(tempWt);}else{tempWt.identity();}displayObject.parent=this._tempDisplayObjectParent;displayObject.updateTransform();displayObject.parent=cacheParent;// displayObject.hitArea = //TODO add a temp hit area }context.setTransform(1,0,0,1,0,0);context.globalAlpha=1;context.globalCompositeOperation=this.blendModes[_const.BLEND_MODES.NORMAL];if(navigator.isCocoonJS&&this.view.screencanvas){context.fillStyle='black';context.clear();}if(clear!==undefined?clear:this.clearBeforeRender){if(this.renderingToScreen){if(this.transparent){context.clearRect(0,0,this.width,this.height);}else{context.fillStyle=this._backgroundColorString;context.fillRect(0,0,this.width,this.height);}}// else { // TODO: implement background for CanvasRenderTarget or RenderTexture? // } }// TODO RENDER TARGET STUFF HERE.. var tempContext=this.context;this.context=context;displayObject.renderCanvas(this);this.context=tempContext;this.resolution=rootResolution;this.emit('postrender');};/** * Clear the canvas of renderer. * * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. */CanvasRenderer.prototype.clear=function clear(clearColor){var context=this.context;clearColor=clearColor||this._backgroundColorString;if(!this.transparent&&clearColor){context.fillStyle=clearColor;context.fillRect(0,0,this.width,this.height);}else{context.clearRect(0,0,this.width,this.height);}};/** * Sets the blend mode of the renderer. * * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. */CanvasRenderer.prototype.setBlendMode=function setBlendMode(blendMode){if(this._activeBlendMode===blendMode){return;}this._activeBlendMode=blendMode;this.context.globalCompositeOperation=this.blendModes[blendMode];};/** * Removes everything from the renderer and optionally removes the Canvas DOM element. * * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. */CanvasRenderer.prototype.destroy=function destroy(removeView){this.destroyPlugins();// call the base destroy _SystemRenderer.prototype.destroy.call(this,removeView);this.context=null;this.refresh=true;this.maskManager.destroy();this.maskManager=null;this.smoothProperty=null;};/** * Resizes the canvas view to the specified width and height. * * @extends PIXI.SystemRenderer#resize * * @param {number} width - The new width of the canvas view * @param {number} height - The new height of the canvas view */CanvasRenderer.prototype.resize=function resize(width,height){_SystemRenderer.prototype.resize.call(this,width,height);// reset the scale mode.. oddly this seems to be reset when the canvas is resized. // surely a browser bug?? Let pixi fix that for you.. if(this.smoothProperty){this.rootContext[this.smoothProperty]=_settings2.default.SCALE_MODE===_const.SCALE_MODES.LINEAR;}};return CanvasRenderer;}(_SystemRenderer3.default);exports.default=CanvasRenderer;_utils.pluginTarget.mixin(CanvasRenderer);},{"../../const":42,"../../settings":97,"../../utils":117,"../SystemRenderer":72,"./utils/CanvasMaskManager":74,"./utils/CanvasRenderTarget":75,"./utils/mapCanvasBlendModesToPixi":77}],74:[function(require,module,exports){'use strict';exports.__esModule=true;var _const=require('../../../const');function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/** * A set of functions used to handle masking. * * @class * @memberof PIXI */var CanvasMaskManager=function(){/** * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. */function CanvasMaskManager(renderer){_classCallCheck(this,CanvasMaskManager);this.renderer=renderer;}/** * This method adds it to the current stack of masks. * * @param {object} maskData - the maskData that will be pushed */CanvasMaskManager.prototype.pushMask=function pushMask(maskData){var renderer=this.renderer;renderer.context.save();var cacheAlpha=maskData.alpha;var transform=maskData.transform.worldTransform;var resolution=renderer.resolution;renderer.context.setTransform(transform.a*resolution,transform.b*resolution,transform.c*resolution,transform.d*resolution,transform.tx*resolution,transform.ty*resolution);// TODO suport sprite alpha masks?? // lots of effort required. If demand is great enough.. if(!maskData._texture){this.renderGraphicsShape(maskData);renderer.context.clip();}maskData.worldAlpha=cacheAlpha;};/** * Renders a PIXI.Graphics shape. * * @param {PIXI.Graphics} graphics - The object to render. */CanvasMaskManager.prototype.renderGraphicsShape=function renderGraphicsShape(graphics){var context=this.renderer.context;var len=graphics.graphicsData.length;if(len===0){return;}context.beginPath();for(var i=0;imaxRadius?maxRadius:radius;context.moveTo(rx,ry+radius);context.lineTo(rx,ry+height-radius);context.quadraticCurveTo(rx,ry+height,rx+radius,ry+height);context.lineTo(rx+width-radius,ry+height);context.quadraticCurveTo(rx+width,ry+height,rx+width,ry+height-radius);context.lineTo(rx+width,ry+radius);context.quadraticCurveTo(rx+width,ry,rx+width-radius,ry);context.lineTo(rx+radius,ry);context.quadraticCurveTo(rx,ry,rx,ry+radius);context.closePath();}}};/** * Restores the current drawing context to the state it was before the mask was applied. * * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. */CanvasMaskManager.prototype.popMask=function popMask(renderer){renderer.context.restore();};/** * Destroys this canvas mask manager. * */CanvasMaskManager.prototype.destroy=function destroy(){/* empty */};return CanvasMaskManager;}();exports.default=CanvasMaskManager;},{"../../../const":42}],75:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;ithis.checkCountMax){this.checkCount=0;this.run();}};/** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU */TextureGarbageCollector.prototype.run=function run(){var tm=this.renderer.textureManager;var managedTextures=tm._managedTextures;var wasRemoved=false;for(var i=0;ithis.maxIdle){tm.destroyTexture(texture,true);managedTextures[i]=null;wasRemoved=true;}}if(wasRemoved){var j=0;for(var _i=0;_i=0;i--){this.unload(displayObject.children[i]);}};return TextureGarbageCollector;}();exports.default=TextureGarbageCollector;},{"../../const":42,"../../settings":97}],79:[function(require,module,exports){'use strict';exports.__esModule=true;var _pixiGlCore=require('pixi-gl-core');var _const=require('../../const');var _RenderTarget=require('./utils/RenderTarget');var _RenderTarget2=_interopRequireDefault(_RenderTarget);var _utils=require('../../utils');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/** * Helper class to create a webGL Texture * * @class * @memberof PIXI */var TextureManager=function(){/** * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer */function TextureManager(renderer){_classCallCheck(this,TextureManager);/** * A reference to the current renderer * * @member {PIXI.WebGLRenderer} */this.renderer=renderer;/** * The current WebGL rendering context * * @member {WebGLRenderingContext} */this.gl=renderer.gl;/** * Track textures in the renderer so we can no longer listen to them on destruction. * * @member {Array<*>} * @private */this._managedTextures=[];}/** * Binds a texture. * */TextureManager.prototype.bindTexture=function bindTexture(){}// empty /** * Gets a texture. * */;TextureManager.prototype.getTexture=function getTexture(){}// empty /** * Updates and/or Creates a WebGL texture for the renderer's context. * * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update * @param {Number} location - the location the texture will be bound to. * @return {GLTexture} The gl texture. */;TextureManager.prototype.updateTexture=function updateTexture(texture,location){// assume it good! // texture = texture.baseTexture || texture; var gl=this.gl;var isRenderTexture=!!texture._glRenderTargets;if(!texture.hasLoaded){return null;}var boundTextures=this.renderer.boundTextures;// if the location is undefined then this may have been called by n event. // this being the case the texture may already be bound to a slot. As a texture can only be bound once // we need to find its current location if it exists. if(location===undefined){location=0;// TODO maybe we can use texture bound ids later on... // check if texture is already bound.. for(var i=0;i} * @private */this.stack=[];/** * The current WebGL rendering context * * @member {WebGLRenderingContext} */this.gl=gl;this.maxAttribs=gl.getParameter(gl.MAX_VERTEX_ATTRIBS);this.attribState={tempAttribState:new Array(this.maxAttribs),attribState:new Array(this.maxAttribs)};this.blendModes=(0,_mapWebGLBlendModesToPixi2.default)(gl);// check we have vao.. this.nativeVaoExtension=gl.getExtension('OES_vertex_array_object')||gl.getExtension('MOZ_OES_vertex_array_object')||gl.getExtension('WEBKIT_OES_vertex_array_object');}/** * Pushes a new active state */WebGLState.prototype.push=function push(){// next state.. var state=this.stack[++this.stackIndex];if(!state){state=this.stack[this.stackIndex]=new Uint8Array(16);}// copy state.. // set active state so we can force overrides of gl state for(var i=0;iUpdating the value of a custom uniform * filter.uniforms.time = performance.now(); * * @member {object} */this.uniforms={};for(var i in this.uniformData){this.uniforms[i]=this.uniformData[i].value;}// this is where we store shader references.. // TODO we could cache this! this.glShaders={};// used for cacheing.. sure there is a better way! if(!SOURCE_KEY_MAP[this.vertexSrc+this.fragmentSrc]){SOURCE_KEY_MAP[this.vertexSrc+this.fragmentSrc]=(0,_utils.uid)();}this.glShaderKey=SOURCE_KEY_MAP[this.vertexSrc+this.fragmentSrc];/** * The padding of the filter. Some filters require extra space to breath such as a blur. * Increasing this will add extra width and height to the bounds of the object that the * filter is applied to. * * @member {number} */this.padding=4;/** * The resolution of the filter. Setting this to be lower will lower the quality but * increase the performance of the filter. * * @member {number} */this.resolution=1;/** * If enabled is true the filter is applied, if false it will not. * * @member {boolean} */this.enabled=true;}/** * Applies the filter * * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from * @param {PIXI.RenderTarget} input - The input render target. * @param {PIXI.RenderTarget} output - The target to output to. * @param {boolean} clear - Should the output be cleared before rendering to it */Filter.prototype.apply=function apply(filterManager,input,output,clear){// --- // // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); // do as you please! filterManager.applyFilter(this,input,output,clear);// or just do a regular render.. };/** * The default vertex shader source * * @static * @constant */_createClass(Filter,null,[{key:'defaultVertexSrc',get:function get(){return['attribute vec2 aVertexPosition;','attribute vec2 aTextureCoord;','uniform mat3 projectionMatrix;','uniform mat3 filterMatrix;','varying vec2 vTextureCoord;','varying vec2 vFilterCoord;','void main(void){',' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);',' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;',' vTextureCoord = aTextureCoord ;','}'].join('\n');}/** * The default fragment shader source * * @static * @constant */},{key:'defaultFragmentSrc',get:function get(){return['varying vec2 vTextureCoord;','varying vec2 vFilterCoord;','uniform sampler2D uSampler;','uniform sampler2D filterSampler;','void main(void){',' vec4 masky = texture2D(filterSampler, vFilterCoord);',' vec4 sample = texture2D(uSampler, vTextureCoord);',' vec4 color;',' if(mod(vFilterCoord.x, 1.0) > 0.5)',' {',' color = vec4(1.0, 0.0, 0.0, 1.0);',' }',' else',' {',' color = vec4(0.0, 1.0, 0.0, 1.0);',' }',// ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', ' gl_FragColor = mix(sample, masky, 0.5);',' gl_FragColor *= sample.a;','}'].join('\n');}}]);return Filter;}();exports.default=Filter;},{"../../../const":42,"../../../utils":117,"./extractUniformsFromSrc":83}],83:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=extractUniformsFromSrc;var _pixiGlCore=require('pixi-gl-core');var _pixiGlCore2=_interopRequireDefault(_pixiGlCore);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}var defaultValue=_pixiGlCore2.default.shader.defaultValue;function extractUniformsFromSrc(vertexSrc,fragmentSrc,mask){var vertUniforms=extractUniformsFromString(vertexSrc,mask);var fragUniforms=extractUniformsFromString(fragmentSrc,mask);return Object.assign(vertUniforms,fragUniforms);}function extractUniformsFromString(string){var maskRegex=new RegExp('^(projectionMatrix|uSampler|filterArea)$');var uniforms={};var nameSplit=void 0;// clean the lines a little - remove extra spaces / tabs etc // then split along ';' var lines=string.replace(/\s+/g,' ').split(/\s*;\s*/);// loop through.. for(var i=0;i-1){var splitLine=line.split(' ');var type=splitLine[1];var name=splitLine[2];var size=1;if(name.indexOf('[')>-1){// array! nameSplit=name.split(/\[|]/);name=nameSplit[0];size*=Number(nameSplit[1]);}if(!name.match(maskRegex)){uniforms[name]={value:defaultValue(type,size),name:name,type:type};}}}return uniforms;}},{"pixi-gl-core":12}],84:[function(require,module,exports){'use strict';exports.__esModule=true;exports.calculateScreenSpaceMatrix=calculateScreenSpaceMatrix;exports.calculateNormalizedScreenSpaceMatrix=calculateNormalizedScreenSpaceMatrix;exports.calculateSpriteMatrix=calculateSpriteMatrix;var _math=require('../../../math');/* * Calculates the mapped matrix * @param filterArea {Rectangle} The filter area * @param sprite {Sprite} the target sprite * @param outputMatrix {Matrix} @alvin */// TODO playing around here.. this is temporary - (will end up in the shader) // this returns a matrix that will normalise map filter cords in the filter to screen space function calculateScreenSpaceMatrix(outputMatrix,filterArea,textureSize){// let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), // let texture = {width:1136, height:700};//sprite._texture.baseTexture; // TODO unwrap? var mappedMatrix=outputMatrix.identity();mappedMatrix.translate(filterArea.x/textureSize.width,filterArea.y/textureSize.height);mappedMatrix.scale(textureSize.width,textureSize.height);return mappedMatrix;}function calculateNormalizedScreenSpaceMatrix(outputMatrix,filterArea,textureSize){var mappedMatrix=outputMatrix.identity();mappedMatrix.translate(filterArea.x/textureSize.width,filterArea.y/textureSize.height);var translateScaleX=textureSize.width/filterArea.width;var translateScaleY=textureSize.height/filterArea.height;mappedMatrix.scale(translateScaleX,translateScaleY);return mappedMatrix;}// this will map the filter coord so that a texture can be used based on the transform of a sprite function calculateSpriteMatrix(outputMatrix,filterArea,textureSize,sprite){var worldTransform=sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX);var texture=sprite._texture.baseTexture;// TODO unwrap? var mappedMatrix=outputMatrix.identity();// scale.. var ratio=textureSize.height/textureSize.width;mappedMatrix.translate(filterArea.x/textureSize.width,filterArea.y/textureSize.height);mappedMatrix.scale(1,ratio);var translateScaleX=textureSize.width/texture.width;var translateScaleY=textureSize.height/texture.height;worldTransform.tx/=texture.width*translateScaleX;// this...? free beer for anyone who can explain why this makes sense! worldTransform.ty/=texture.width*translateScaleX;// worldTransform.ty /= texture.height * translateScaleY; worldTransform.invert();mappedMatrix.prepend(worldTransform);// apply inverse scale.. mappedMatrix.scale(1,1/ratio);mappedMatrix.scale(translateScaleX,translateScaleY);mappedMatrix.translate(sprite.anchor.x,sprite.anchor.y);return mappedMatrix;}},{"../../../math":66}],85:[function(require,module,exports){'use strict';exports.__esModule=true;var _Filter2=require('../Filter');var _Filter3=_interopRequireDefault(_Filter2);var _math=require('../../../../math');var _path=require('path');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/** * The SpriteMaskFilter class * * @class * @extends PIXI.Filter * @memberof PIXI */var SpriteMaskFilter=function(_Filter){_inherits(SpriteMaskFilter,_Filter);/** * @param {PIXI.Sprite} sprite - the target sprite */function SpriteMaskFilter(sprite){_classCallCheck(this,SpriteMaskFilter);var maskMatrix=new _math.Matrix();var _this=_possibleConstructorReturn(this,_Filter.call(this,'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n','varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n'));sprite.renderable=false;_this.maskSprite=sprite;_this.maskMatrix=maskMatrix;return _this;}/** * Applies the filter * * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from * @param {PIXI.RenderTarget} input - The input render target. * @param {PIXI.RenderTarget} output - The target to output to. */SpriteMaskFilter.prototype.apply=function apply(filterManager,input,output){var maskSprite=this.maskSprite;this.uniforms.mask=maskSprite._texture;this.uniforms.otherMatrix=filterManager.calculateSpriteMatrix(this.maskMatrix,maskSprite);this.uniforms.alpha=maskSprite.worldAlpha;filterManager.applyFilter(this,input,output);};return SpriteMaskFilter;}(_Filter3.default);exports.default=SpriteMaskFilter;},{"../../../../math":66,"../Filter":82,"path":22}],86:[function(require,module,exports){'use strict';exports.__esModule=true;var _WebGLManager2=require('./WebGLManager');var _WebGLManager3=_interopRequireDefault(_WebGLManager2);var _RenderTarget=require('../utils/RenderTarget');var _RenderTarget2=_interopRequireDefault(_RenderTarget);var _Quad=require('../utils/Quad');var _Quad2=_interopRequireDefault(_Quad);var _math=require('../../../math');var _Shader=require('../../../Shader');var _Shader2=_interopRequireDefault(_Shader);var _filterTransforms=require('../filters/filterTransforms');var filterTransforms=_interopRequireWildcard(_filterTransforms);var _bitTwiddle=require('bit-twiddle');var _bitTwiddle2=_interopRequireDefault(_bitTwiddle);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/** * @ignore * @class */var FilterState=/** * */function FilterState(){_classCallCheck(this,FilterState);this.renderTarget=null;this.sourceFrame=new _math.Rectangle();this.destinationFrame=new _math.Rectangle();this.filters=[];this.target=null;this.resolution=1;};/** * @class * @memberof PIXI * @extends PIXI.WebGLManager */var FilterManager=function(_WebGLManager){_inherits(FilterManager,_WebGLManager);/** * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. */function FilterManager(renderer){_classCallCheck(this,FilterManager);var _this=_possibleConstructorReturn(this,_WebGLManager.call(this,renderer));_this.gl=_this.renderer.gl;// know about sprites! _this.quad=new _Quad2.default(_this.gl,renderer.state.attribState);_this.shaderCache={};// todo add default! _this.pool={};_this.filterData=null;return _this;}/** * Adds a new filter to the manager. * * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */FilterManager.prototype.pushFilter=function pushFilter(target,filters){var renderer=this.renderer;var filterData=this.filterData;if(!filterData){filterData=this.renderer._activeRenderTarget.filterStack;// add new stack var filterState=new FilterState();filterState.sourceFrame=filterState.destinationFrame=this.renderer._activeRenderTarget.size;filterState.renderTarget=renderer._activeRenderTarget;this.renderer._activeRenderTarget.filterData=filterData={index:0,stack:[filterState]};this.filterData=filterData;}// get the current filter state.. var currentState=filterData.stack[++filterData.index];if(!currentState){currentState=filterData.stack[filterData.index]=new FilterState();}// for now we go off the filter of the first resolution.. var resolution=filters[0].resolution;var padding=filters[0].padding|0;var targetBounds=target.filterArea||target.getBounds(true);var sourceFrame=currentState.sourceFrame;var destinationFrame=currentState.destinationFrame;sourceFrame.x=(targetBounds.x*resolution|0)/resolution;sourceFrame.y=(targetBounds.y*resolution|0)/resolution;sourceFrame.width=(targetBounds.width*resolution|0)/resolution;sourceFrame.height=(targetBounds.height*resolution|0)/resolution;if(filterData.stack[0].renderTarget.transform){// // TODO we should fit the rect around the transform.. }else{sourceFrame.fit(filterData.stack[0].destinationFrame);}// lets apply the padding After we fit the element to the screen. // this should stop the strange side effects that can occur when cropping to the edges sourceFrame.pad(padding);destinationFrame.width=sourceFrame.width;destinationFrame.height=sourceFrame.height;// lets play the padding after we fit the element to the screen. // this should stop the strange side effects that can occur when cropping to the edges var renderTarget=this.getPotRenderTarget(renderer.gl,sourceFrame.width,sourceFrame.height,resolution);currentState.target=target;currentState.filters=filters;currentState.resolution=resolution;currentState.renderTarget=renderTarget;// bind the render target to draw the shape in the top corner.. renderTarget.setFrame(destinationFrame,sourceFrame);// bind the render target renderer.bindRenderTarget(renderTarget);renderTarget.clear();};/** * Pops off the filter and applies it. * */FilterManager.prototype.popFilter=function popFilter(){var filterData=this.filterData;var lastState=filterData.stack[filterData.index-1];var currentState=filterData.stack[filterData.index];this.quad.map(currentState.renderTarget.size,currentState.sourceFrame).upload();var filters=currentState.filters;if(filters.length===1){filters[0].apply(this,currentState.renderTarget,lastState.renderTarget,false);this.freePotRenderTarget(currentState.renderTarget);}else{var flip=currentState.renderTarget;var flop=this.getPotRenderTarget(this.renderer.gl,currentState.sourceFrame.width,currentState.sourceFrame.height,currentState.resolution);flop.setFrame(currentState.destinationFrame,currentState.sourceFrame);// finally lets clear the render target before drawing to it.. flop.clear();var i=0;for(i=0;i0){src+='\nelse ';}if(ix1&&tempPoint.xy1&&tempPoint.y>16)+(value&0xff00)+((value&0xff)<<16);}/** * The texture that the sprite is using * * @member {PIXI.Texture} * @memberof PIXI.Sprite# */},{key:'texture',get:function get(){return this._texture;}/** * Sets the texture of the sprite. * * @param {PIXI.Texture} value - The value to set to. */,set:function set(value){if(this._texture===value){return;}this._texture=value;this.cachedTint=0xFFFFFF;this._textureID=-1;if(value){// wait for the texture to load if(value.baseTexture.hasLoaded){this._onTextureUpdate();}else{value.once('update',this._onTextureUpdate,this);}}}}]);return Sprite;}(_Container3.default);exports.default=Sprite;},{"../const":42,"../display/Container":44,"../math":66,"../textures/Texture":109,"../utils":117}],99:[function(require,module,exports){'use strict';exports.__esModule=true;var _CanvasRenderer=require('../../renderers/canvas/CanvasRenderer');var _CanvasRenderer2=_interopRequireDefault(_CanvasRenderer);var _const=require('../../const');var _math=require('../../math');var _CanvasTinter=require('./CanvasTinter');var _CanvasTinter2=_interopRequireDefault(_CanvasTinter);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var canvasRenderWorldTransform=new _math.Matrix();/** * @author Mat Groves * * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ * for creating the original pixi version! * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now * share 4 bytes on the vertex buffer * * Heavily inspired by LibGDX's CanvasSpriteRenderer: * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java *//** * Renderer dedicated to drawing and batching sprites. * * @class * @private * @memberof PIXI */var CanvasSpriteRenderer=function(){/** * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. */function CanvasSpriteRenderer(renderer){_classCallCheck(this,CanvasSpriteRenderer);this.renderer=renderer;}/** * Renders the sprite object. * * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch */CanvasSpriteRenderer.prototype.render=function render(sprite){var texture=sprite._texture;var renderer=this.renderer;var width=texture._frame.width;var height=texture._frame.height;var wt=sprite.transform.worldTransform;var dx=0;var dy=0;if(texture.orig.width<=0||texture.orig.height<=0||!texture.baseTexture.source){return;}renderer.setBlendMode(sprite.blendMode);// Ignore null sources if(texture.valid){renderer.context.globalAlpha=sprite.worldAlpha;// If smoothingEnabled is supported and we need to change the smoothing property for sprite texture var smoothingEnabled=texture.baseTexture.scaleMode===_const.SCALE_MODES.LINEAR;if(renderer.smoothProperty&&renderer.context[renderer.smoothProperty]!==smoothingEnabled){renderer.context[renderer.smoothProperty]=smoothingEnabled;}if(texture.trim){dx=texture.trim.width/2+texture.trim.x-sprite.anchor.x*texture.orig.width;dy=texture.trim.height/2+texture.trim.y-sprite.anchor.y*texture.orig.height;}else{dx=(0.5-sprite.anchor.x)*texture.orig.width;dy=(0.5-sprite.anchor.y)*texture.orig.height;}if(texture.rotate){wt.copy(canvasRenderWorldTransform);wt=canvasRenderWorldTransform;_math.GroupD8.matrixAppendRotationInv(wt,texture.rotate,dx,dy);// the anchor has already been applied above, so lets set it to zero dx=0;dy=0;}dx-=width/2;dy-=height/2;// Allow for pixel rounding if(renderer.roundPixels){renderer.context.setTransform(wt.a,wt.b,wt.c,wt.d,wt.tx*renderer.resolution|0,wt.ty*renderer.resolution|0);dx=dx|0;dy=dy|0;}else{renderer.context.setTransform(wt.a,wt.b,wt.c,wt.d,wt.tx*renderer.resolution,wt.ty*renderer.resolution);}var resolution=texture.baseTexture.resolution;if(sprite.tint!==0xFFFFFF){if(sprite.cachedTint!==sprite.tint){sprite.cachedTint=sprite.tint;// TODO clean up caching - how to clean up the caches? sprite.tintedTexture=_CanvasTinter2.default.getTintedTexture(sprite,sprite.tint);}renderer.context.drawImage(sprite.tintedTexture,0,0,width*resolution,height*resolution,dx*renderer.resolution,dy*renderer.resolution,width*renderer.resolution,height*renderer.resolution);}else{renderer.context.drawImage(texture.baseTexture.source,texture._frame.x*resolution,texture._frame.y*resolution,width*resolution,height*resolution,dx*renderer.resolution,dy*renderer.resolution,width*renderer.resolution,height*renderer.resolution);}}};/** * destroy the sprite object. * */CanvasSpriteRenderer.prototype.destroy=function destroy(){this.renderer=null;};return CanvasSpriteRenderer;}();exports.default=CanvasSpriteRenderer;_CanvasRenderer2.default.registerPlugin('sprite',CanvasSpriteRenderer);},{"../../const":42,"../../math":66,"../../renderers/canvas/CanvasRenderer":73,"./CanvasTinter":100}],100:[function(require,module,exports){'use strict';exports.__esModule=true;var _utils=require('../../utils');var _canUseNewCanvasBlendModes=require('../../renderers/canvas/utils/canUseNewCanvasBlendModes');var _canUseNewCanvasBlendModes2=_interopRequireDefault(_canUseNewCanvasBlendModes);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/** * Utility methods for Sprite/Texture tinting. * * @namespace PIXI.CanvasTinter */var CanvasTinter={/** * Basically this method just needs a sprite and a color and tints the sprite with the given color. * * @memberof PIXI.CanvasTinter * @param {PIXI.Sprite} sprite - the sprite to tint * @param {number} color - the color to use to tint the sprite with * @return {HTMLCanvasElement} The tinted canvas */getTintedTexture:function getTintedTexture(sprite,color){var texture=sprite.texture;color=CanvasTinter.roundColor(color);var stringColor='#'+('00000'+(color|0).toString(16)).substr(-6);texture.tintCache=texture.tintCache||{};if(texture.tintCache[stringColor]){return texture.tintCache[stringColor];}// clone texture.. var canvas=CanvasTinter.canvas||document.createElement('canvas');// CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); CanvasTinter.tintMethod(texture,color,canvas);if(CanvasTinter.convertTintToImage){// is this better? var tintImage=new Image();tintImage.src=canvas.toDataURL();texture.tintCache[stringColor]=tintImage;}else{texture.tintCache[stringColor]=canvas;// if we are not converting the texture to an image then we need to lose the reference to the canvas CanvasTinter.canvas=null;}return canvas;},/** * Tint a texture using the 'multiply' operation. * * @memberof PIXI.CanvasTinter * @param {PIXI.Texture} texture - the texture to tint * @param {number} color - the color to use to tint the sprite with * @param {HTMLCanvasElement} canvas - the current canvas */tintWithMultiply:function tintWithMultiply(texture,color,canvas){var context=canvas.getContext('2d');var crop=texture._frame.clone();var resolution=texture.baseTexture.resolution;crop.x*=resolution;crop.y*=resolution;crop.width*=resolution;crop.height*=resolution;canvas.width=crop.width;canvas.height=crop.height;context.fillStyle='#'+('00000'+(color|0).toString(16)).substr(-6);context.fillRect(0,0,crop.width,crop.height);context.globalCompositeOperation='multiply';context.drawImage(texture.baseTexture.source,crop.x,crop.y,crop.width,crop.height,0,0,crop.width,crop.height);context.globalCompositeOperation='destination-atop';context.drawImage(texture.baseTexture.source,crop.x,crop.y,crop.width,crop.height,0,0,crop.width,crop.height);},/** * Tint a texture using the 'overlay' operation. * * @memberof PIXI.CanvasTinter * @param {PIXI.Texture} texture - the texture to tint * @param {number} color - the color to use to tint the sprite with * @param {HTMLCanvasElement} canvas - the current canvas */tintWithOverlay:function tintWithOverlay(texture,color,canvas){var context=canvas.getContext('2d');var crop=texture._frame.clone();var resolution=texture.baseTexture.resolution;crop.x*=resolution;crop.y*=resolution;crop.width*=resolution;crop.height*=resolution;canvas.width=crop.width;canvas.height=crop.height;context.globalCompositeOperation='copy';context.fillStyle='#'+('00000'+(color|0).toString(16)).substr(-6);context.fillRect(0,0,crop.width,crop.height);context.globalCompositeOperation='destination-atop';context.drawImage(texture.baseTexture.source,crop.x,crop.y,crop.width,crop.height,0,0,crop.width,crop.height);// context.globalCompositeOperation = 'copy'; },/** * Tint a texture pixel per pixel. * * @memberof PIXI.CanvasTinter * @param {PIXI.Texture} texture - the texture to tint * @param {number} color - the color to use to tint the sprite with * @param {HTMLCanvasElement} canvas - the current canvas */tintWithPerPixel:function tintWithPerPixel(texture,color,canvas){var context=canvas.getContext('2d');var crop=texture._frame.clone();var resolution=texture.baseTexture.resolution;crop.x*=resolution;crop.y*=resolution;crop.width*=resolution;crop.height*=resolution;canvas.width=crop.width;canvas.height=crop.height;context.globalCompositeOperation='copy';context.drawImage(texture.baseTexture.source,crop.x,crop.y,crop.width,crop.height,0,0,crop.width,crop.height);var rgbValues=(0,_utils.hex2rgb)(color);var r=rgbValues[0];var g=rgbValues[1];var b=rgbValues[2];var pixelData=context.getImageData(0,0,crop.width,crop.height);var pixels=pixelData.data;for(var i=0;i=this.size){this.flush();}// get the uvs for the texture // if the uvs have not updated then no point rendering just yet! if(!sprite._texture._uvs){return;}// push a texture. // increment the batchsize this.sprites[this.currentIndex++]=sprite;};/** * Renders the content and empties the current batch. * */SpriteRenderer.prototype.flush=function flush(){if(this.currentIndex===0){return;}var gl=this.renderer.gl;var MAX_TEXTURES=this.MAX_TEXTURES;var np2=_bitTwiddle2.default.nextPow2(this.currentIndex);var log2=_bitTwiddle2.default.log2(np2);var buffer=this.buffers[log2];var sprites=this.sprites;var groups=this.groups;var float32View=buffer.float32View;var uint32View=buffer.uint32View;var boundTextures=this.boundTextures;var rendererBoundTextures=this.renderer.boundTextures;var touch=this.renderer.textureGC.count;var index=0;var nextTexture=void 0;var currentTexture=void 0;var groupCount=1;var textureCount=0;var currentGroup=groups[0];var vertexData=void 0;var uvs=void 0;var blendMode=sprites[0].blendMode;currentGroup.textureCount=0;currentGroup.start=0;currentGroup.blend=blendMode;TICK++;var i=void 0;// copy textures.. for(i=0;i0){src+='\nelse ';}if(i0){this.context.shadowColor=style.dropShadowColor;this.context.shadowBlur=style.dropShadowBlur;}else{this.context.fillStyle=style.dropShadowColor;}var xShadowOffset=Math.cos(style.dropShadowAngle)*style.dropShadowDistance;var yShadowOffset=Math.sin(style.dropShadowAngle)*style.dropShadowDistance;for(var _i=0;_iwordWrapWidth){// Word should be split in the middle var characters=words[j].split('');for(var c=0;cspaceLeft){result+='\n'+characters[c];spaceLeft=wordWrapWidth-characterWidth;}else{if(c===0){result+=' ';}result+=characters[c];spaceLeft-=characterWidth;}}}else{var wordWidthWithSpace=wordWidth+this.context.measureText(' ').width;if(j===0||wordWidthWithSpace>spaceLeft){// Skip printing the newline if it's the first word of the line that is // greater than the word wrap width. if(j>0){result+='\n';}result+=words[j];spaceLeft=wordWrapWidth-wordWidth;}else{spaceLeft-=wordWidthWithSpace;result+=' '+words[j];}}}if(i=0;i--){// Trim any extra white-space var fontFamily=fontFamilies[i].trim();// Check if font already contains strings if(!/([\"\'])[^\'\"]+\1/.test(fontFamily)){fontFamily='"'+fontFamily+'"';}fontFamilies[i]=fontFamily;}return style.fontStyle+' '+style.fontVariant+' '+style.fontWeight+' '+fontSizeString+' '+fontFamilies.join(',');};/** * Calculates the ascent, descent and fontSize of a given fontStyle * * @static * @param {string} fontStyle - String representing the style of the font * @return {Object} Font properties object */Text.calculateFontProperties=function calculateFontProperties(fontStyle){// as this method is used for preparing assets, don't recalculate things if we don't need to if(Text.fontPropertiesCache[fontStyle]){return Text.fontPropertiesCache[fontStyle];}var properties={};var canvas=Text.fontPropertiesCanvas;var context=Text.fontPropertiesContext;context.font=fontStyle;var width=Math.ceil(context.measureText('|MÉq').width);var baseline=Math.ceil(context.measureText('M').width);var height=2*baseline;baseline=baseline*1.4|0;canvas.width=width;canvas.height=height;context.fillStyle='#f00';context.fillRect(0,0,width,height);context.font=fontStyle;context.textBaseline='alphabetic';context.fillStyle='#000';context.fillText('|MÉq',0,baseline);var imagedata=context.getImageData(0,0,width,height).data;var pixels=imagedata.length;var line=width*4;var i=0;var idx=0;var stop=false;// ascent. scan from top to bottom until we find a non red pixel for(i=0;ibaseline;--i){for(var _j=0;_j} */_this._glRenderTargets={};/** * A reference to the canvas render target (we only need one as this can be shared across renderers) * * @private * @member {object} */_this._canvasRenderTarget=null;/** * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. * * @member {boolean} */_this.valid=false;return _this;}/** * Resizes the BaseRenderTexture. * * @param {number} width - The width to resize to. * @param {number} height - The height to resize to. */BaseRenderTexture.prototype.resize=function resize(width,height){if(width===this.width&&height===this.height){return;}this.valid=width>0&&height>0;this.width=width;this.height=height;this.realWidth=this.width*this.resolution;this.realHeight=this.height*this.resolution;if(!this.valid){return;}this.emit('update',this);};/** * Destroys this texture * */BaseRenderTexture.prototype.destroy=function destroy(){_BaseTexture.prototype.destroy.call(this,true);this.renderer=null;};return BaseRenderTexture;}(_BaseTexture3.default);exports.default=BaseRenderTexture;},{"../settings":97,"./BaseTexture":107}],107:[function(require,module,exports){'use strict';exports.__esModule=true;var _typeof=typeof Symbol==="function"&&_typeof2(Symbol.iterator)==="symbol"?function(obj){return typeof obj==="undefined"?"undefined":_typeof2(obj);}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj==="undefined"?"undefined":_typeof2(obj);};var _utils=require('../utils');var _settings=require('../settings');var _settings2=_interopRequireDefault(_settings);var _eventemitter=require('eventemitter3');var _eventemitter2=_interopRequireDefault(_eventemitter);var _determineCrossOrigin=require('../utils/determineCrossOrigin');var _determineCrossOrigin2=_interopRequireDefault(_determineCrossOrigin);var _bitTwiddle=require('bit-twiddle');var _bitTwiddle2=_interopRequireDefault(_bitTwiddle);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/** * A texture stores the information that represents an image. All textures have a base texture. * * @class * @extends EventEmitter * @memberof PIXI */var BaseTexture=function(_EventEmitter){_inherits(BaseTexture,_EventEmitter);/** * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture */function BaseTexture(source,scaleMode,resolution){_classCallCheck(this,BaseTexture);var _this=_possibleConstructorReturn(this,_EventEmitter.call(this));_this.uid=(0,_utils.uid)();_this.touched=0;/** * The resolution / device pixel ratio of the texture * * @member {number} * @default 1 */_this.resolution=resolution||_settings2.default.RESOLUTION;/** * The width of the base texture set when the image has loaded * * @readonly * @member {number} */_this.width=100;/** * The height of the base texture set when the image has loaded * * @readonly * @member {number} */_this.height=100;// TODO docs // used to store the actual dimensions of the source /** * Used to store the actual width of the source of this texture * * @readonly * @member {number} */_this.realWidth=100;/** * Used to store the actual height of the source of this texture * * @readonly * @member {number} */_this.realHeight=100;/** * The scale mode to apply when scaling this texture * * @member {number} * @default PIXI.settings.SCALE_MODE * @see PIXI.SCALE_MODES */_this.scaleMode=scaleMode||_settings2.default.SCALE_MODE;/** * Set to true once the base texture has successfully loaded. * * This is never true if the underlying source fails to load or has no texture data. * * @readonly * @member {boolean} */_this.hasLoaded=false;/** * Set to true if the source is currently loading. * * If an Image source is loading the 'loaded' or 'error' event will be * dispatched when the operation ends. An underyling source that is * immediately-available bypasses loading entirely. * * @readonly * @member {boolean} */_this.isLoading=false;/** * The image source that is used to create the texture. * * TODO: Make this a setter that calls loadSource(); * * @readonly * @member {HTMLImageElement|HTMLCanvasElement} */_this.source=null;// set in loadSource, if at all /** * The image source that is used to create the texture. This is used to * store the original Svg source when it is replaced with a canvas element. * * TODO: Currently not in use but could be used when re-scaling svg. * * @readonly * @member {Image} */_this.origSource=null;// set in loadSvg, if at all /** * Type of image defined in source, eg. `png` or `svg` * * @readonly * @member {string} */_this.imageType=null;// set in updateImageType /** * Scale for source image. Used with Svg images to scale them before rasterization. * * @readonly * @member {number} */_this.sourceScale=1.0;/** * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) * All blend modes, and shaders written for default value. Change it on your own risk. * * @member {boolean} * @default true */_this.premultipliedAlpha=true;/** * The image url of the texture * * @member {string} */_this.imageUrl=null;/** * Whether or not the texture is a power of two, try to use power of two textures as much * as you can * * @private * @member {boolean} */_this.isPowerOfTwo=false;// used for webGL /** * * Set this to true if a mipmap of this texture needs to be generated. This value needs * to be set before the texture is used * Also the texture must be a power of two size to work * * @member {boolean} * @see PIXI.MIPMAP_TEXTURES */_this.mipmap=_settings2.default.MIPMAP_TEXTURES;/** * * WebGL Texture wrap mode * * @member {number} * @see PIXI.WRAP_MODES */_this.wrapMode=_settings2.default.WRAP_MODE;/** * A map of renderer IDs to webgl textures * * @private * @member {object} */_this._glTextures={};_this._enabled=0;_this._virtalBoundId=-1;// if no source passed don't try to load if(source){_this.loadSource(source);}/** * Fired when a not-immediately-available source finishes loading. * * @protected * @event loaded * @memberof PIXI.BaseTexture# *//** * Fired when a not-immediately-available source fails to load. * * @protected * @event error * @memberof PIXI.BaseTexture# */return _this;}/** * Updates the texture on all the webgl renderers, this also assumes the src has changed. * * @fires update */BaseTexture.prototype.update=function update(){// Svg size is handled during load if(this.imageType!=='svg'){this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width;this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height;this.width=this.realWidth/this.resolution;this.height=this.realHeight/this.resolution;this.isPowerOfTwo=_bitTwiddle2.default.isPow2(this.realWidth)&&_bitTwiddle2.default.isPow2(this.realHeight);}this.emit('update',this);};/** * Load a source. * * If the source is not-immediately-available, such as an image that needs to be * downloaded, then the 'loaded' or 'error' event will be dispatched in the future * and `hasLoaded` will remain false after this call. * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * * if (texture.hasLoaded) { * // texture ready for use * } else if (texture.isLoading) { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded * // (it may still make sense to listen to the events) * } * * @protected * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. */BaseTexture.prototype.loadSource=function loadSource(source){var _this2=this;var wasLoading=this.isLoading;this.hasLoaded=false;this.isLoading=false;if(wasLoading&&this.source){this.source.onload=null;this.source.onerror=null;}var firstSourceLoaded=!this.source;this.source=source;// Apply source if loaded. Otherwise setup appropriate loading monitors. if((source.src&&source.complete||source.getContext)&&source.width&&source.height){this._updateImageType();if(this.imageType==='svg'){this._loadSvgSource();}else{this._sourceLoaded();}if(firstSourceLoaded){// send loaded event if previous source was null and we have been passed a pre-loaded IMG element this.emit('loaded',this);}}else if(!source.getContext){var _ret=function(){// Image fail / not ready _this2.isLoading=true;var scope=_this2;source.onload=function(){scope._updateImageType();source.onload=null;source.onerror=null;if(!scope.isLoading){return;}scope.isLoading=false;scope._sourceLoaded();if(scope.imageType==='svg'){scope._loadSvgSource();return;}scope.emit('loaded',scope);};source.onerror=function(){source.onload=null;source.onerror=null;if(!scope.isLoading){return;}scope.isLoading=false;scope.emit('error',scope);};// Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. // NOTE: complete will be true if the image has no src so best to check if the src is set. if(source.complete&&source.src){// ..and if we're complete now, no need for callbacks source.onload=null;source.onerror=null;if(scope.imageType==='svg'){scope._loadSvgSource();return{v:void 0};}_this2.isLoading=false;if(source.width&&source.height){_this2._sourceLoaded();// If any previous subscribers possible if(wasLoading){_this2.emit('loaded',_this2);}}// If any previous subscribers possible else if(wasLoading){_this2.emit('error',_this2);}}}();if((typeof _ret==='undefined'?'undefined':_typeof(_ret))==="object")return _ret.v;}};/** * Updates type of the source image. */BaseTexture.prototype._updateImageType=function _updateImageType(){if(!this.imageUrl){return;}var dataUri=(0,_utils.decomposeDataUri)(this.imageUrl);var imageType=void 0;if(dataUri&&dataUri.mediaType==='image'){// Check for subType validity var firstSubType=dataUri.subType.split('+')[0];imageType=(0,_utils.getUrlFileExtension)('.'+firstSubType);if(!imageType){throw new Error('Invalid image type in data URI.');}}else{imageType=(0,_utils.getUrlFileExtension)(this.imageUrl);if(!imageType){imageType='png';}}this.imageType=imageType;};/** * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. */BaseTexture.prototype._loadSvgSource=function _loadSvgSource(){if(this.imageType!=='svg'){// Do nothing if source is not svg return;}var dataUri=(0,_utils.decomposeDataUri)(this.imageUrl);if(dataUri){this._loadSvgSourceUsingDataUri(dataUri);}else{// We got an URL, so we need to do an XHR to check the svg size this._loadSvgSourceUsingXhr();}};/** * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. * * @param {string} dataUri - The data uri to load from. */BaseTexture.prototype._loadSvgSourceUsingDataUri=function _loadSvgSourceUsingDataUri(dataUri){var svgString=void 0;if(dataUri.encoding==='base64'){if(!atob){throw new Error('Your browser doesn\'t support base64 conversions.');}svgString=atob(dataUri.data);}else{svgString=dataUri.data;}this._loadSvgSourceUsingString(svgString);};/** * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. */BaseTexture.prototype._loadSvgSourceUsingXhr=function _loadSvgSourceUsingXhr(){var _this3=this;var svgXhr=new XMLHttpRequest();// This throws error on IE, so SVG Document can't be used // svgXhr.responseType = 'document'; // This is not needed since we load the svg as string (breaks IE too) // but overrideMimeType() can be used to force the response to be parsed as XML // svgXhr.overrideMimeType('image/svg+xml'); svgXhr.onload=function(){if(svgXhr.readyState!==svgXhr.DONE||svgXhr.status!==200){throw new Error('Failed to load SVG using XHR.');}_this3._loadSvgSourceUsingString(svgXhr.response);};svgXhr.onerror=function(){return _this3.emit('error',_this3);};svgXhr.open('GET',this.imageUrl,true);svgXhr.send();};/** * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. * * @param {string} svgString SVG source as string * * @fires loaded */BaseTexture.prototype._loadSvgSourceUsingString=function _loadSvgSourceUsingString(svgString){var svgSize=(0,_utils.getSvgSize)(svgString);var svgWidth=svgSize.width;var svgHeight=svgSize.height;if(!svgWidth||!svgHeight){throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.');}// Scale realWidth and realHeight this.realWidth=Math.round(svgWidth*this.sourceScale);this.realHeight=Math.round(svgHeight*this.sourceScale);this.width=this.realWidth/this.resolution;this.height=this.realHeight/this.resolution;// Check pow2 after scale this.isPowerOfTwo=_bitTwiddle2.default.isPow2(this.realWidth)&&_bitTwiddle2.default.isPow2(this.realHeight);// Create a canvas element var canvas=document.createElement('canvas');canvas.width=this.realWidth;canvas.height=this.realHeight;canvas._pixiId='canvas_'+(0,_utils.uid)();// Draw the Svg to the canvas canvas.getContext('2d').drawImage(this.source,0,0,svgWidth,svgHeight,0,0,this.realWidth,this.realHeight);// Replace the original source image with the canvas this.origSource=this.source;this.source=canvas;// Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) _utils.BaseTextureCache[canvas._pixiId]=this;this.isLoading=false;this._sourceLoaded();this.emit('loaded',this);};/** * Used internally to update the width, height, and some other tracking vars once * a source has successfully loaded. * * @private */BaseTexture.prototype._sourceLoaded=function _sourceLoaded(){this.hasLoaded=true;this.update();};/** * Destroys this base texture * */BaseTexture.prototype.destroy=function destroy(){if(this.imageUrl){delete _utils.BaseTextureCache[this.imageUrl];delete _utils.TextureCache[this.imageUrl];this.imageUrl=null;if(!navigator.isCocoonJS){this.source.src='';}}// An svg source has both `imageUrl` and `__pixiId`, so no `else if` here if(this.source&&this.source._pixiId){delete _utils.BaseTextureCache[this.source._pixiId];}this.source=null;this.dispose();};/** * Frees the texture from WebGL memory without destroying this texture object. * This means you can still use the texture later which will upload it to GPU * memory again. * */BaseTexture.prototype.dispose=function dispose(){this.emit('dispose',this);};/** * Changes the source image of the texture. * The original source must be an Image element. * * @param {string} newSrc - the path of the image */BaseTexture.prototype.updateSourceImage=function updateSourceImage(newSrc){this.source.src=newSrc;this.loadSource(this.source);};/** * Helper function that creates a base texture from the given image url. * If the image is not in the base texture cache it will be created and loaded. * * @static * @param {string} imageUrl - The image url of the texture * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */BaseTexture.fromImage=function fromImage(imageUrl,crossorigin,scaleMode,sourceScale){var baseTexture=_utils.BaseTextureCache[imageUrl];if(!baseTexture){// new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image=new Image();// document.createElement('img'); if(crossorigin===undefined&&imageUrl.indexOf('data:')!==0){image.crossOrigin=(0,_determineCrossOrigin2.default)(imageUrl);}baseTexture=new BaseTexture(image,scaleMode);baseTexture.imageUrl=imageUrl;if(sourceScale){baseTexture.sourceScale=sourceScale;}// if there is an @2x at the end of the url we are going to assume its a highres image baseTexture.resolution=(0,_utils.getResolutionOfUrl)(imageUrl);image.src=imageUrl;// Setting this triggers load _utils.BaseTextureCache[imageUrl]=baseTexture;}return baseTexture;};/** * Helper function that creates a base texture from the given canvas element. * * @static * @param {HTMLCanvasElement} canvas - The canvas element source of the texture * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values * @return {PIXI.BaseTexture} The new base texture. */BaseTexture.fromCanvas=function fromCanvas(canvas,scaleMode){if(!canvas._pixiId){canvas._pixiId='canvas_'+(0,_utils.uid)();}var baseTexture=_utils.BaseTextureCache[canvas._pixiId];if(!baseTexture){baseTexture=new BaseTexture(canvas,scaleMode);_utils.BaseTextureCache[canvas._pixiId]=baseTexture;}return baseTexture;};return BaseTexture;}(_eventemitter2.default);exports.default=BaseTexture;},{"../settings":97,"../utils":117,"../utils/determineCrossOrigin":116,"bit-twiddle":1,"eventemitter3":3}],108:[function(require,module,exports){'use strict';exports.__esModule=true;var _BaseRenderTexture=require('./BaseRenderTexture');var _BaseRenderTexture2=_interopRequireDefault(_BaseRenderTexture);var _Texture2=require('./Texture');var _Texture3=_interopRequireDefault(_Texture2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/** * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. * * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded * otherwise black rectangles will be drawn instead. * * A RenderTexture takes a snapshot of any Display Object given to its render method. The position * and rotation of the given Display Objects is ignored. For example: * * ```js * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); * let renderTexture = PIXI.RenderTexture.create(800, 600); * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); * * sprite.position.x = 800/2; * sprite.position.y = 600/2; * sprite.anchor.x = 0.5; * sprite.anchor.y = 0.5; * * renderer.render(sprite, renderTexture); * ``` * * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual * position a Container should be used: * * ```js * let doc = new PIXI.Container(); * * doc.addChild(sprite); * * renderer.render(doc, renderTexture); // Renders to center of renderTexture * ``` * * @class * @extends PIXI.Texture * @memberof PIXI */var RenderTexture=function(_Texture){_inherits(RenderTexture,_Texture);/** * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show */function RenderTexture(baseRenderTexture,frame){_classCallCheck(this,RenderTexture);// support for legacy.. var _legacyRenderer=null;if(!(baseRenderTexture instanceof _BaseRenderTexture2.default)){/* eslint-disable prefer-rest-params, no-console */var width=arguments[1];var height=arguments[2];var scaleMode=arguments[3]||0;var resolution=arguments[4]||1;// we have an old render texture.. console.warn('Please use RenderTexture.create('+width+', '+height+') instead of the ctor directly.');_legacyRenderer=arguments[0];/* eslint-enable prefer-rest-params, no-console */frame=null;baseRenderTexture=new _BaseRenderTexture2.default(width,height,scaleMode,resolution);}/** * The base texture object that this texture uses * * @member {BaseTexture} */var _this=_possibleConstructorReturn(this,_Texture.call(this,baseRenderTexture,frame));_this.legacyRenderer=_legacyRenderer;/** * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. * * @member {boolean} */_this.valid=true;_this._updateUvs();return _this;}/** * Resizes the RenderTexture. * * @param {number} width - The width to resize to. * @param {number} height - The height to resize to. * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? */RenderTexture.prototype.resize=function resize(width,height,doNotResizeBaseTexture){// TODO - could be not required.. this.valid=width>0&&height>0;this._frame.width=this.orig.width=width;this._frame.height=this.orig.height=height;if(!doNotResizeBaseTexture){this.baseTexture.resize(width,height);}this._updateUvs();};/** * A short hand way of creating a render texture. * * @param {number} [width=100] - The width of the render texture * @param {number} [height=100] - The height of the render texture * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated * @return {PIXI.RenderTexture} The new render texture */RenderTexture.create=function create(width,height,scaleMode,resolution){return new RenderTexture(new _BaseRenderTexture2.default(width,height,scaleMode,resolution));};return RenderTexture;}(_Texture3.default);exports.default=RenderTexture;},{"./BaseRenderTexture":106,"./Texture":109}],109:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;ithis.baseTexture.width||frame.y+frame.height>this.baseTexture.height){throw new Error('Texture Error: frame does not fit inside the base Texture dimensions '+this);}// this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; this.valid=frame&&frame.width&&frame.height&&this.baseTexture.hasLoaded;if(!this.trim&&!this.rotate){this.orig=frame;}if(this.valid){this._updateUvs();}}/** * Indicates whether the texture is rotated inside the atlas * set to 2 to compensate for texture packer rotation * set to 6 to compensate for spine packer rotation * can be used to rotate or mirror sprites * See {@link PIXI.GroupD8} for explanation * * @member {number} */},{key:'rotate',get:function get(){return this._rotate;}/** * Set the rotation * * @param {number} rotate - The new rotation to set. */,set:function set(rotate){this._rotate=rotate;if(this.valid){this._updateUvs();}}/** * The width of the Texture in pixels. * * @member {number} */},{key:'width',get:function get(){return this.orig.width;}/** * The height of the Texture in pixels. * * @member {number} */},{key:'height',get:function get(){return this.orig.height;}}]);return Texture;}(_eventemitter2.default);/** * An empty texture, used often to not have to create multiple empty textures. * Can not be destroyed. * * @static * @constant */exports.default=Texture;Texture.EMPTY=new Texture(new _BaseTexture2.default());Texture.EMPTY.destroy=function _emptyDestroy(){/* empty */};Texture.EMPTY.on=function _emptyOn(){/* empty */};Texture.EMPTY.once=function _emptyOnce(){/* empty */};Texture.EMPTY.emit=function _emptyEmit(){/* empty */};},{"../math":66,"../utils":117,"./BaseTexture":107,"./TextureUvs":110,"./VideoBaseTexture":111,"eventemitter3":3}],110:[function(require,module,exports){'use strict';exports.__esModule=true;var _GroupD=require('../math/GroupD8');var _GroupD2=_interopRequireDefault(_GroupD);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/** * A standard object to store the Uvs of a texture * * @class * @private * @memberof PIXI */var TextureUvs=function(){/** * */function TextureUvs(){_classCallCheck(this,TextureUvs);this.x0=0;this.y0=0;this.x1=1;this.y1=0;this.x2=1;this.y2=1;this.x3=0;this.y3=1;this.uvsUint32=new Uint32Array(4);}/** * Sets the texture Uvs based on the given frame information. * * @private * @param {PIXI.Rectangle} frame - The frame of the texture * @param {PIXI.Rectangle} baseFrame - The base frame of the texture * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} */TextureUvs.prototype.set=function set(frame,baseFrame,rotate){var tw=baseFrame.width;var th=baseFrame.height;if(rotate){// width and height div 2 div baseFrame size var w2=frame.width/2/tw;var h2=frame.height/2/th;// coordinates of center var cX=frame.x/tw+w2;var cY=frame.y/th+h2;rotate=_GroupD2.default.add(rotate,_GroupD2.default.NW);// NW is top-left corner this.x0=cX+w2*_GroupD2.default.uX(rotate);this.y0=cY+h2*_GroupD2.default.uY(rotate);rotate=_GroupD2.default.add(rotate,2);// rotate 90 degrees clockwise this.x1=cX+w2*_GroupD2.default.uX(rotate);this.y1=cY+h2*_GroupD2.default.uY(rotate);rotate=_GroupD2.default.add(rotate,2);this.x2=cX+w2*_GroupD2.default.uX(rotate);this.y2=cY+h2*_GroupD2.default.uY(rotate);rotate=_GroupD2.default.add(rotate,2);this.x3=cX+w2*_GroupD2.default.uX(rotate);this.y3=cY+h2*_GroupD2.default.uY(rotate);}else{this.x0=frame.x/tw;this.y0=frame.y/th;this.x1=(frame.x+frame.width)/tw;this.y1=frame.y/th;this.x2=(frame.x+frame.width)/tw;this.y2=(frame.y+frame.height)/th;this.x3=frame.x/tw;this.y3=(frame.y+frame.height)/th;}this.uvsUint32[0]=(this.y0*65535&0xFFFF)<<16|this.x0*65535&0xFFFF;this.uvsUint32[1]=(this.y1*65535&0xFFFF)<<16|this.x1*65535&0xFFFF;this.uvsUint32[2]=(this.y2*65535&0xFFFF)<<16|this.x2*65535&0xFFFF;this.uvsUint32[3]=(this.y3*65535&0xFFFF)<<16|this.x3*65535&0xFFFF;};return TextureUvs;}();exports.default=TextureUvs;},{"../math/GroupD8":62}],111:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i0&&source.paused===false&&source.ended===false&&source.readyState>2;};/** * Returns true if the underlying source is ready for playing. * * @private * @return {boolean} True if ready. */VideoBaseTexture.prototype._isSourceReady=function _isSourceReady(){return this.source.readyState===3||this.source.readyState===4;};/** * Runs the update loop when the video is ready to play * * @private */VideoBaseTexture.prototype._onPlayStart=function _onPlayStart(){// Just in case the video has not received its can play even yet.. if(!this.hasLoaded){this._onCanPlay();}if(!this._isAutoUpdating&&this.autoUpdate){ticker.shared.add(this.update,this);this._isAutoUpdating=true;}};/** * Fired when a pause event is triggered, stops the update loop * * @private */VideoBaseTexture.prototype._onPlayStop=function _onPlayStop(){if(this._isAutoUpdating){ticker.shared.remove(this.update,this);this._isAutoUpdating=false;}};/** * Fired when the video is loaded and ready to play * * @private */VideoBaseTexture.prototype._onCanPlay=function _onCanPlay(){this.hasLoaded=true;if(this.source){this.source.removeEventListener('canplay',this._onCanPlay);this.source.removeEventListener('canplaythrough',this._onCanPlay);this.width=this.source.videoWidth;this.height=this.source.videoHeight;// prevent multiple loaded dispatches.. if(!this.__loaded){this.__loaded=true;this.emit('loaded',this);}if(this._isSourcePlaying()){this._onPlayStart();}else if(this.autoPlay){this.source.play();}}};/** * Destroys this texture * */VideoBaseTexture.prototype.destroy=function destroy(){if(this._isAutoUpdating){ticker.shared.remove(this.update,this);}if(this.source&&this.source._pixiId){delete _utils.BaseTextureCache[this.source._pixiId];delete this.source._pixiId;}_BaseTexture.prototype.destroy.call(this);};/** * Mimic Pixi BaseTexture.from.... method. * * @static * @param {HTMLVideoElement} video - Video to create texture from * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture */VideoBaseTexture.fromVideo=function fromVideo(video,scaleMode){if(!video._pixiId){video._pixiId='video_'+(0,_utils.uid)();}var baseTexture=_utils.BaseTextureCache[video._pixiId];if(!baseTexture){baseTexture=new VideoBaseTexture(video,scaleMode);_utils.BaseTextureCache[video._pixiId]=baseTexture;}return baseTexture;};/** * Helper function that creates a new BaseTexture based on the given video element. * This BaseTexture can then be used to create a texture * * @static * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. * @param {string} [videoSrc.src] - One of the source urls for the video * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified * the url's extension will be used as the second part of the mime type. * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture */VideoBaseTexture.fromUrl=function fromUrl(videoSrc,scaleMode){var video=document.createElement('video');video.setAttribute('webkit-playsinline','');video.setAttribute('playsinline','');// array of objects or strings if(Array.isArray(videoSrc)){for(var i=0;ithis.lastTime){// Save uncapped elapsedMS for measurement elapsedMS=this.elapsedMS=currentTime-this.lastTime;// cap the milliseconds elapsed used for deltaTime if(elapsedMS>this._maxElapsedMS){elapsedMS=this._maxElapsedMS;}this.deltaTime=elapsedMS*_settings2.default.TARGET_FPMS*this.speed;// Invoke listeners added to internal emitter this._emitter.emit(TICK,this.deltaTime);}else{this.deltaTime=this.elapsedMS=0;}this.lastTime=currentTime;};/** * The frames per second at which this ticker is running. * The default is approximately 60 in most modern browsers. * **Note:** This does not factor in the value of * {@link PIXI.ticker.Ticker#speed}, which is specific * to scaling {@link PIXI.ticker.Ticker#deltaTime}. * * @memberof PIXI.ticker.Ticker# * @readonly */_createClass(Ticker,[{key:'FPS',get:function get(){return 1000/this.elapsedMS;}/** * Manages the maximum amount of milliseconds allowed to * elapse between invoking {@link PIXI.ticker.Ticker#update}. * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. * When setting this property it is clamped to a value between * `0` and `PIXI.settings.TARGET_FPMS * 1000`. * * @memberof PIXI.ticker.Ticker# * @default 10 */},{key:'minFPS',get:function get(){return 1000/this._maxElapsedMS;}/** * Sets the min fps. * * @param {number} fps - value to set. */,set:function set(fps){// Clamp: 0 to TARGET_FPMS var minFPMS=Math.min(Math.max(0,fps)/1000,_settings2.default.TARGET_FPMS);this._maxElapsedMS=1/minFPMS;}}]);return Ticker;}();exports.default=Ticker;},{"../settings":97,"eventemitter3":3}],113:[function(require,module,exports){'use strict';exports.__esModule=true;exports.Ticker=exports.shared=undefined;var _Ticker=require('./Ticker');var _Ticker2=_interopRequireDefault(_Ticker);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}/** * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. * and by {@link PIXI.interaction.InteractionManager}. * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` * for this instance. Please follow the examples for usage, including * how to opt-out of auto-starting the shared ticker. * * @example * let ticker = PIXI.ticker.shared; * // Set this to prevent starting this ticker when listeners are added. * // By default this is true only for the PIXI.ticker.shared instance. * ticker.autoStart = false; * // FYI, call this to ensure the ticker is stopped. It should be stopped * // if you have not attempted to render anything yet. * ticker.stop(); * // Call this when you are ready for a running shared ticker. * ticker.start(); * * @example * // You may use the shared ticker to render... * let renderer = PIXI.autoDetectRenderer(800, 600); * let stage = new PIXI.Container(); * let interactionManager = PIXI.interaction.InteractionManager(renderer); * document.body.appendChild(renderer.view); * ticker.add(function (time) { * renderer.render(stage); * }); * * @example * // Or you can just update it manually. * ticker.autoStart = false; * ticker.stop(); * function animate(time) { * ticker.update(time); * renderer.render(stage); * requestAnimationFrame(animate); * } * animate(performance.now()); * * @type {PIXI.ticker.Ticker} * @memberof PIXI.ticker */var shared=new _Ticker2.default();shared.autoStart=true;/** * @namespace PIXI.ticker */exports.shared=shared;exports.Ticker=_Ticker2.default;},{"./Ticker":112}],114:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=canUploadSameBuffer;function canUploadSameBuffer(){// Uploading the same buffer multiple times in a single frame can cause perf issues. // Apparent on IOS so only check for that at the moment // this check may become more complex if this issue pops up elsewhere. var ios=!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform);return!ios;}},{}],115:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=createIndicesForQuads;/** * Generic Mask Stack data structure * * @memberof PIXI * @function createIndicesForQuads * @private * @param {number} size - Number of quads * @return {Uint16Array} indices */function createIndicesForQuads(size){// the total number of indices in our array, there are 6 points per quad. var totalIndices=size*6;var indices=new Uint16Array(totalIndices);// fill the indices with the quads to draw for(var i=0,j=0;i>16&0xFF)/255;out[1]=(hex>>8&0xFF)/255;out[2]=(hex&0xFF)/255;return out;}/** * Converts a hex color number to a string. * * @memberof PIXI.utils * @function hex2string * @param {number} hex - Number in hex * @return {string} The string color. */function hex2string(hex){hex=hex.toString(16);hex='000000'.substr(0,6-hex.length)+hex;return'#'+hex;}/** * Converts a color as an [R, G, B] array to a hex number * * @memberof PIXI.utils * @function rgb2hex * @param {number[]} rgb - rgb array * @return {number} The color number */function rgb2hex(rgb){return(rgb[0]*255<<16)+(rgb[1]*255<<8)+rgb[2]*255;}/** * get the resolution / device pixel ratio of an asset by looking for the prefix * used by spritesheets and image urls * * @memberof PIXI.utils * @function getResolutionOfUrl * @param {string} url - the image path * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. * @return {number} resolution / device pixel ratio of an asset */function getResolutionOfUrl(url,defaultValue){var resolution=_settings2.default.RETINA_PREFIX.exec(url);if(resolution){return parseFloat(resolution[1]);}return defaultValue!==undefined?defaultValue:1;}/** * Typedef for decomposeDataUri return object. * * @typedef {object} DecomposedDataUri * @property {mediaType} Media type, eg. `image` * @property {subType} Sub type, eg. `png` * @property {encoding} Data encoding, eg. `base64` * @property {data} The actual data *//** * Split a data URI into components. Returns undefined if * parameter `dataUri` is not a valid data URI. * * @memberof PIXI.utils * @function decomposeDataUri * @param {string} dataUri - the data URI to check * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined */function decomposeDataUri(dataUri){var dataUriMatch=_const.DATA_URI.exec(dataUri);if(dataUriMatch){return{mediaType:dataUriMatch[1]?dataUriMatch[1].toLowerCase():undefined,subType:dataUriMatch[2]?dataUriMatch[2].toLowerCase():undefined,encoding:dataUriMatch[3]?dataUriMatch[3].toLowerCase():undefined,data:dataUriMatch[4]};}return undefined;}/** * Get type of the image by regexp for extension. Returns undefined for unknown extensions. * * @memberof PIXI.utils * @function getUrlFileExtension * @param {string} url - the image path * @return {string|undefined} image extension */function getUrlFileExtension(url){var extension=_const.URL_FILE_EXTENSION.exec(url);if(extension){return extension[1].toLowerCase();}return undefined;}/** * Typedef for Size object. * * @typedef {object} Size * @property {width} Width component * @property {height} Height component *//** * Get size from an svg string using regexp. * * @memberof PIXI.utils * @function getSvgSize * @param {string} svgString - a serialized svg element * @return {Size|undefined} image extension */function getSvgSize(svgString){var sizeMatch=_const.SVG_SIZE.exec(svgString);var size={};if(sizeMatch){size[sizeMatch[1]]=Math.round(parseFloat(sizeMatch[3]));size[sizeMatch[5]]=Math.round(parseFloat(sizeMatch[7]));}return size;}/** * Skips the hello message of renderers that are created after this is run. * * @function skipHello * @memberof PIXI.utils */function skipHello(){saidHello=true;}/** * Logs out the version and renderer information for this running instance of PIXI. * If you don't want to see this message you can run `PIXI.utils.skipHello()` before * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. * * @static * @function sayHello * @memberof PIXI.utils * @param {string} type - The string renderer type to log. */function sayHello(type){if(saidHello){return;}if(navigator.userAgent.toLowerCase().indexOf('chrome')>-1){var args=['\n %c %c %c Pixi.js '+_const.VERSION+' - ✰ '+type+' ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n','background: #ff66a5; padding:5px 0;','background: #ff66a5; padding:5px 0;','color: #ff66a5; background: #030307; padding:5px 0;','background: #ff66a5; padding:5px 0;','background: #ffc3dc; padding:5px 0;','background: #ff66a5; padding:5px 0;','color: #ff2424; background: #fff; padding:5px 0;','color: #ff2424; background: #fff; padding:5px 0;','color: #ff2424; background: #fff; padding:5px 0;'];window.console.log.apply(console,args);}else if(window.console){window.console.log('Pixi.js '+_const.VERSION+' - '+type+' - http://www.pixijs.com/');}saidHello=true;}/** * Helper for checking for webgl support * * @memberof PIXI.utils * @function isWebGLSupported * @return {boolean} is webgl supported */function isWebGLSupported(){var contextOptions={stencil:true,failIfMajorPerformanceCaveat:true};try{if(!window.WebGLRenderingContext){return false;}var canvas=document.createElement('canvas');var gl=canvas.getContext('webgl',contextOptions)||canvas.getContext('experimental-webgl',contextOptions);var success=!!(gl&&gl.getContextAttributes().stencil);if(gl){var loseContext=gl.getExtension('WEBGL_lose_context');if(loseContext){loseContext.loseContext();}}gl=null;return success;}catch(e){return false;}}/** * Returns sign of number * * @memberof PIXI.utils * @function sign * @param {number} n - the number to check the sign of * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive */function sign(n){if(n===0)return 0;return n<0?-1:1;}/** * Remove a range of items from an array * * @memberof PIXI.utils * @function removeItems * @param {Array<*>} arr The target array * @param {number} startIdx The index to begin removing from (inclusive) * @param {number} removeCount How many items to remove */function removeItems(arr,startIdx,removeCount){var length=arr.length;if(startIdx>=length||removeCount===0){return;}removeCount=startIdx+removeCount>length?length-startIdx:removeCount;var len=length-removeCount;for(var i=startIdx;i1){this._fontStyle='italic';}else if(font.indexOf('oblique')>-1){this._fontStyle='oblique';}else{this._fontStyle='normal';}// can work out fontVariant from search of whole string if(font.indexOf('small-caps')>-1){this._fontVariant='small-caps';}else{this._fontVariant='normal';}// fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units var splits=font.split(' ');var fontSizeIndex=-1;this._fontSize=26;for(var _i=0;_i-1&&fontSizeIndex=this._durations[this.currentFrame]){lag-=this._durations[this.currentFrame]*sign;this._currentTime+=sign;}this._currentTime+=lag/this._durations[this.currentFrame];}else{this._currentTime+=elapsed;}if(this._currentTime<0&&!this.loop){this.gotoAndStop(0);if(this.onComplete){this.onComplete();}}else if(this._currentTime>=this._textures.length&&!this.loop){this.gotoAndStop(this._textures.length-1);if(this.onComplete){this.onComplete();}}else if(previousFrame!==this.currentFrame){this.updateTexture();}};/** * Updates the displayed texture to match the current frame index * * @private */AnimatedSprite.prototype.updateTexture=function updateTexture(){this._texture=this._textures[this.currentFrame];this._textureID=-1;if(this.onFrameChange){this.onFrameChange(this.currentFrame);}};/** * Stops the AnimatedSprite and destroys it * */AnimatedSprite.prototype.destroy=function destroy(){this.stop();_core$Sprite.prototype.destroy.call(this);};/** * A short hand way of creating a movieclip from an array of frame ids * * @static * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames * @return {AnimatedSprite} The new animated sprite with the specified frames. */AnimatedSprite.fromFrames=function fromFrames(frames){var textures=[];for(var i=0;i0&&pos.x*scale>this.maxWidth){core.utils.removeItems(chars,lastSpace,i-lastSpace);i=lastSpace;lastSpace=-1;lineWidths.push(lastSpaceWidth);maxLineWidth=Math.max(maxLineWidth,lastSpaceWidth);line++;pos.x=0;pos.y+=data.lineHeight;prevCharCode=null;continue;}var charData=data.chars[charCode];if(!charData){continue;}if(prevCharCode&&charData.kerning[prevCharCode]){pos.x+=charData.kerning[prevCharCode];}chars.push({texture:charData.texture,line:line,charCode:charCode,position:new core.Point(pos.x+charData.xOffset,pos.y+charData.yOffset)});lastLineWidth=pos.x+(charData.texture.width+charData.xOffset);pos.x+=charData.xAdvance;maxLineHeight=Math.max(maxLineHeight,charData.yOffset+charData.texture.height);prevCharCode=charCode;}lineWidths.push(lastLineWidth);maxLineWidth=Math.max(maxLineWidth,lastLineWidth);var lineAlignOffsets=[];for(var _i=0;_i<=line;_i++){var alignOffset=0;if(this._font.align==='right'){alignOffset=maxLineWidth-lineWidths[_i];}else if(this._font.align==='center'){alignOffset=(maxLineWidth-lineWidths[_i])/2;}lineAlignOffsets.push(alignOffset);}var lenChars=chars.length;var tint=this.tint;for(var _i2=0;_i2=0?value:0xFFFFFF;this.dirty=true;}/** * The alignment of the BitmapText object * * @member {string} * @default 'left' * @memberof PIXI.extras.BitmapText# */},{key:'align',get:function get(){return this._font.align;}/** * Sets the alignment * * @param {string} value - The value to set to. */,set:function set(value){this._font.align=value||'left';this.dirty=true;}/** * The anchor sets the origin point of the text. * The default is 0,0 this means the text's origin is the top left * Setting the anchor to 0.5,0.5 means the text's origin is centered * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner * * @member {PIXI.Point | number} * @memberof PIXI.extras.BitmapText# */},{key:'anchor',get:function get(){return this._anchor;}/** * Sets the anchor. * * @param {PIXI.Point|number} value - The value to set to. */,set:function set(value){if(typeof value==='number'){this._anchor.set(value);}else{this._anchor.copy(value);}}/** * The font descriptor of the BitmapText object * * @member {string|object} * @memberof PIXI.extras.BitmapText# */},{key:'font',get:function get(){return this._font;}/** * Sets the font. * * @param {string|object} value - The value to set to. */,set:function set(value){if(!value){return;}if(typeof value==='string'){value=value.split(' ');this._font.name=value.length===1?value[0]:value.slice(1).join(' ');this._font.size=value.length>=2?parseInt(value[0],10):BitmapText.fonts[this._font.name].size;}else{this._font.name=value.name;this._font.size=typeof value.size==='number'?value.size:parseInt(value.size,10);}this.dirty=true;}/** * The text of the BitmapText object * * @member {string} * @memberof PIXI.extras.BitmapText# */},{key:'text',get:function get(){return this._text;}/** * Sets the text. * * @param {string} value - The value to set to. */,set:function set(value){value=value.toString()||' ';if(this._text===value){return;}this._text=value;this.dirty=true;}/** * The width of the overall text, different from fontSize, * which is defined in the style object * * @member {number} * @memberof PIXI.extras.BitmapText# * @readonly */},{key:'textWidth',get:function get(){this.validate();return this._textWidth;}/** * The height of the overall text, different from fontSize, * which is defined in the style object * * @member {number} * @memberof PIXI.extras.BitmapText# * @readonly */},{key:'textHeight',get:function get(){this.validate();return this._textHeight;}}]);return BitmapText;}(core.Container);exports.default=BitmapText;BitmapText.fonts={};},{"../core":61,"../core/math/ObservablePoint":64}],126:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;ix1&&tempPoint.xy1&&tempPoint.y=halfLength){value=kernelSize-i-1;}blur=blur.replace('%value%',kernel[value]);blurLoop+=blur;blurLoop+='\n';}fragSource=fragSource.replace('%blur%',blurLoop);fragSource=fragSource.replace('%size%',kernelSize);return fragSource;}},{}],137:[function(require,module,exports){'use strict';exports.__esModule=true;exports.default=generateVertBlurSource;var vertTemplate=['attribute vec2 aVertexPosition;','attribute vec2 aTextureCoord;','uniform float strength;','uniform mat3 projectionMatrix;','varying vec2 vBlurTexCoords[%size%];','void main(void)','{','gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);','%blur%','}'].join('\n');function generateVertBlurSource(kernelSize,x){var halfLength=Math.ceil(kernelSize/2);var vertSource=vertTemplate;var blurLoop='';var template=void 0;// let value; if(x){template='vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);';}else{template='vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);';}for(var i=0;i= halfLength) // { // value = kernelSize - i - 1; // } blur=blur.replace('%sampleIndex%',i-(halfLength-1)+'.0');blurLoop+=blur;blurLoop+='\n';}vertSource=vertSource.replace('%blur%',blurLoop);vertSource=vertSource.replace('%size%',kernelSize);return vertSource;}},{}],138:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=getMaxKernelSize;function getMaxKernelSize(gl){var maxVaryings=gl.getParameter(gl.MAX_VARYING_VECTORS);var kernelSize=15;while(kernelSize>maxVaryings){kernelSize-=2;}return kernelSize;}},{}],139:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i * @class * @extends PIXI.Filter * @memberof PIXI.filters */var ColorMatrixFilter=function(_core$Filter){_inherits(ColorMatrixFilter,_core$Filter);/** * */function ColorMatrixFilter(){_classCallCheck(this,ColorMatrixFilter);var _this=_possibleConstructorReturn(this,_core$Filter.call(this,// vertex shader 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}',// fragment shader 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n gl_FragColor.r = (m[0] * c.r);\n gl_FragColor.r += (m[1] * c.g);\n gl_FragColor.r += (m[2] * c.b);\n gl_FragColor.r += (m[3] * c.a);\n gl_FragColor.r += m[4] * c.a;\n\n gl_FragColor.g = (m[5] * c.r);\n gl_FragColor.g += (m[6] * c.g);\n gl_FragColor.g += (m[7] * c.b);\n gl_FragColor.g += (m[8] * c.a);\n gl_FragColor.g += m[9] * c.a;\n\n gl_FragColor.b = (m[10] * c.r);\n gl_FragColor.b += (m[11] * c.g);\n gl_FragColor.b += (m[12] * c.b);\n gl_FragColor.b += (m[13] * c.a);\n gl_FragColor.b += m[14] * c.a;\n\n gl_FragColor.a = (m[15] * c.r);\n gl_FragColor.a += (m[16] * c.g);\n gl_FragColor.a += (m[17] * c.b);\n gl_FragColor.a += (m[18] * c.a);\n gl_FragColor.a += m[19] * c.a;\n\n// gl_FragColor = vec4(m[0]);\n}\n'));_this.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];return _this;}/** * Transforms current matrix and set the new one * * @param {number[]} matrix - 5x4 matrix * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype._loadMatrix=function _loadMatrix(matrix){var multiply=arguments.length<=1||arguments[1]===undefined?false:arguments[1];var newMatrix=matrix;if(multiply){this._multiply(newMatrix,this.uniforms.m,matrix);newMatrix=this._colorMatrix(newMatrix);}// set the new matrix this.uniforms.m=newMatrix;};/** * Multiplies two mat5's * * @private * @param {number[]} out - 5x4 matrix the receiving matrix * @param {number[]} a - 5x4 matrix the first operand * @param {number[]} b - 5x4 matrix the second operand * @returns {number[]} 5x4 matrix */ColorMatrixFilter.prototype._multiply=function _multiply(out,a,b){// Red Channel out[0]=a[0]*b[0]+a[1]*b[5]+a[2]*b[10]+a[3]*b[15];out[1]=a[0]*b[1]+a[1]*b[6]+a[2]*b[11]+a[3]*b[16];out[2]=a[0]*b[2]+a[1]*b[7]+a[2]*b[12]+a[3]*b[17];out[3]=a[0]*b[3]+a[1]*b[8]+a[2]*b[13]+a[3]*b[18];out[4]=a[0]*b[4]+a[1]*b[9]+a[2]*b[14]+a[3]*b[19];// Green Channel out[5]=a[5]*b[0]+a[6]*b[5]+a[7]*b[10]+a[8]*b[15];out[6]=a[5]*b[1]+a[6]*b[6]+a[7]*b[11]+a[8]*b[16];out[7]=a[5]*b[2]+a[6]*b[7]+a[7]*b[12]+a[8]*b[17];out[8]=a[5]*b[3]+a[6]*b[8]+a[7]*b[13]+a[8]*b[18];out[9]=a[5]*b[4]+a[6]*b[9]+a[7]*b[14]+a[8]*b[19];// Blue Channel out[10]=a[10]*b[0]+a[11]*b[5]+a[12]*b[10]+a[13]*b[15];out[11]=a[10]*b[1]+a[11]*b[6]+a[12]*b[11]+a[13]*b[16];out[12]=a[10]*b[2]+a[11]*b[7]+a[12]*b[12]+a[13]*b[17];out[13]=a[10]*b[3]+a[11]*b[8]+a[12]*b[13]+a[13]*b[18];out[14]=a[10]*b[4]+a[11]*b[9]+a[12]*b[14]+a[13]*b[19];// Alpha Channel out[15]=a[15]*b[0]+a[16]*b[5]+a[17]*b[10]+a[18]*b[15];out[16]=a[15]*b[1]+a[16]*b[6]+a[17]*b[11]+a[18]*b[16];out[17]=a[15]*b[2]+a[16]*b[7]+a[17]*b[12]+a[18]*b[17];out[18]=a[15]*b[3]+a[16]*b[8]+a[17]*b[13]+a[18]*b[18];out[19]=a[15]*b[4]+a[16]*b[9]+a[17]*b[14]+a[18]*b[19];return out;};/** * Create a Float32 Array and normalize the offset component to 0-1 * * @private * @param {number[]} matrix - 5x4 matrix * @return {number[]} 5x4 matrix with all values between 0-1 */ColorMatrixFilter.prototype._colorMatrix=function _colorMatrix(matrix){// Create a Float32 Array and normalize the offset component to 0-1 var m=new Float32Array(matrix);m[4]/=255;m[9]/=255;m[14]/=255;m[19]/=255;return m;};/** * Adjusts brightness * * @param {number} b - value of the brigthness (0-1, where 0 is black) * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.brightness=function brightness(b,multiply){var matrix=[b,0,0,0,0,0,b,0,0,0,0,0,b,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Set the matrices in grey scales * * @param {number} scale - value of the grey (0-1, where 0 is black) * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.greyscale=function greyscale(scale,multiply){var matrix=[scale,scale,scale,0,0,scale,scale,scale,0,0,scale,scale,scale,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Set the black and white matrice. * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.blackAndWhite=function blackAndWhite(multiply){var matrix=[0.3,0.6,0.1,0,0,0.3,0.6,0.1,0,0,0.3,0.6,0.1,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Set the hue property of the color * * @param {number} rotation - in degrees * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.hue=function hue(rotation,multiply){rotation=(rotation||0)/180*Math.PI;var cosR=Math.cos(rotation);var sinR=Math.sin(rotation);var sqrt=Math.sqrt;/* a good approximation for hue rotation This matrix is far better than the versions with magic luminance constants formerly used here, but also used in the starling framework (flash) and known from this old part of the internet: quasimondo.com/archives/000565.php This new matrix is based on rgb cube rotation in space. Look here for a more descriptive implementation as a shader not a general matrix: https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js This is the source for the code: see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 */var w=1/3;var sqrW=sqrt(w);// weight is var a00=cosR+(1.0-cosR)*w;var a01=w*(1.0-cosR)-sqrW*sinR;var a02=w*(1.0-cosR)+sqrW*sinR;var a10=w*(1.0-cosR)+sqrW*sinR;var a11=cosR+w*(1.0-cosR);var a12=w*(1.0-cosR)-sqrW*sinR;var a20=w*(1.0-cosR)-sqrW*sinR;var a21=w*(1.0-cosR)+sqrW*sinR;var a22=cosR+w*(1.0-cosR);var matrix=[a00,a01,a02,0,0,a10,a11,a12,0,0,a20,a21,a22,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Set the contrast matrix, increase the separation between dark and bright * Increase contrast : shadows darker and highlights brighter * Decrease contrast : bring the shadows up and the highlights down * * @param {number} amount - value of the contrast (0-1) * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.contrast=function contrast(amount,multiply){var v=(amount||0)+1;var o=-128*(v-1);var matrix=[v,0,0,0,o,0,v,0,0,o,0,0,v,0,o,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Set the saturation matrix, increase the separation between colors * Increase saturation : increase contrast, brightness, and sharpness * * @param {number} amount - The saturation amount (0-1) * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.saturate=function saturate(){var amount=arguments.length<=0||arguments[0]===undefined?0:arguments[0];var multiply=arguments[1];var x=amount*2/3+1;var y=(x-1)*-0.5;var matrix=[x,y,y,0,0,y,x,y,0,0,y,y,x,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Desaturate image (remove color) * * Call the saturate function * */ColorMatrixFilter.prototype.desaturate=function desaturate()// eslint-disable-line no-unused-vars {this.saturate(-1);};/** * Negative image (inverse of classic rgb matrix) * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.negative=function negative(multiply){var matrix=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Sepia image * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.sepia=function sepia(multiply){var matrix=[0.393,0.7689999,0.18899999,0,0,0.349,0.6859999,0.16799999,0,0,0.272,0.5339999,0.13099999,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Color motion picture process invented in 1916 (thanks Dominic Szablewski) * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.technicolor=function technicolor(multiply){var matrix=[1.9125277891456083,-0.8545344976951645,-0.09155508482755585,0,11.793603434377337,-0.3087833385928097,1.7658908555458428,-0.10601743074722245,0,-70.35205161461398,-0.231103377548616,-0.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Polaroid filter * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.polaroid=function polaroid(multiply){var matrix=[1.438,-0.062,-0.062,0,0,-0.122,1.378,-0.122,0,0,-0.016,-0.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Filter who transforms : Red -> Blue and Blue -> Red * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.toBGR=function toBGR(multiply){var matrix=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.kodachrome=function kodachrome(multiply){var matrix=[1.1285582396593525,-0.3967382283601348,-0.03992559172921793,0,63.72958762196502,-0.16404339962244616,1.0835251566291304,-0.05498805115633132,0,24.732407896706203,-0.16786010706155763,-0.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Brown delicious browni filter (thanks Dominic Szablewski) * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.browni=function browni(multiply){var matrix=[0.5997023498159715,0.34553243048391263,-0.2708298674538042,0,47.43192855600873,-0.037703249837783157,0.8609577587992641,0.15059552388459913,0,-36.96841498319127,0.24113635128153335,-0.07441037908422492,0.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Vintage filter (thanks Dominic Szablewski) * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.vintage=function vintage(multiply){var matrix=[0.6279345635605994,0.3202183420819367,-0.03965408211312453,0,9.651285835294123,0.02578397704808868,0.6441188644374771,0.03259127616149294,0,7.462829176470591,0.0466055556782719,-0.0851232987247891,0.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * We don't know exactly what it does, kind of gradient map, but funny to play with! * * @param {number} desaturation - Tone values. * @param {number} toned - Tone values. * @param {string} lightColor - Tone values, example: `0xFFE580` * @param {string} darkColor - Tone values, example: `0xFFE580` * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.colorTone=function colorTone(desaturation,toned,lightColor,darkColor,multiply){desaturation=desaturation||0.2;toned=toned||0.15;lightColor=lightColor||0xFFE580;darkColor=darkColor||0x338000;var lR=(lightColor>>16&0xFF)/255;var lG=(lightColor>>8&0xFF)/255;var lB=(lightColor&0xFF)/255;var dR=(darkColor>>16&0xFF)/255;var dG=(darkColor>>8&0xFF)/255;var dB=(darkColor&0xFF)/255;var matrix=[0.3,0.59,0.11,0,0,lR,lG,lB,desaturation,0,dR,dG,dB,toned,0,lR-dR,lG-dG,lB-dB,0,0];this._loadMatrix(matrix,multiply);};/** * Night effect * * @param {number} intensity - The intensity of the night effect. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.night=function night(intensity,multiply){intensity=intensity||0.1;var matrix=[intensity*-2.0,-intensity,0,0,0,-intensity,0,intensity,0,0,0,intensity,intensity*2.0,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Predator effect * * Erase the current matrix by setting a new indepent one * * @param {number} amount - how much the predator feels his future victim * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.predator=function predator(amount,multiply){var matrix=[// row 1 11.224130630493164*amount,-4.794486999511719*amount,-2.8746118545532227*amount,0*amount,0.40342438220977783*amount,// row 2 -3.6330697536468506*amount,9.193157196044922*amount,-2.951810836791992*amount,0*amount,-1.316135048866272*amount,// row 3 -3.2184197902679443*amount,-4.2375030517578125*amount,7.476448059082031*amount,0*amount,0.8044459223747253*amount,// row 4 0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * LSD effect * * Multiply the current matrix * * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, * just set the current matrix with @param matrix */ColorMatrixFilter.prototype.lsd=function lsd(multiply){var matrix=[2,-0.4,0.5,0,0,-0.5,2,-0.4,0,0,-0.4,-0.5,3,0,0,0,0,0,1,0];this._loadMatrix(matrix,multiply);};/** * Erase the current matrix by setting the default one * */ColorMatrixFilter.prototype.reset=function reset(){var matrix=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(matrix,false);};/** * The matrix of the color matrix filter * * @member {number[]} * @memberof PIXI.filters.ColorMatrixFilter# * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] */_createClass(ColorMatrixFilter,[{key:'matrix',get:function get(){return this.uniforms.m;}/** * Sets the matrix directly. * * @param {number[]} value - the value to set to. */,set:function set(value){this.uniforms.m=value;}}]);return ColorMatrixFilter;}(core.Filter);// Americanized alias exports.default=ColorMatrixFilter;ColorMatrixFilter.prototype.grayscale=ColorMatrixFilter.prototype.greyscale;},{"../../core":61,"path":22}],140:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'));}return FXAAFilter;}(core.Filter);exports.default=FXAAFilter;},{"../../core":61,"path":22}],142:[function(require,module,exports){'use strict';exports.__esModule=true;var _FXAAFilter=require('./fxaa/FXAAFilter');Object.defineProperty(exports,'FXAAFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_FXAAFilter).default;}});var _NoiseFilter=require('./noise/NoiseFilter');Object.defineProperty(exports,'NoiseFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_NoiseFilter).default;}});var _DisplacementFilter=require('./displacement/DisplacementFilter');Object.defineProperty(exports,'DisplacementFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_DisplacementFilter).default;}});var _BlurFilter=require('./blur/BlurFilter');Object.defineProperty(exports,'BlurFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_BlurFilter).default;}});var _BlurXFilter=require('./blur/BlurXFilter');Object.defineProperty(exports,'BlurXFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_BlurXFilter).default;}});var _BlurYFilter=require('./blur/BlurYFilter');Object.defineProperty(exports,'BlurYFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_BlurYFilter).default;}});var _ColorMatrixFilter=require('./colormatrix/ColorMatrixFilter');Object.defineProperty(exports,'ColorMatrixFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_ColorMatrixFilter).default;}});var _VoidFilter=require('./void/VoidFilter');Object.defineProperty(exports,'VoidFilter',{enumerable:true,get:function get(){return _interopRequireDefault(_VoidFilter).default;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./blur/BlurFilter":133,"./blur/BlurXFilter":134,"./blur/BlurYFilter":135,"./colormatrix/ColorMatrixFilter":139,"./displacement/DisplacementFilter":140,"./fxaa/FXAAFilter":141,"./noise/NoiseFilter":143,"./void/VoidFilter":144}],143:[function(require,module,exports){'use strict';exports.__esModule=true;var _createClass=function(){function defineProperties(target,props){for(var i=0;i=0;i--){var child=children[i];// time to get recursive.. if this function will return if something is hit.. if(this.processInteractive(point,child,func,hitTest,interactiveParent)){// its a good idea to check if a child has lost its parent. // this means it has been removed whilst looping so its best if(!child.parent){continue;}hit=true;// we no longer need to hit test any more objects in this container as we we // now know the parent has been hit interactiveParent=false;// If the child is interactive , that means that the object hit was actually // interactive and not just the child of an interactive object. // This means we no longer need to hit test anything else. We still need to run // through all objects, but we don't need to perform any hit tests. // { hitTest=false;// } // we can break now as we have hit an object. }}}// no point running this if the item is not interactive or does not have an interactive parent. if(interactive){// if we are hit testing (as in we have no hit any objects yet) // We also don't need to worry about hit testing if once of the displayObjects children // has already been hit! if(hitTest&&!hit){if(displayObject.hitArea){displayObject.worldTransform.applyInverse(point,this._tempPoint);hit=displayObject.hitArea.contains(this._tempPoint.x,this._tempPoint.y);}else if(displayObject.containsPoint){hit=displayObject.containsPoint(point);}}if(displayObject.interactive){if(hit&&!this.eventData.target){this.eventData.target=displayObject;this.mouse.target=displayObject;this.pointer.target=displayObject;}func(displayObject,hit);}}return hit;};/** * Is called when the mouse button is pressed down on the renderer element * * @private * @param {MouseEvent} event - The DOM event of a mouse button being pressed down */InteractionManager.prototype.onMouseDown=function onMouseDown(event){this.mouse.originalEvent=event;this.eventData.data=this.mouse;this.eventData._reset();// Update internal mouse reference this.mapPositionToPoint(this.mouse.global,event.clientX,event.clientY);if(this.autoPreventDefault){this.mouse.originalEvent.preventDefault();}this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseDown,true);var isRightButton=event.button===2||event.which===3;this.emit(isRightButton?'rightdown':'mousedown',this.eventData);};/** * Processes the result of the mouse down check and dispatches the event if need be * * @private * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */InteractionManager.prototype.processMouseDown=function processMouseDown(displayObject,hit){var e=this.mouse.originalEvent;var isRightButton=e.button===2||e.which===3;if(hit){displayObject[isRightButton?'_isRightDown':'_isLeftDown']=true;this.dispatchEvent(displayObject,isRightButton?'rightdown':'mousedown',this.eventData);}};/** * Is called when the mouse button is released on the renderer element * * @private * @param {MouseEvent} event - The DOM event of a mouse button being released */InteractionManager.prototype.onMouseUp=function onMouseUp(event){this.mouse.originalEvent=event;this.eventData.data=this.mouse;this.eventData._reset();// Update internal mouse reference this.mapPositionToPoint(this.mouse.global,event.clientX,event.clientY);this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseUp,true);var isRightButton=event.button===2||event.which===3;this.emit(isRightButton?'rightup':'mouseup',this.eventData);};/** * Processes the result of the mouse up check and dispatches the event if need be * * @private * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */InteractionManager.prototype.processMouseUp=function processMouseUp(displayObject,hit){var e=this.mouse.originalEvent;var isRightButton=e.button===2||e.which===3;var isDown=isRightButton?'_isRightDown':'_isLeftDown';if(hit){this.dispatchEvent(displayObject,isRightButton?'rightup':'mouseup',this.eventData);if(displayObject[isDown]){displayObject[isDown]=false;this.dispatchEvent(displayObject,isRightButton?'rightclick':'click',this.eventData);}}else if(displayObject[isDown]){displayObject[isDown]=false;this.dispatchEvent(displayObject,isRightButton?'rightupoutside':'mouseupoutside',this.eventData);}};/** * Is called when the mouse moves across the renderer element * * @private * @param {MouseEvent} event - The DOM event of the mouse moving */InteractionManager.prototype.onMouseMove=function onMouseMove(event){this.mouse.originalEvent=event;this.eventData.data=this.mouse;this.eventData._reset();this.mapPositionToPoint(this.mouse.global,event.clientX,event.clientY);this.didMove=true;this.cursor=this.defaultCursorStyle;this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseMove,true);this.emit('mousemove',this.eventData);if(this.currentCursorStyle!==this.cursor){this.currentCursorStyle=this.cursor;this.interactionDOMElement.style.cursor=this.cursor;}// TODO BUG for parents interactive object (border order issue) };/** * Processes the result of the mouse move check and dispatches the event if need be * * @private * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */InteractionManager.prototype.processMouseMove=function processMouseMove(displayObject,hit){this.processMouseOverOut(displayObject,hit);// only display on mouse over if(!this.moveWhenInside||hit){this.dispatchEvent(displayObject,'mousemove',this.eventData);}};/** * Is called when the mouse is moved out of the renderer element * * @private * @param {MouseEvent} event - The DOM event of the mouse being moved out */InteractionManager.prototype.onMouseOut=function onMouseOut(event){this.mouseOverRenderer=false;this.mouse.originalEvent=event;this.eventData.data=this.mouse;this.eventData._reset();// Update internal mouse reference this.mapPositionToPoint(this.mouse.global,event.clientX,event.clientY);this.interactionDOMElement.style.cursor=this.defaultCursorStyle;// TODO optimize by not check EVERY TIME! maybe half as often? // this.mapPositionToPoint(this.mouse.global,event.clientX,event.clientY);this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseOverOut,false);this.emit('mouseout',this.eventData);};/** * Processes the result of the mouse over/out check and dispatches the event if need be * * @private * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */InteractionManager.prototype.processMouseOverOut=function processMouseOverOut(displayObject,hit){if(hit&&this.mouseOverRenderer){if(!displayObject._mouseOver){displayObject._mouseOver=true;this.dispatchEvent(displayObject,'mouseover',this.eventData);}if(displayObject.buttonMode){this.cursor=displayObject.defaultCursor;}}else if(displayObject._mouseOver){displayObject._mouseOver=false;this.dispatchEvent(displayObject,'mouseout',this.eventData);}};/** * Is called when the mouse enters the renderer element area * * @private * @param {MouseEvent} event - The DOM event of the mouse moving into the renderer view */InteractionManager.prototype.onMouseOver=function onMouseOver(event){this.mouseOverRenderer=true;this.mouse.originalEvent=event;this.eventData.data=this.mouse;this.eventData._reset();this.emit('mouseover',this.eventData);};/** * Is called when the pointer button is pressed down on the renderer element * * @private * @param {PointerEvent} event - The DOM event of a pointer button being pressed down */InteractionManager.prototype.onPointerDown=function onPointerDown(event){this.normalizeToPointerData(event);this.pointer.originalEvent=event;this.eventData.data=this.pointer;this.eventData._reset();// Update internal pointer reference this.mapPositionToPoint(this.pointer.global,event.clientX,event.clientY);/** * No need to prevent default on natural pointer events, as there are no side effects * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, * so still need to be prevented. */if(this.autoPreventDefault&&(this.normalizeMouseEvents||this.normalizeTouchEvents)){this.pointer.originalEvent.preventDefault();}this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerDown,true);this.emit('pointerdown',this.eventData);};/** * Processes the result of the pointer down check and dispatches the event if need be * * @private * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */InteractionManager.prototype.processPointerDown=function processPointerDown(displayObject,hit){if(hit){displayObject._pointerDown=true;this.dispatchEvent(displayObject,'pointerdown',this.eventData);}};/** * Is called when the pointer button is released on the renderer element * * @private * @param {PointerEvent} event - The DOM event of a pointer button being released */InteractionManager.prototype.onPointerUp=function onPointerUp(event){this.normalizeToPointerData(event);this.pointer.originalEvent=event;this.eventData.data=this.pointer;this.eventData._reset();// Update internal pointer reference this.mapPositionToPoint(this.pointer.global,event.clientX,event.clientY);this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerUp,true);this.emit('pointerup',this.eventData);};/** * Processes the result of the pointer up check and dispatches the event if need be * * @private * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */InteractionManager.prototype.processPointerUp=function processPointerUp(displayObject,hit){if(hit){this.dispatchEvent(displayObject,'pointerup',this.eventData);if(displayObject._pointerDown){displayObject._pointerDown=false;this.dispatchEvent(displayObject,'pointertap',this.eventData);}}else if(displayObject._pointerDown){displayObject._pointerDown=false;this.dispatchEvent(displayObject,'pointerupoutside',this.eventData);}};/** * Is called when the pointer moves across the renderer element * * @private * @param {PointerEvent} event - The DOM event of a pointer moving */InteractionManager.prototype.onPointerMove=function onPointerMove(event){this.normalizeToPointerData(event);this.pointer.originalEvent=event;this.eventData.data=this.pointer;this.eventData._reset();this.mapPositionToPoint(this.pointer.global,event.clientX,event.clientY);this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerMove,true);this.emit('pointermove',this.eventData);};/** * Processes the result of the pointer move check and dispatches the event if need be * * @private * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */InteractionManager.prototype.processPointerMove=function processPointerMove(displayObject,hit){if(!this.pointer.originalEvent.changedTouches){this.processPointerOverOut(displayObject,hit);}if(!this.moveWhenInside||hit){this.dispatchEvent(displayObject,'pointermove',this.eventData);}};/** * Is called when the pointer is moved out of the renderer element * * @private * @param {PointerEvent} event - The DOM event of a pointer being moved out */InteractionManager.prototype.onPointerOut=function onPointerOut(event){this.normalizeToPointerData(event);this.pointer.originalEvent=event;this.eventData.data=this.pointer;this.eventData._reset();// Update internal pointer reference this.mapPositionToPoint(this.pointer.global,event.clientX,event.clientY);this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerOverOut,false);this.emit('pointerout',this.eventData);};/** * Processes the result of the pointer over/out check and dispatches the event if need be * * @private * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested * @param {boolean} hit - the result of the hit test on the display object */InteractionManager.prototype.processPointerOverOut=function processPointerOverOut(displayObject,hit){if(hit&&this.mouseOverRenderer){if(!displayObject._pointerOver){displayObject._pointerOver=true;this.dispatchEvent(displayObject,'pointerover',this.eventData);}}else if(displayObject._pointerOver){displayObject._pointerOver=false;this.dispatchEvent(displayObject,'pointerout',this.eventData);}};/** * Is called when the pointer is moved into the renderer element * * @private * @param {PointerEvent} event - The DOM event of a pointer button being moved into the renderer view */InteractionManager.prototype.onPointerOver=function onPointerOver(event){this.pointer.originalEvent=event;this.eventData.data=this.pointer;this.eventData._reset();this.emit('pointerover',this.eventData);};/** * Is called when a touch is started on the renderer element * * @private * @param {TouchEvent} event - The DOM event of a touch starting on the renderer view */InteractionManager.prototype.onTouchStart=function onTouchStart(event){if(this.autoPreventDefault){event.preventDefault();}var changedTouches=event.changedTouches;var cLength=changedTouches.length;for(var i=0;i} */_this._glDatas={};/** * Plugin that is responsible for rendering this element. * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. * * @member {string} * @default 'mesh' */_this.pluginName='mesh';return _this;}/** * Renders the object using the WebGL renderer * * @private * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer */Mesh.prototype._renderWebGL=function _renderWebGL(renderer){renderer.setObjectRenderer(renderer.plugins[this.pluginName]);renderer.plugins[this.pluginName].render(this);};/** * Renders the object using the Canvas renderer * * @private * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. */Mesh.prototype._renderCanvas=function _renderCanvas(renderer){renderer.plugins[this.pluginName].render(this);};/** * When the texture is updated, this event will fire to update the scale and frame * * @private */Mesh.prototype._onTextureUpdate=function _onTextureUpdate(){}/* empty *//** * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. * */;Mesh.prototype._calculateBounds=function _calculateBounds(){// TODO - we can cache local bounds and use them if they are dirty (like graphics) this._bounds.addVertices(this.transform,this.vertices,0,this.vertices.length);};/** * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH * * @param {PIXI.Point} point - the point to test * @return {boolean} the result of the test */Mesh.prototype.containsPoint=function containsPoint(point){if(!this.getBounds().contains(point.x,point.y)){return false;}this.worldTransform.applyInverse(point,tempPoint);var vertices=this.vertices;var points=tempPolygon.points;var indices=this.indices;var len=this.indices.length;var step=this.drawMode===Mesh.DRAW_MODES.TRIANGLES?3:1;for(var i=0;i+2 * A B * +---+----------------------+---+ * C | 1 | 2 | 3 | * +---+----------------------+---+ * | | | | * | 4 | 5 | 6 | * | | | | * +---+----------------------+---+ * D | 7 | 8 | 9 | * +---+----------------------+---+ * When changing this objects width and/or height: * areas 1 3 7 and 9 will remain unscaled. * areas 2 and 8 will be stretched horizontally * areas 4 and 6 will be stretched vertically * area 5 will be stretched both horizontally and vertically * * * @class * @extends PIXI.mesh.Plane * @memberof PIXI.mesh * */var NineSlicePlane=function(_Plane){_inherits(NineSlicePlane,_Plane);/** * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. * @param {int} [leftWidth=10] size of the left vertical bar (A) * @param {int} [topHeight=10] size of the top horizontal bar (C) * @param {int} [rightWidth=10] size of the right vertical bar (B) * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) */function NineSlicePlane(texture,leftWidth,topHeight,rightWidth,bottomHeight){_classCallCheck(this,NineSlicePlane);var _this=_possibleConstructorReturn(this,_Plane.call(this,texture,4,4));var uvs=_this.uvs;// right and bottom uv's are always 1 uvs[6]=uvs[14]=uvs[22]=uvs[30]=1;uvs[25]=uvs[27]=uvs[29]=uvs[31]=1;_this._origWidth=texture.width;_this._origHeight=texture.height;_this._uvw=1/_this._origWidth;_this._uvh=1/_this._origHeight;/** * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane * * @member {number} * @memberof PIXI.NineSlicePlane# * @override */_this.width=texture.width;/** * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane * * @member {number} * @memberof PIXI.NineSlicePlane# * @override */_this.height=texture.height;uvs[2]=uvs[10]=uvs[18]=uvs[26]=_this._uvw*leftWidth;uvs[4]=uvs[12]=uvs[20]=uvs[28]=1-_this._uvw*rightWidth;uvs[9]=uvs[11]=uvs[13]=uvs[15]=_this._uvh*topHeight;uvs[17]=uvs[19]=uvs[21]=uvs[23]=1-_this._uvh*bottomHeight;/** * The width of the left column (a) * * @member {number} */_this.leftWidth=typeof leftWidth!=='undefined'?leftWidth:DEFAULT_BORDER_SIZE;/** * The width of the right column (b) * * @member {number} */_this.rightWidth=typeof rightWidth!=='undefined'?rightWidth:DEFAULT_BORDER_SIZE;/** * The height of the top row (c) * * @member {number} */_this.topHeight=typeof topHeight!=='undefined'?topHeight:DEFAULT_BORDER_SIZE;/** * The height of the bottom row (d) * * @member {number} */_this.bottomHeight=typeof bottomHeight!=='undefined'?bottomHeight:DEFAULT_BORDER_SIZE;return _this;}/** * Updates the horizontal vertices. * */NineSlicePlane.prototype.updateHorizontalVertices=function updateHorizontalVertices(){var vertices=this.vertices;vertices[9]=vertices[11]=vertices[13]=vertices[15]=this._topHeight;vertices[17]=vertices[19]=vertices[21]=vertices[23]=this._height-this._bottomHeight;vertices[25]=vertices[27]=vertices[29]=vertices[31]=this._height;};/** * Updates the vertical vertices. * */NineSlicePlane.prototype.updateVerticalVertices=function updateVerticalVertices(){var vertices=this.vertices;vertices[2]=vertices[10]=vertices[18]=vertices[26]=this._leftWidth;vertices[4]=vertices[12]=vertices[20]=vertices[28]=this._width-this._rightWidth;vertices[6]=vertices[14]=vertices[22]=vertices[30]=this._width;};/** * Renders the object using the Canvas renderer * * @private * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. */NineSlicePlane.prototype._renderCanvas=function _renderCanvas(renderer){var context=renderer.context;context.globalAlpha=this.worldAlpha;var transform=this.worldTransform;var res=renderer.resolution;if(renderer.roundPixels){context.setTransform(transform.a*res,transform.b*res,transform.c*res,transform.d*res,transform.tx*res|0,transform.ty*res|0);}else{context.setTransform(transform.a*res,transform.b*res,transform.c*res,transform.d*res,transform.tx*res,transform.ty*res);}var base=this._texture.baseTexture;var textureSource=base.source;var w=base.width;var h=base.height;this.drawSegment(context,textureSource,w,h,0,1,10,11);this.drawSegment(context,textureSource,w,h,2,3,12,13);this.drawSegment(context,textureSource,w,h,4,5,14,15);this.drawSegment(context,textureSource,w,h,8,9,18,19);this.drawSegment(context,textureSource,w,h,10,11,20,21);this.drawSegment(context,textureSource,w,h,12,13,22,23);this.drawSegment(context,textureSource,w,h,16,17,26,27);this.drawSegment(context,textureSource,w,h,18,19,28,29);this.drawSegment(context,textureSource,w,h,20,21,30,31);};/** * Renders one segment of the plane. * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. * * @private * @param {CanvasRenderingContext2D} context - The context to draw with. * @param {CanvasImageSource} textureSource - The source to draw. * @param {number} w - width of the texture * @param {number} h - height of the texture * @param {number} x1 - x index 1 * @param {number} y1 - y index 1 * @param {number} x2 - x index 2 * @param {number} y2 - y index 2 */NineSlicePlane.prototype.drawSegment=function drawSegment(context,textureSource,w,h,x1,y1,x2,y2){// otherwise you get weird results when using slices of that are 0 wide or high. var uvs=this.uvs;var vertices=this.vertices;var sw=(uvs[x2]-uvs[x1])*w;var sh=(uvs[y2]-uvs[y1])*h;var dw=vertices[x2]-vertices[x1];var dh=vertices[y2]-vertices[y1];// make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. if(sw<1){sw=1;}if(sh<1){sh=1;}// make sure destination is at least 1 pixel wide and high, otherwise you get // lines when rendering close to original size. if(dw<1){dw=1;}if(dh<1){dh=1;}context.drawImage(textureSource,uvs[x1]*w,uvs[y1]*h,sw,sh,vertices[x1],vertices[y1],dw,dh);};/** * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane * * @member {number} * @memberof PIXI.NineSlicePlane# */_createClass(NineSlicePlane,[{key:'width',get:function get(){return this._width;}/** * Sets the width. * * @param {number} value - the value to set to. */,set:function set(value){this._width=value;this.updateVerticalVertices();}/** * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane * * @member {number} * @memberof PIXI.NineSlicePlane# */},{key:'height',get:function get(){return this._height;}/** * Sets the height. * * @param {number} value - the value to set to. */,set:function set(value){this._height=value;this.updateHorizontalVertices();}/** * The width of the left column * * @member {number} */},{key:'leftWidth',get:function get(){return this._leftWidth;}/** * Sets the width of the left column. * * @param {number} value - the value to set to. */,set:function set(value){this._leftWidth=value;var uvs=this.uvs;var vertices=this.vertices;uvs[2]=uvs[10]=uvs[18]=uvs[26]=this._uvw*value;vertices[2]=vertices[10]=vertices[18]=vertices[26]=value;this.dirty=true;}/** * The width of the right column * * @member {number} */},{key:'rightWidth',get:function get(){return this._rightWidth;}/** * Sets the width of the right column. * * @param {number} value - the value to set to. */,set:function set(value){this._rightWidth=value;var uvs=this.uvs;var vertices=this.vertices;uvs[4]=uvs[12]=uvs[20]=uvs[28]=1-this._uvw*value;vertices[4]=vertices[12]=vertices[20]=vertices[28]=this._width-value;this.dirty=true;}/** * The height of the top row * * @member {number} */},{key:'topHeight',get:function get(){return this._topHeight;}/** * Sets the height of the top row. * * @param {number} value - the value to set to. */,set:function set(value){this._topHeight=value;var uvs=this.uvs;var vertices=this.vertices;uvs[9]=uvs[11]=uvs[13]=uvs[15]=this._uvh*value;vertices[9]=vertices[11]=vertices[13]=vertices[15]=value;this.dirty=true;}/** * The height of the bottom row * * @member {number} */},{key:'bottomHeight',get:function get(){return this._bottomHeight;}/** * Sets the height of the bottom row. * * @param {number} value - the value to set to. */,set:function set(value){this._bottomHeight=value;var uvs=this.uvs;var vertices=this.vertices;uvs[17]=uvs[19]=uvs[21]=uvs[23]=1-this._uvh*value;vertices[17]=vertices[19]=vertices[21]=vertices[23]=this._height-value;this.dirty=true;}}]);return NineSlicePlane;}(_Plane3.default);exports.default=NineSlicePlane;},{"./Plane":157}],157:[function(require,module,exports){'use strict';exports.__esModule=true;var _Mesh2=require('./Mesh');var _Mesh3=_interopRequireDefault(_Mesh2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}/** * The Plane allows you to draw a texture across several points and them manipulate these points * *```js * for (let i = 0; i < 20; i++) { * points.push(new PIXI.Point(i * 50, 0)); * }; * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); * ``` * * @class * @extends PIXI.mesh.Mesh * @memberof PIXI.mesh * */var Plane=function(_Mesh){_inherits(Plane,_Mesh);/** * @param {PIXI.Texture} texture - The texture to use on the Plane. * @param {number} verticesX - The number of vertices in the x-axis * @param {number} verticesY - The number of vertices in the y-axis */function Plane(texture,verticesX,verticesY){_classCallCheck(this,Plane);/** * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can * call _onTextureUpdated which could call refresh too early. * * @member {boolean} * @private */var _this=_possibleConstructorReturn(this,_Mesh.call(this,texture));_this._ready=true;_this.verticesX=verticesX||10;_this.verticesY=verticesY||10;_this.drawMode=_Mesh3.default.DRAW_MODES.TRIANGLES;_this.refresh();return _this;}/** * Refreshes * */Plane.prototype.refresh=function refresh(){var total=this.verticesX*this.verticesY;var verts=[];var colors=[];var uvs=[];var indices=[];var texture=this.texture;var segmentsX=this.verticesX-1;var segmentsY=this.verticesY-1;var sizeX=texture.width/segmentsX;var sizeY=texture.height/segmentsY;for(var i=0;i1){ratio=1;}var perpLength=Math.sqrt(perpX*perpX+perpY*perpY);var num=this._texture.height/2;// (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; perpX/=perpLength;perpY/=perpLength;perpX*=num;perpY*=num;vertices[index]=point.x+perpX;vertices[index+1]=point.y+perpY;vertices[index+2]=point.x-perpX;vertices[index+3]=point.y-perpY;lastPoint=point;}this.containerUpdateTransform();};return Rope;}(_Mesh3.default);exports.default=Rope;},{"../core":61,"./Mesh":155}],159:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);var _Mesh=require('../Mesh');var _Mesh2=_interopRequireDefault(_Mesh);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/** * Renderer dedicated to meshes. * * @class * @private * @memberof PIXI */var MeshSpriteRenderer=function(){/** * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for */function MeshSpriteRenderer(renderer){_classCallCheck(this,MeshSpriteRenderer);this.renderer=renderer;}/** * Renders the Mesh * * @param {PIXI.mesh.Mesh} mesh - the Mesh to render */MeshSpriteRenderer.prototype.render=function render(mesh){var renderer=this.renderer;var context=renderer.context;var transform=mesh.worldTransform;var res=renderer.resolution;if(renderer.roundPixels){context.setTransform(transform.a*res,transform.b*res,transform.c*res,transform.d*res,transform.tx*res|0,transform.ty*res|0);}else{context.setTransform(transform.a*res,transform.b*res,transform.c*res,transform.d*res,transform.tx*res,transform.ty*res);}renderer.setBlendMode(mesh.blendMode);if(mesh.drawMode===_Mesh2.default.DRAW_MODES.TRIANGLE_MESH){this._renderTriangleMesh(mesh);}else{this._renderTriangles(mesh);}};/** * Draws the object in Triangle Mesh mode * * @private * @param {PIXI.mesh.Mesh} mesh - the Mesh to render */MeshSpriteRenderer.prototype._renderTriangleMesh=function _renderTriangleMesh(mesh){// draw triangles!! var length=mesh.vertices.length/2;for(var i=0;i0){var paddingX=mesh.canvasPadding/mesh.worldTransform.a;var paddingY=mesh.canvasPadding/mesh.worldTransform.d;var centerX=(x0+x1+x2)/3;var centerY=(y0+y1+y2)/3;var normX=x0-centerX;var normY=y0-centerY;var dist=Math.sqrt(normX*normX+normY*normY);x0=centerX+normX/dist*(dist+paddingX);y0=centerY+normY/dist*(dist+paddingY);// normX=x1-centerX;normY=y1-centerY;dist=Math.sqrt(normX*normX+normY*normY);x1=centerX+normX/dist*(dist+paddingX);y1=centerY+normY/dist*(dist+paddingY);normX=x2-centerX;normY=y2-centerY;dist=Math.sqrt(normX*normX+normY*normY);x2=centerX+normX/dist*(dist+paddingX);y2=centerY+normY/dist*(dist+paddingY);}context.save();context.beginPath();context.moveTo(x0,y0);context.lineTo(x1,y1);context.lineTo(x2,y2);context.closePath();context.clip();// Compute matrix transform var delta=u0*v1+v0*u2+u1*v2-v1*u2-v0*u1-u0*v2;var deltaA=x0*v1+v0*x2+x1*v2-v1*x2-v0*x1-x0*v2;var deltaB=u0*x1+x0*u2+u1*x2-x1*u2-x0*u1-u0*x2;var deltaC=u0*v1*x2+v0*x1*u2+x0*u1*v2-x0*v1*u2-v0*u1*x2-u0*x1*v2;var deltaD=y0*v1+v0*y2+y1*v2-v1*y2-v0*y1-y0*v2;var deltaE=u0*y1+y0*u2+u1*y2-y1*u2-y0*u1-u0*y2;var deltaF=u0*v1*y2+v0*y1*u2+y0*u1*v2-y0*v1*u2-v0*u1*y2-u0*y1*v2;context.transform(deltaA/delta,deltaD/delta,deltaB/delta,deltaE/delta,deltaC/delta,deltaF/delta);context.drawImage(textureSource,0,0,textureWidth*base.resolution,textureHeight*base.resolution,0,0,textureWidth,textureHeight);context.restore();};/** * Renders a flat Mesh * * @private * @param {PIXI.mesh.Mesh} mesh - The Mesh to render */MeshSpriteRenderer.prototype.renderMeshFlat=function renderMeshFlat(mesh){var context=this.renderer.context;var vertices=mesh.vertices;var length=vertices.length/2;// this.count++; context.beginPath();for(var i=1;imaxBatchSize){batchSize=maxBatchSize;}if(batchSize>maxSize){batchSize=maxSize;}/** * Set properties to be dynamic (true) / static (false) * * @member {boolean[]} * @private */_this._properties=[false,true,false,false,false];/** * @member {number} * @private */_this._maxSize=maxSize;/** * @member {number} * @private */_this._batchSize=batchSize;/** * @member {object} * @private */_this._glBuffers={};/** * @member {number} * @private */_this._bufferToUpdate=0;/** * @member {boolean} * */_this.interactiveChildren=false;/** * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` * to reset the blend mode. * * @member {number} * @default PIXI.BLEND_MODES.NORMAL * @see PIXI.BLEND_MODES */_this.blendMode=core.BLEND_MODES.NORMAL;/** * Used for canvas renderering. If true then the elements will be positioned at the * nearest pixel. This provides a nice speed boost. * * @member {boolean} * @default true; */_this.roundPixels=true;/** * The texture used to render the children. * * @readonly * @member {BaseTexture} */_this.baseTexture=null;_this.setProperties(properties);return _this;}/** * Sets the private properties array to dynamic / static based on the passed properties object * * @param {object} properties - The properties to be uploaded */ParticleContainer.prototype.setProperties=function setProperties(properties){if(properties){this._properties[0]='scale'in properties?!!properties.scale:this._properties[0];this._properties[1]='position'in properties?!!properties.position:this._properties[1];this._properties[2]='rotation'in properties?!!properties.rotation:this._properties[2];this._properties[3]='uvs'in properties?!!properties.uvs:this._properties[3];this._properties[4]='alpha'in properties?!!properties.alpha:this._properties[4];}};/** * Updates the object transform for rendering * * @private */ParticleContainer.prototype.updateTransform=function updateTransform(){// TODO don't need to! this.displayObjectUpdateTransform();// PIXI.Container.prototype.updateTransform.call( this ); };/** * Renders the container using the WebGL renderer * * @private * @param {PIXI.WebGLRenderer} renderer - The webgl renderer */ParticleContainer.prototype.renderWebGL=function renderWebGL(renderer){var _this2=this;if(!this.visible||this.worldAlpha<=0||!this.children.length||!this.renderable){return;}if(!this.baseTexture){this.baseTexture=this.children[0]._texture.baseTexture;if(!this.baseTexture.hasLoaded){this.baseTexture.once('update',function(){return _this2.onChildrenChange(0);});}}renderer.setObjectRenderer(renderer.plugins.particle);renderer.plugins.particle.render(this);};/** * Set the flag that static data should be updated to true * * @private * @param {number} smallestChildIndex - The smallest child index */ParticleContainer.prototype.onChildrenChange=function onChildrenChange(smallestChildIndex){var bufferIndex=Math.floor(smallestChildIndex/this._batchSize);if(bufferIndex https://github.com/mattdesl/ * for creating the original pixi version! * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that * they now share 4 bytes on the vertex buffer * * Heavily inspired by LibGDX's ParticleBuffer: * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java *//** * The particle buffer manages the static and dynamic buffers for a particle container. * * @class * @private * @memberof PIXI */var ParticleBuffer=function(){/** * @param {WebGLRenderingContext} gl - The rendering context. * @param {object} properties - The properties to upload. * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. * @param {number} size - The size of the batch. */function ParticleBuffer(gl,properties,dynamicPropertyFlags,size){_classCallCheck(this,ParticleBuffer);/** * The current WebGL drawing context. * * @member {WebGLRenderingContext} */this.gl=gl;/** * Size of a single vertex. * * @member {number} */this.vertSize=2;/** * Size of a single vertex in bytes. * * @member {number} */this.vertByteSize=this.vertSize*4;/** * The number of particles the buffer can hold * * @member {number} */this.size=size;/** * A list of the properties that are dynamic. * * @member {object[]} */this.dynamicProperties=[];/** * A list of the properties that are static. * * @member {object[]} */this.staticProperties=[];for(var i=0;i https://github.com/mattdesl/ * for creating the original pixi version! * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now * share 4 bytes on the vertex buffer * * Heavily inspired by LibGDX's ParticleRenderer: * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java *//** * * @class * @private * @memberof PIXI */var ParticleRenderer=function(_core$ObjectRenderer){_inherits(ParticleRenderer,_core$ObjectRenderer);/** * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. */function ParticleRenderer(renderer){_classCallCheck(this,ParticleRenderer);// 65535 is max vertex index in the index buffer (see ParticleRenderer) // so max number of particles is 65536 / 4 = 16384 // and max number of element in the index buffer is 16384 * 6 = 98304 // Creating a full index buffer, overhead is 98304 * 2 = 196Ko // let numIndices = 98304; /** * The default shader that is used if a sprite doesn't have a more specific one. * * @member {PIXI.Shader} */var _this=_possibleConstructorReturn(this,_core$ObjectRenderer.call(this,renderer));_this.shader=null;_this.indexBuffer=null;_this.properties=null;_this.tempMatrix=new core.Matrix();_this.CONTEXT_UID=0;return _this;}/** * When there is a WebGL context change * * @private */ParticleRenderer.prototype.onContextChange=function onContextChange(){var gl=this.renderer.gl;this.CONTEXT_UID=this.renderer.CONTEXT_UID;// setup default shader this.shader=new _ParticleShader2.default(gl);this.properties=[// verticesData {attribute:this.shader.attributes.aVertexPosition,size:2,uploadFunction:this.uploadVertices,offset:0},// positionData {attribute:this.shader.attributes.aPositionCoord,size:2,uploadFunction:this.uploadPosition,offset:0},// rotationData {attribute:this.shader.attributes.aRotation,size:1,uploadFunction:this.uploadRotation,offset:0},// uvsData {attribute:this.shader.attributes.aTextureCoord,size:2,uploadFunction:this.uploadUvs,offset:0},// alphaData {attribute:this.shader.attributes.aColor,size:1,uploadFunction:this.uploadAlpha,offset:0}];};/** * Starts a new particle batch. * */ParticleRenderer.prototype.start=function start(){this.renderer.bindShader(this.shader);};/** * Renders the particle container object. * * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer */ParticleRenderer.prototype.render=function render(container){var children=container.children;var maxSize=container._maxSize;var batchSize=container._batchSize;var renderer=this.renderer;var totalChildren=children.length;if(totalChildren===0){return;}else if(totalChildren>maxSize){totalChildren=maxSize;}var buffers=container._glBuffers[renderer.CONTEXT_UID];if(!buffers){buffers=container._glBuffers[renderer.CONTEXT_UID]=this.generateBuffers(container);}// if the uvs have not updated then no point rendering just yet! this.renderer.setBlendMode(container.blendMode);var gl=renderer.gl;var m=container.worldTransform.copy(this.tempMatrix);m.prepend(renderer._activeRenderTarget.projectionMatrix);this.shader.uniforms.projectionMatrix=m.toArray(true);this.shader.uniforms.uAlpha=container.worldAlpha;// make sure the texture is bound.. var baseTexture=children[0]._texture.baseTexture;this.shader.uniforms.uSampler=renderer.bindTexture(baseTexture);// now lets upload and render the buffers.. for(var i=0,j=0;ibatchSize){amount=batchSize;}var buffer=buffers[j];// we always upload the dynamic buffer.uploadDynamic(children,i,amount);// we only upload the static content when we have to! if(container._bufferToUpdate===j){buffer.uploadStatic(children,i,amount);container._bufferToUpdate=j+1;}// bind the buffer renderer.bindVao(buffer.vao);buffer.vao.draw(gl.TRIANGLES,amount*6);}};/** * Creates one particle buffer for each child in the container we want to render and updates internal properties * * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer * @return {PIXI.ParticleBuffer[]} The buffers */ParticleRenderer.prototype.generateBuffers=function generateBuffers(container){var gl=this.renderer.gl;var buffers=[];var size=container._maxSize;var batchSize=container._batchSize;var dynamicPropertyFlags=container._properties;for(var i=0;i0?1:-1;};}},{}],168:[function(require,module,exports){'use strict';var _objectAssign=require('object-assign');var _objectAssign2=_interopRequireDefault(_objectAssign);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}if(!Object.assign){Object.assign=_objectAssign2.default;}// References: // https://github.com/sindresorhus/object-assign // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign },{"object-assign":5}],169:[function(require,module,exports){'use strict';require('./Object.assign');require('./requestAnimationFrame');require('./Math.sign');if(!window.ArrayBuffer){window.ArrayBuffer=Array;}if(!window.Float32Array){window.Float32Array=Array;}if(!window.Uint32Array){window.Uint32Array=Array;}if(!window.Uint16Array){window.Uint16Array=Array;}},{"./Math.sign":167,"./Object.assign":168,"./requestAnimationFrame":170}],170:[function(require,module,exports){(function(global){'use strict';// References: // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // https://gist.github.com/1579671 // http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision // https://gist.github.com/timhall/4078614 // https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame // Expected to be used with Browserfiy // Browserify automatically detects the use of `global` and passes the // correct reference of `global`, `self`, and finally `window` var ONE_FRAME_TIME=16;// Date.now if(!(Date.now&&Date.prototype.getTime)){Date.now=function now(){return new Date().getTime();};}// performance.now if(!(global.performance&&global.performance.now)){(function(){var startTime=Date.now();if(!global.performance){global.performance={};}global.performance.now=function(){return Date.now()-startTime;};})();}// requestAnimationFrame var lastTime=Date.now();var vendors=['ms','moz','webkit','o'];for(var x=0;x} * @private */this.queue=[];/** * Collection of additional hooks for finding assets. * @type {Array} * @private */this.addHooks=[];/** * Collection of additional hooks for processing assets. * @type {Array} * @private */this.uploadHooks=[];/** * Callback to call after completed. * @type {Array} * @private */this.completes=[];/** * If prepare is ticking (running). * @type {boolean} * @private */this.ticking=false;/** * 'bound' call for prepareItems(). * @type {Function} * @private */this.delayedTick=function(){// unlikely, but in case we were destroyed between tick() and delayedTick() if(!_this.queue){return;}_this.prepareItems();};this.register(findText,drawText);this.register(findTextStyle,calculateTextStyle);}/** * Upload all the textures and graphics to the GPU. * * @param {Function|PIXI.DisplayObject|PIXI.Container} item - Either * the container or display object to search for items to upload or * the callback function, if items have been added using `prepare.add`. * @param {Function} [done] - Optional callback when all queued uploads have completed */BasePrepare.prototype.upload=function upload(item,done){if(typeof item==='function'){done=item;item=null;}// If a display object, search for items // that we could upload if(item){this.add(item);}// Get the items for upload from the display if(this.queue.length){if(done){this.completes.push(done);}if(!this.ticking){this.ticking=true;SharedTicker.addOnce(this.tick,this);}}else if(done){done();}};/** * Handle tick update * * @private */BasePrepare.prototype.tick=function tick(){setTimeout(this.delayedTick,0);};/** * Actually prepare items. This is handled outside of the tick because it will take a while * and we do NOT want to block the current animation frame from rendering. * * @private */BasePrepare.prototype.prepareItems=function prepareItems(){this.limiter.beginFrame();// Upload the graphics while(this.queue.length&&this.limiter.allowedToUpload()){var item=this.queue[0];var uploaded=false;for(var i=0,len=this.uploadHooks.length;i=0;_i2--){this.add(item.children[_i2]);}}return this;};/** * Destroys the plugin, don't use after this. * */BasePrepare.prototype.destroy=function destroy(){if(this.ticking){SharedTicker.remove(this.tick,this);}this.ticking=false;this.addHooks=null;this.uploadHooks=null;this.renderer=null;this.completes=null;this.queue=null;this.limiter=null;this.uploadHookHelper=null;};return BasePrepare;}();/** * Built-in hook to draw PIXI.Text to its texture. * * @private * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler * @param {PIXI.DisplayObject} item - Item to check * @return {boolean} If item was uploaded. */exports.default=BasePrepare;function drawText(helper,item){if(item instanceof core.Text){// updating text will return early if it is not dirty item.updateText(true);return true;}return false;}/** * Built-in hook to calculate a text style for a PIXI.Text object. * * @private * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler * @param {PIXI.DisplayObject} item - Item to check * @return {boolean} If item was uploaded. */function calculateTextStyle(helper,item){if(item instanceof core.TextStyle){var font=core.Text.getFontStyle(item);if(!core.Text.fontPropertiesCache[font]){core.Text.calculateFontProperties(font);}return true;}return false;}/** * Built-in hook to find Text objects. * * @private * @param {PIXI.DisplayObject} item - Display object to check * @param {Array<*>} queue - Collection of items to upload * @return {boolean} if a PIXI.Text object was found. */function findText(item,queue){if(item instanceof core.Text){// push the text style to prepare it - this can be really expensive if(queue.indexOf(item.style)===-1){queue.push(item.style);}// also push the text object so that we can render it (to canvas/texture) if needed if(queue.indexOf(item)===-1){queue.push(item);}// also push the Text's texture for upload to GPU var texture=item._texture.baseTexture;if(queue.indexOf(texture)===-1){queue.push(texture);}return true;}return false;}/** * Built-in hook to find TextStyle objects. * * @private * @param {PIXI.TextStyle} item - Display object to check * @param {Array<*>} queue - Collection of items to upload * @return {boolean} if a PIXI.TextStyle object was found. */function findTextStyle(item,queue){if(item instanceof core.TextStyle){if(queue.indexOf(item)===-1){queue.push(item);}return true;}return false;}},{"../core":61,"./limiters/CountLimiter":174}],172:[function(require,module,exports){'use strict';exports.__esModule=true;var _core=require('../../core');var core=_interopRequireWildcard(_core);var _BasePrepare2=require('../BasePrepare');var _BasePrepare3=_interopRequireDefault(_BasePrepare2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&((typeof call==="undefined"?"undefined":_typeof2(call))==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+(typeof superClass==="undefined"?"undefined":_typeof2(superClass)));}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var CANVAS_START_SIZE=16;/** * The prepare manager provides functionality to upload content to the GPU * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing * textures to an offline canvas. * This draw call will force the texture to be moved onto the GPU. * * @class * @memberof PIXI */var CanvasPrepare=function(_BasePrepare){_inherits(CanvasPrepare,_BasePrepare);/** * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer */function CanvasPrepare(renderer){_classCallCheck(this,CanvasPrepare);var _this=_possibleConstructorReturn(this,_BasePrepare.call(this,renderer));_this.uploadHookHelper=_this;/** * An offline canvas to render textures to * @type {HTMLCanvasElement} * @private */_this.canvas=document.createElement('canvas');_this.canvas.width=CANVAS_START_SIZE;_this.canvas.height=CANVAS_START_SIZE;/** * The context to the canvas * @type {CanvasRenderingContext2D} * @private */_this.ctx=_this.canvas.getContext('2d');// Add textures to upload _this.register(findBaseTextures,uploadBaseTextures);return _this;}/** * Destroys the plugin, don't use after this. * */CanvasPrepare.prototype.destroy=function destroy(){_BasePrepare.prototype.destroy.call(this);this.ctx=null;this.canvas=null;};return CanvasPrepare;}(_BasePrepare3.default);/** * Built-in hook to upload PIXI.Texture objects to the GPU. * * @private * @param {*} prepare - Instance of CanvasPrepare * @param {*} item - Item to check * @return {boolean} If item was uploaded. */exports.default=CanvasPrepare;function uploadBaseTextures(prepare,item){if(item instanceof core.BaseTexture){var image=item.source;// Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. // So if the width or height is equal to zero then use the canvas size // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. var imageWidth=image.width===0?prepare.canvas.width:Math.min(prepare.canvas.width,image.width);var imageHeight=image.height===0?prepare.canvas.height:Math.min(prepare.canvas.height,image.height);// Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU // A smaller draw can be faster. prepare.ctx.drawImage(image,0,0,imageWidth,imageHeight,0,0,prepare.canvas.width,prepare.canvas.height);return true;}return false;}/** * Built-in hook to find textures from Sprites. * * @private * @param {PIXI.DisplayObject} item -Display object to check * @param {Array<*>} queue - Collection of items to upload * @return {boolean} if a PIXI.Texture object was found. */function findBaseTextures(item,queue){// Objects with textures, like Sprites/Text if(item instanceof core.BaseTexture){if(queue.indexOf(item)===-1){queue.push(item);}return true;}else if(item._texture&&item._texture instanceof core.Texture){var texture=item._texture.baseTexture;if(queue.indexOf(texture)===-1){queue.push(texture);}return true;}return false;}core.CanvasRenderer.registerPlugin('prepare',CanvasPrepare);},{"../../core":61,"../BasePrepare":171}],173:[function(require,module,exports){'use strict';exports.__esModule=true;var _WebGLPrepare=require('./webgl/WebGLPrepare');Object.defineProperty(exports,'webgl',{enumerable:true,get:function get(){return _interopRequireDefault(_WebGLPrepare).default;}});var _CanvasPrepare=require('./canvas/CanvasPrepare');Object.defineProperty(exports,'canvas',{enumerable:true,get:function get(){return _interopRequireDefault(_CanvasPrepare).default;}});var _BasePrepare=require('./BasePrepare');Object.defineProperty(exports,'BasePrepare',{enumerable:true,get:function get(){return _interopRequireDefault(_BasePrepare).default;}});var _CountLimiter=require('./limiters/CountLimiter');Object.defineProperty(exports,'CountLimiter',{enumerable:true,get:function get(){return _interopRequireDefault(_CountLimiter).default;}});var _TimeLimiter=require('./limiters/TimeLimiter');Object.defineProperty(exports,'TimeLimiter',{enumerable:true,get:function get(){return _interopRequireDefault(_TimeLimiter).default;}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}},{"./BasePrepare":171,"./canvas/CanvasPrepare":172,"./limiters/CountLimiter":174,"./limiters/TimeLimiter":175,"./webgl/WebGLPrepare":176}],174:[function(require,module,exports){"use strict";exports.__esModule=true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/** * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified * number of items per frame. * * @class * @memberof PIXI */var CountLimiter=function(){/** * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. */function CountLimiter(maxItemsPerFrame){_classCallCheck(this,CountLimiter);/** * The maximum number of items that can be prepared each frame. * @private */this.maxItemsPerFrame=maxItemsPerFrame;/** * The number of items that can be prepared in the current frame. * @type {number} * @private */this.itemsLeft=0;}/** * Resets any counting properties to start fresh on a new frame. */CountLimiter.prototype.beginFrame=function beginFrame(){this.itemsLeft=this.maxItemsPerFrame;};/** * Checks to see if another item can be uploaded. This should only be called once per item. * @return {boolean} If the item is allowed to be uploaded. */CountLimiter.prototype.allowedToUpload=function allowedToUpload(){return this.itemsLeft-->0;};return CountLimiter;}();exports.default=CountLimiter;},{}],175:[function(require,module,exports){"use strict";exports.__esModule=true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}/** * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified * number of milliseconds per frame. * * @class * @memberof PIXI */var TimeLimiter=function(){/** * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. */function TimeLimiter(maxMilliseconds){_classCallCheck(this,TimeLimiter);/** * The maximum milliseconds that can be spent preparing items each frame. * @private */this.maxMilliseconds=maxMilliseconds;/** * The start time of the current frame. * @type {number} * @private */this.frameStart=0;}/** * Resets any counting properties to start fresh on a new frame. */TimeLimiter.prototype.beginFrame=function beginFrame(){this.frameStart=Date.now();};/** * Checks to see if another item can be uploaded. This should only be called once per item. * @return {boolean} If the item is allowed to be uploaded. */TimeLimiter.prototype.allowedToUpload=function allowedToUpload(){return Date.now()-this.frameStart} queue - Collection of items to upload * @return {boolean} if a PIXI.Texture object was found. */function findBaseTextures(item,queue){// Objects with textures, like Sprites/Text if(item instanceof core.BaseTexture){if(queue.indexOf(item)===-1){queue.push(item);}return true;}else if(item._texture&&item._texture instanceof core.Texture){var texture=item._texture.baseTexture;if(queue.indexOf(texture)===-1){queue.push(texture);}return true;}return false;}/** * Built-in hook to find graphics. * * @private * @param {PIXI.DisplayObject} item - Display object to check * @param {Array<*>} queue - Collection of items to upload * @return {boolean} if a PIXI.Graphics object was found. */function findGraphics(item,queue){if(item instanceof core.Graphics){queue.push(item);return true;}return false;}core.WebGLRenderer.registerPlugin('prepare',WebGLPrepare);},{"../../core":61,"../BasePrepare":171}],177:[function(require,module,exports){(function(global){'use strict';exports.__esModule=true;exports.loader=exports.prepare=exports.particles=exports.mesh=exports.loaders=exports.interaction=exports.filters=exports.extras=exports.extract=exports.accessibility=undefined;var _deprecation=require('./deprecation');Object.keys(_deprecation).forEach(function(key){if(key==="default"||key==="__esModule")return;Object.defineProperty(exports,key,{enumerable:true,get:function get(){return _deprecation[key];}});});var _core=require('./core');Object.keys(_core).forEach(function(key){if(key==="default"||key==="__esModule")return;Object.defineProperty(exports,key,{enumerable:true,get:function get(){return _core[key];}});});require('./polyfill');var _accessibility=require('./accessibility');var accessibility=_interopRequireWildcard(_accessibility);var _extract=require('./extract');var extract=_interopRequireWildcard(_extract);var _extras=require('./extras');var extras=_interopRequireWildcard(_extras);var _filters=require('./filters');var filters=_interopRequireWildcard(_filters);var _interaction=require('./interaction');var interaction=_interopRequireWildcard(_interaction);var _loaders=require('./loaders');var loaders=_interopRequireWildcard(_loaders);var _mesh=require('./mesh');var mesh=_interopRequireWildcard(_mesh);var _particles=require('./particles');var particles=_interopRequireWildcard(_particles);var _prepare=require('./prepare');var prepare=_interopRequireWildcard(_prepare);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj;}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj;}}// import polyfills exports.accessibility=accessibility;exports.extract=extract;exports.extras=extras;exports.filters=filters;exports.interaction=interaction;exports.loaders=loaders;exports.mesh=mesh;exports.particles=particles;exports.prepare=prepare;/** * A premade instance of the loader that can be used to load resources. * * @name loader * @memberof PIXI * @property {PIXI.loaders.Loader} */// export libs // export core var loader=loaders&&loaders.Loader?new loaders.Loader():null;// check is there in case user excludes loader lib exports.loader=loader;// Always export pixi globally. global.PIXI=exports;// eslint-disable-line }).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"./accessibility":40,"./core":61,"./deprecation":120,"./extract":122,"./extras":131,"./filters":142,"./interaction":148,"./loaders":151,"./mesh":160,"./particles":163,"./polyfill":169,"./prepare":173}]},{},[177])(177);});//# sourceMappingURL=pixi.js.map /*! * VERSION: 1.19.1 * DATE: 2017-01-17 * UPDATES AND DOCS AT: http://greensock.com * * Includes all of the following: TweenLite, TweenMax, TimelineLite, TimelineMax, EasePack, CSSPlugin, RoundPropsPlugin, BezierPlugin, AttrPlugin, DirectionalRotationPlugin * * @license Copyright (c) 2008-2017, GreenSock. All rights reserved. * This work is subject to the terms at http://greensock.com/standard-license or for * Club GreenSock members, the software agreement that was issued with your membership. * * @author: Jack Doyle, jack@greensock.com **/ var _gsScope = (typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node (_gsScope._gsQueue || (_gsScope._gsQueue = [])).push( function() { "use strict"; _gsScope._gsDefine("TweenMax", ["core.Animation","core.SimpleTimeline","TweenLite"], function(Animation, SimpleTimeline, TweenLite) { var _slice = function(a) { //don't use [].slice because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll() var b = [], l = a.length, i; for (i = 0; i !== l; b.push(a[i++])); return b; }, _applyCycle = function(vars, targets, i) { var alt = vars.cycle, p, val; for (p in alt) { val = alt[p]; vars[p] = (typeof(val) === "function") ? val(i, targets[i]) : val[i % val.length]; } delete vars.cycle; }, TweenMax = function(target, duration, vars) { TweenLite.call(this, target, duration, vars); this._cycle = 0; this._yoyo = (this.vars.yoyo === true); this._repeat = this.vars.repeat || 0; this._repeatDelay = this.vars.repeatDelay || 0; this._dirty = true; //ensures that if there is any repeat, the totalDuration will get recalculated to accurately report it. this.render = TweenMax.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method) }, _tinyNum = 0.0000000001, TweenLiteInternals = TweenLite._internals, _isSelector = TweenLiteInternals.isSelector, _isArray = TweenLiteInternals.isArray, p = TweenMax.prototype = TweenLite.to({}, 0.1, {}), _blankArray = []; TweenMax.version = "1.19.1"; p.constructor = TweenMax; p.kill()._gc = false; TweenMax.killTweensOf = TweenMax.killDelayedCallsTo = TweenLite.killTweensOf; TweenMax.getTweensOf = TweenLite.getTweensOf; TweenMax.lagSmoothing = TweenLite.lagSmoothing; TweenMax.ticker = TweenLite.ticker; TweenMax.render = TweenLite.render; p.invalidate = function() { this._yoyo = (this.vars.yoyo === true); this._repeat = this.vars.repeat || 0; this._repeatDelay = this.vars.repeatDelay || 0; this._uncache(true); return TweenLite.prototype.invalidate.call(this); }; p.updateTo = function(vars, resetDuration) { var curRatio = this.ratio, immediate = this.vars.immediateRender || vars.immediateRender, p; if (resetDuration && this._startTime < this._timeline._time) { this._startTime = this._timeline._time; this._uncache(false); if (this._gc) { this._enabled(true, false); } else { this._timeline.insert(this, this._startTime - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct. } } for (p in vars) { this.vars[p] = vars[p]; } if (this._initted || immediate) { if (resetDuration) { this._initted = false; if (immediate) { this.render(0, true, true); } } else { if (this._gc) { this._enabled(true, false); } if (this._notifyPluginsOfEnabled && this._firstPT) { TweenLite._onPluginEvent("_onDisable", this); //in case a plugin like MotionBlur must perform some cleanup tasks } if (this._time / this._duration > 0.998) { //if the tween has finished (or come extremely close to finishing), we just need to rewind it to 0 and then render it again at the end which forces it to re-initialize (parsing the new vars). We allow tweens that are close to finishing (but haven't quite finished) to work this way too because otherwise, the values are so small when determining where to project the starting values that binary math issues creep in and can make the tween appear to render incorrectly when run backwards. var prevTime = this._totalTime; this.render(0, true, false); this._initted = false; this.render(prevTime, true, false); } else { this._initted = false; this._init(); if (this._time > 0 || immediate) { var inv = 1 / (1 - curRatio), pt = this._firstPT, endValue; while (pt) { endValue = pt.s + pt.c; pt.c *= inv; pt.s = endValue - pt.c; pt = pt._next; } } } } } return this; }; p.render = function(time, suppressEvents, force) { if (!this._initted) if (this._duration === 0 && this.vars.repeat) { //zero duration tweens that render immediately have render() called from TweenLite's constructor, before TweenMax's constructor has finished setting _repeat, _repeatDelay, and _yoyo which are critical in determining totalDuration() so we need to call invalidate() which is a low-kb way to get those set properly. this.invalidate(); } var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(), prevTime = this._time, prevTotalTime = this._totalTime, prevCycle = this._cycle, duration = this._duration, prevRawPrevTime = this._rawPrevTime, isComplete, callback, pt, cycleDuration, r, type, pow, rawPrevTime; if (time >= totalDur - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts. this._totalTime = totalDur; this._cycle = this._repeat; if (this._yoyo && (this._cycle & 1) !== 0) { this._time = 0; this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0; } else { this._time = duration; this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1; } if (!this._reversed) { isComplete = true; callback = "onComplete"; force = (force || this._timeline.autoRemoveChildren); //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline. } if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered. if (this._startTime === this._timeline._duration) { //if a zero-duration tween is at the VERY end of a timeline and that timeline renders at its end, it will typically add a tiny bit of cushion to the render time to prevent rounding errors from getting in the way of tweens rendering their VERY end. If we then reverse() that timeline, the zero-duration tween will trigger its onReverseComplete even though technically the playhead didn't pass over it again. It's a very specific edge case we must accommodate. time = 0; } if (prevRawPrevTime < 0 || (time <= 0 && time >= -0.0000001) || (prevRawPrevTime === _tinyNum && this.data !== "isPause")) if (prevRawPrevTime !== time) { //note: when this.data is "isPause", it's a callback added by addPause() on a timeline that we should not be triggered when LEAVING its exact start time. In other words, tl.addPause(1).play(1) shouldn't pause. force = true; if (prevRawPrevTime > _tinyNum) { callback = "onReverseComplete"; } } this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. } } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0. this._totalTime = this._time = this._cycle = 0; this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0; if (prevTotalTime !== 0 || (duration === 0 && prevRawPrevTime > 0)) { callback = "onReverseComplete"; isComplete = this._reversed; } if (time < 0) { this._active = false; if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered. if (prevRawPrevTime >= 0) { force = true; } this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. } } if (!this._initted) { //if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately. force = true; } } else { this._totalTime = this._time = time; if (this._repeat !== 0) { cycleDuration = duration + this._repeatDelay; this._cycle = (this._totalTime / cycleDuration) >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but some browsers report it as 0.79999999!) if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration && prevTotalTime <= time) { this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) } this._time = this._totalTime - (this._cycle * cycleDuration); if (this._yoyo) if ((this._cycle & 1) !== 0) { this._time = duration - this._time; } if (this._time > duration) { this._time = duration; } else if (this._time < 0) { this._time = 0; } } if (this._easeType) { r = this._time / duration; type = this._easeType; pow = this._easePower; if (type === 1 || (type === 3 && r >= 0.5)) { r = 1 - r; } if (type === 3) { r *= 2; } if (pow === 1) { r *= r; } else if (pow === 2) { r *= r * r; } else if (pow === 3) { r *= r * r * r; } else if (pow === 4) { r *= r * r * r * r; } if (type === 1) { this.ratio = 1 - r; } else if (type === 2) { this.ratio = r; } else if (this._time / duration < 0.5) { this.ratio = r / 2; } else { this.ratio = 1 - (r / 2); } } else { this.ratio = this._ease.getRatio(this._time / duration); } } if (prevTime === this._time && !force && prevCycle === this._cycle) { if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) { //so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate. this._callback("onUpdate"); } return; } else if (!this._initted) { this._init(); if (!this._initted || this._gc) { //immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example. return; } else if (!force && this._firstPT && ((this.vars.lazy !== false && this._duration) || (this.vars.lazy && !this._duration))) { //we stick it in the queue for rendering at the very end of the tick - this is a performance optimization because browsers invalidate styles and force a recalculation if you read, write, and then read style data (so it's better to read/read/read/write/write/write than read/write/read/write/read/write). The down side, of course, is that usually you WANT things to render immediately because you may have code running right after that which depends on the change. Like imagine running TweenLite.set(...) and then immediately after that, creating a nother tween that animates the same property to another value; the starting values of that 2nd tween wouldn't be accurate if lazy is true. this._time = prevTime; this._totalTime = prevTotalTime; this._rawPrevTime = prevRawPrevTime; this._cycle = prevCycle; TweenLiteInternals.lazyTweens.push(this); this._lazy = [time, suppressEvents]; return; } //_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently. if (this._time && !isComplete) { this.ratio = this._ease.getRatio(this._time / duration); } else if (isComplete && this._ease._calcEnd) { this.ratio = this._ease.getRatio((this._time === 0) ? 0 : 1); } } if (this._lazy !== false) { this._lazy = false; } if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) { this._active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done. } if (prevTotalTime === 0) { if (this._initted === 2 && time > 0) { //this.invalidate(); this._init(); //will just apply overwriting since _initted of (2) means it was a from() tween that had immediateRender:true } if (this._startAt) { if (time >= 0) { this._startAt.render(time, suppressEvents, force); } else if (!callback) { callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area. } } if (this.vars.onStart) if (this._totalTime !== 0 || duration === 0) if (!suppressEvents) { this._callback("onStart"); } } pt = this._firstPT; while (pt) { if (pt.f) { pt.t[pt.p](pt.c * this.ratio + pt.s); } else { pt.t[pt.p] = pt.c * this.ratio + pt.s; } pt = pt._next; } if (this._onUpdate) { if (time < 0) if (this._startAt && this._startTime) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values. this._startAt.render(time, suppressEvents, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete. } if (!suppressEvents) if (this._totalTime !== prevTotalTime || callback) { this._callback("onUpdate"); } } if (this._cycle !== prevCycle) if (!suppressEvents) if (!this._gc) if (this.vars.onRepeat) { this._callback("onRepeat"); } if (callback) if (!this._gc || force) { //check gc because there's a chance that kill() could be called in an onUpdate if (time < 0 && this._startAt && !this._onUpdate && this._startTime) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values. this._startAt.render(time, suppressEvents, force); } if (isComplete) { if (this._timeline.autoRemoveChildren) { this._enabled(false, false); } this._active = false; } if (!suppressEvents && this.vars[callback]) { this._callback(callback); } if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) { //the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless. this._rawPrevTime = 0; } } }; //---- STATIC FUNCTIONS ----------------------------------------------------------------------------------------------------------- TweenMax.to = function(target, duration, vars) { return new TweenMax(target, duration, vars); }; TweenMax.from = function(target, duration, vars) { vars.runBackwards = true; vars.immediateRender = (vars.immediateRender != false); return new TweenMax(target, duration, vars); }; TweenMax.fromTo = function(target, duration, fromVars, toVars) { toVars.startAt = fromVars; toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false); return new TweenMax(target, duration, toVars); }; TweenMax.staggerTo = TweenMax.allTo = function(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { stagger = stagger || 0; var delay = 0, a = [], finalComplete = function() { if (vars.onComplete) { vars.onComplete.apply(vars.onCompleteScope || this, arguments); } onCompleteAll.apply(onCompleteAllScope || vars.callbackScope || this, onCompleteAllParams || _blankArray); }, cycle = vars.cycle, fromCycle = (vars.startAt && vars.startAt.cycle), l, copy, i, p; if (!_isArray(targets)) { if (typeof(targets) === "string") { targets = TweenLite.selector(targets) || targets; } if (_isSelector(targets)) { targets = _slice(targets); } } targets = targets || []; if (stagger < 0) { targets = _slice(targets); targets.reverse(); stagger *= -1; } l = targets.length - 1; for (i = 0; i <= l; i++) { copy = {}; for (p in vars) { copy[p] = vars[p]; } if (cycle) { _applyCycle(copy, targets, i); if (copy.duration != null) { duration = copy.duration; delete copy.duration; } } if (fromCycle) { fromCycle = copy.startAt = {}; for (p in vars.startAt) { fromCycle[p] = vars.startAt[p]; } _applyCycle(copy.startAt, targets, i); } copy.delay = delay + (copy.delay || 0); if (i === l && onCompleteAll) { copy.onComplete = finalComplete; } a[i] = new TweenMax(targets[i], duration, copy); delay += stagger; } return a; }; TweenMax.staggerFrom = TweenMax.allFrom = function(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { vars.runBackwards = true; vars.immediateRender = (vars.immediateRender != false); return TweenMax.staggerTo(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope); }; TweenMax.staggerFromTo = TweenMax.allFromTo = function(targets, duration, fromVars, toVars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { toVars.startAt = fromVars; toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false); return TweenMax.staggerTo(targets, duration, toVars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope); }; TweenMax.delayedCall = function(delay, callback, params, scope, useFrames) { return new TweenMax(callback, 0, {delay:delay, onComplete:callback, onCompleteParams:params, callbackScope:scope, onReverseComplete:callback, onReverseCompleteParams:params, immediateRender:false, useFrames:useFrames, overwrite:0}); }; TweenMax.set = function(target, vars) { return new TweenMax(target, 0, vars); }; TweenMax.isTweening = function(target) { return (TweenLite.getTweensOf(target, true).length > 0); }; var _getChildrenOf = function(timeline, includeTimelines) { var a = [], cnt = 0, tween = timeline._first; while (tween) { if (tween instanceof TweenLite) { a[cnt++] = tween; } else { if (includeTimelines) { a[cnt++] = tween; } a = a.concat(_getChildrenOf(tween, includeTimelines)); cnt = a.length; } tween = tween._next; } return a; }, getAllTweens = TweenMax.getAllTweens = function(includeTimelines) { return _getChildrenOf(Animation._rootTimeline, includeTimelines).concat( _getChildrenOf(Animation._rootFramesTimeline, includeTimelines) ); }; TweenMax.killAll = function(complete, tweens, delayedCalls, timelines) { if (tweens == null) { tweens = true; } if (delayedCalls == null) { delayedCalls = true; } var a = getAllTweens((timelines != false)), l = a.length, allTrue = (tweens && delayedCalls && timelines), isDC, tween, i; for (i = 0; i < l; i++) { tween = a[i]; if (allTrue || (tween instanceof SimpleTimeline) || ((isDC = (tween.target === tween.vars.onComplete)) && delayedCalls) || (tweens && !isDC)) { if (complete) { tween.totalTime(tween._reversed ? 0 : tween.totalDuration()); } else { tween._enabled(false, false); } } } }; TweenMax.killChildTweensOf = function(parent, complete) { if (parent == null) { return; } var tl = TweenLiteInternals.tweenLookup, a, curParent, p, i, l; if (typeof(parent) === "string") { parent = TweenLite.selector(parent) || parent; } if (_isSelector(parent)) { parent = _slice(parent); } if (_isArray(parent)) { i = parent.length; while (--i > -1) { TweenMax.killChildTweensOf(parent[i], complete); } return; } a = []; for (p in tl) { curParent = tl[p].target.parentNode; while (curParent) { if (curParent === parent) { a = a.concat(tl[p].tweens); } curParent = curParent.parentNode; } } l = a.length; for (i = 0; i < l; i++) { if (complete) { a[i].totalTime(a[i].totalDuration()); } a[i]._enabled(false, false); } }; var _changePause = function(pause, tweens, delayedCalls, timelines) { tweens = (tweens !== false); delayedCalls = (delayedCalls !== false); timelines = (timelines !== false); var a = getAllTweens(timelines), allTrue = (tweens && delayedCalls && timelines), i = a.length, isDC, tween; while (--i > -1) { tween = a[i]; if (allTrue || (tween instanceof SimpleTimeline) || ((isDC = (tween.target === tween.vars.onComplete)) && delayedCalls) || (tweens && !isDC)) { tween.paused(pause); } } }; TweenMax.pauseAll = function(tweens, delayedCalls, timelines) { _changePause(true, tweens, delayedCalls, timelines); }; TweenMax.resumeAll = function(tweens, delayedCalls, timelines) { _changePause(false, tweens, delayedCalls, timelines); }; TweenMax.globalTimeScale = function(value) { var tl = Animation._rootTimeline, t = TweenLite.ticker.time; if (!arguments.length) { return tl._timeScale; } value = value || _tinyNum; //can't allow zero because it'll throw the math off tl._startTime = t - ((t - tl._startTime) * tl._timeScale / value); tl = Animation._rootFramesTimeline; t = TweenLite.ticker.frame; tl._startTime = t - ((t - tl._startTime) * tl._timeScale / value); tl._timeScale = Animation._rootTimeline._timeScale = value; return value; }; //---- GETTERS / SETTERS ---------------------------------------------------------------------------------------------------------- p.progress = function(value, suppressEvents) { return (!arguments.length) ? this._time / this.duration() : this.totalTime( this.duration() * ((this._yoyo && (this._cycle & 1) !== 0) ? 1 - value : value) + (this._cycle * (this._duration + this._repeatDelay)), suppressEvents); }; p.totalProgress = function(value, suppressEvents) { return (!arguments.length) ? this._totalTime / this.totalDuration() : this.totalTime( this.totalDuration() * value, suppressEvents); }; p.time = function(value, suppressEvents) { if (!arguments.length) { return this._time; } if (this._dirty) { this.totalDuration(); } if (value > this._duration) { value = this._duration; } if (this._yoyo && (this._cycle & 1) !== 0) { value = (this._duration - value) + (this._cycle * (this._duration + this._repeatDelay)); } else if (this._repeat !== 0) { value += this._cycle * (this._duration + this._repeatDelay); } return this.totalTime(value, suppressEvents); }; p.duration = function(value) { if (!arguments.length) { return this._duration; //don't set _dirty = false because there could be repeats that haven't been factored into the _totalDuration yet. Otherwise, if you create a repeated TweenMax and then immediately check its duration(), it would cache the value and the totalDuration would not be correct, thus repeats wouldn't take effect. } return Animation.prototype.duration.call(this, value); }; p.totalDuration = function(value) { if (!arguments.length) { if (this._dirty) { //instead of Infinity, we use 999999999999 so that we can accommodate reverses this._totalDuration = (this._repeat === -1) ? 999999999999 : this._duration * (this._repeat + 1) + (this._repeatDelay * this._repeat); this._dirty = false; } return this._totalDuration; } return (this._repeat === -1) ? this : this.duration( (value - (this._repeat * this._repeatDelay)) / (this._repeat + 1) ); }; p.repeat = function(value) { if (!arguments.length) { return this._repeat; } this._repeat = value; return this._uncache(true); }; p.repeatDelay = function(value) { if (!arguments.length) { return this._repeatDelay; } this._repeatDelay = value; return this._uncache(true); }; p.yoyo = function(value) { if (!arguments.length) { return this._yoyo; } this._yoyo = value; return this; }; return TweenMax; }, true); /* * ---------------------------------------------------------------- * TimelineLite * ---------------------------------------------------------------- */ _gsScope._gsDefine("TimelineLite", ["core.Animation","core.SimpleTimeline","TweenLite"], function(Animation, SimpleTimeline, TweenLite) { var TimelineLite = function(vars) { SimpleTimeline.call(this, vars); this._labels = {}; this.autoRemoveChildren = (this.vars.autoRemoveChildren === true); this.smoothChildTiming = (this.vars.smoothChildTiming === true); this._sortChildren = true; this._onUpdate = this.vars.onUpdate; var v = this.vars, val, p; for (p in v) { val = v[p]; if (_isArray(val)) if (val.join("").indexOf("{self}") !== -1) { v[p] = this._swapSelfInParams(val); } } if (_isArray(v.tweens)) { this.add(v.tweens, 0, v.align, v.stagger); } }, _tinyNum = 0.0000000001, TweenLiteInternals = TweenLite._internals, _internals = TimelineLite._internals = {}, _isSelector = TweenLiteInternals.isSelector, _isArray = TweenLiteInternals.isArray, _lazyTweens = TweenLiteInternals.lazyTweens, _lazyRender = TweenLiteInternals.lazyRender, _globals = _gsScope._gsDefine.globals, _copy = function(vars) { var copy = {}, p; for (p in vars) { copy[p] = vars[p]; } return copy; }, _applyCycle = function(vars, targets, i) { var alt = vars.cycle, p, val; for (p in alt) { val = alt[p]; vars[p] = (typeof(val) === "function") ? val(i, targets[i]) : val[i % val.length]; } delete vars.cycle; }, _pauseCallback = _internals.pauseCallback = function() {}, _slice = function(a) { //don't use [].slice because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll() var b = [], l = a.length, i; for (i = 0; i !== l; b.push(a[i++])); return b; }, p = TimelineLite.prototype = new SimpleTimeline(); TimelineLite.version = "1.19.1"; p.constructor = TimelineLite; p.kill()._gc = p._forcingPlayhead = p._hasPause = false; /* might use later... //translates a local time inside an animation to the corresponding time on the root/global timeline, factoring in all nesting and timeScales. function localToGlobal(time, animation) { while (animation) { time = (time / animation._timeScale) + animation._startTime; animation = animation.timeline; } return time; } //translates the supplied time on the root/global timeline into the corresponding local time inside a particular animation, factoring in all nesting and timeScales function globalToLocal(time, animation) { var scale = 1; time -= localToGlobal(0, animation); while (animation) { scale *= animation._timeScale; animation = animation.timeline; } return time * scale; } */ p.to = function(target, duration, vars, position) { var Engine = (vars.repeat && _globals.TweenMax) || TweenLite; return duration ? this.add( new Engine(target, duration, vars), position) : this.set(target, vars, position); }; p.from = function(target, duration, vars, position) { return this.add( ((vars.repeat && _globals.TweenMax) || TweenLite).from(target, duration, vars), position); }; p.fromTo = function(target, duration, fromVars, toVars, position) { var Engine = (toVars.repeat && _globals.TweenMax) || TweenLite; return duration ? this.add( Engine.fromTo(target, duration, fromVars, toVars), position) : this.set(target, toVars, position); }; p.staggerTo = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { var tl = new TimelineLite({onComplete:onCompleteAll, onCompleteParams:onCompleteAllParams, callbackScope:onCompleteAllScope, smoothChildTiming:this.smoothChildTiming}), cycle = vars.cycle, copy, i; if (typeof(targets) === "string") { targets = TweenLite.selector(targets) || targets; } targets = targets || []; if (_isSelector(targets)) { //senses if the targets object is a selector. If it is, we should translate it into an array. targets = _slice(targets); } stagger = stagger || 0; if (stagger < 0) { targets = _slice(targets); targets.reverse(); stagger *= -1; } for (i = 0; i < targets.length; i++) { copy = _copy(vars); if (copy.startAt) { copy.startAt = _copy(copy.startAt); if (copy.startAt.cycle) { _applyCycle(copy.startAt, targets, i); } } if (cycle) { _applyCycle(copy, targets, i); if (copy.duration != null) { duration = copy.duration; delete copy.duration; } } tl.to(targets[i], duration, copy, i * stagger); } return this.add(tl, position); }; p.staggerFrom = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { vars.immediateRender = (vars.immediateRender != false); vars.runBackwards = true; return this.staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope); }; p.staggerFromTo = function(targets, duration, fromVars, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) { toVars.startAt = fromVars; toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false); return this.staggerTo(targets, duration, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope); }; p.call = function(callback, params, scope, position) { return this.add( TweenLite.delayedCall(0, callback, params, scope), position); }; p.set = function(target, vars, position) { position = this._parseTimeOrLabel(position, 0, true); if (vars.immediateRender == null) { vars.immediateRender = (position === this._time && !this._paused); } return this.add( new TweenLite(target, 0, vars), position); }; TimelineLite.exportRoot = function(vars, ignoreDelayedCalls) { vars = vars || {}; if (vars.smoothChildTiming == null) { vars.smoothChildTiming = true; } var tl = new TimelineLite(vars), root = tl._timeline, tween, next; if (ignoreDelayedCalls == null) { ignoreDelayedCalls = true; } root._remove(tl, true); tl._startTime = 0; tl._rawPrevTime = tl._time = tl._totalTime = root._time; tween = root._first; while (tween) { next = tween._next; if (!ignoreDelayedCalls || !(tween instanceof TweenLite && tween.target === tween.vars.onComplete)) { tl.add(tween, tween._startTime - tween._delay); } tween = next; } root.add(tl, 0); return tl; }; p.add = function(value, position, align, stagger) { var curTime, l, i, child, tl, beforeRawTime; if (typeof(position) !== "number") { position = this._parseTimeOrLabel(position, 0, true, value); } if (!(value instanceof Animation)) { if ((value instanceof Array) || (value && value.push && _isArray(value))) { align = align || "normal"; stagger = stagger || 0; curTime = position; l = value.length; for (i = 0; i < l; i++) { if (_isArray(child = value[i])) { child = new TimelineLite({tweens:child}); } this.add(child, curTime); if (typeof(child) !== "string" && typeof(child) !== "function") { if (align === "sequence") { curTime = child._startTime + (child.totalDuration() / child._timeScale); } else if (align === "start") { child._startTime -= child.delay(); } } curTime += stagger; } return this._uncache(true); } else if (typeof(value) === "string") { return this.addLabel(value, position); } else if (typeof(value) === "function") { value = TweenLite.delayedCall(0, value); } else { throw("Cannot add " + value + " into the timeline; it is not a tween, timeline, function, or string."); } } SimpleTimeline.prototype.add.call(this, value, position); //if the timeline has already ended but the inserted tween/timeline extends the duration, we should enable this timeline again so that it renders properly. We should also align the playhead with the parent timeline's when appropriate. if (this._gc || this._time === this._duration) if (!this._paused) if (this._duration < this.duration()) { //in case any of the ancestors had completed but should now be enabled... tl = this; beforeRawTime = (tl.rawTime() > value._startTime); //if the tween is placed on the timeline so that it starts BEFORE the current rawTime, we should align the playhead (move the timeline). This is because sometimes users will create a timeline, let it finish, and much later append a tween and expect it to run instead of jumping to its end state. While technically one could argue that it should jump to its end state, that's not what users intuitively expect. while (tl._timeline) { if (beforeRawTime && tl._timeline.smoothChildTiming) { tl.totalTime(tl._totalTime, true); //moves the timeline (shifts its startTime) if necessary, and also enables it. } else if (tl._gc) { tl._enabled(true, false); } tl = tl._timeline; } } return this; }; p.remove = function(value) { if (value instanceof Animation) { this._remove(value, false); var tl = value._timeline = value.vars.useFrames ? Animation._rootFramesTimeline : Animation._rootTimeline; //now that it's removed, default it to the root timeline so that if it gets played again, it doesn't jump back into this timeline. value._startTime = (value._paused ? value._pauseTime : tl._time) - ((!value._reversed ? value._totalTime : value.totalDuration() - value._totalTime) / value._timeScale); //ensure that if it gets played again, the timing is correct. return this; } else if (value instanceof Array || (value && value.push && _isArray(value))) { var i = value.length; while (--i > -1) { this.remove(value[i]); } return this; } else if (typeof(value) === "string") { return this.removeLabel(value); } return this.kill(null, value); }; p._remove = function(tween, skipDisable) { SimpleTimeline.prototype._remove.call(this, tween, skipDisable); var last = this._last; if (!last) { this._time = this._totalTime = this._duration = this._totalDuration = 0; } else if (this._time > this.duration()) { this._time = this._duration; this._totalTime = this._totalDuration; } return this; }; p.append = function(value, offsetOrLabel) { return this.add(value, this._parseTimeOrLabel(null, offsetOrLabel, true, value)); }; p.insert = p.insertMultiple = function(value, position, align, stagger) { return this.add(value, position || 0, align, stagger); }; p.appendMultiple = function(tweens, offsetOrLabel, align, stagger) { return this.add(tweens, this._parseTimeOrLabel(null, offsetOrLabel, true, tweens), align, stagger); }; p.addLabel = function(label, position) { this._labels[label] = this._parseTimeOrLabel(position); return this; }; p.addPause = function(position, callback, params, scope) { var t = TweenLite.delayedCall(0, _pauseCallback, params, scope || this); t.vars.onComplete = t.vars.onReverseComplete = callback; t.data = "isPause"; this._hasPause = true; return this.add(t, position); }; p.removeLabel = function(label) { delete this._labels[label]; return this; }; p.getLabelTime = function(label) { return (this._labels[label] != null) ? this._labels[label] : -1; }; p._parseTimeOrLabel = function(timeOrLabel, offsetOrLabel, appendIfAbsent, ignore) { var i; //if we're about to add a tween/timeline (or an array of them) that's already a child of this timeline, we should remove it first so that it doesn't contaminate the duration(). if (ignore instanceof Animation && ignore.timeline === this) { this.remove(ignore); } else if (ignore && ((ignore instanceof Array) || (ignore.push && _isArray(ignore)))) { i = ignore.length; while (--i > -1) { if (ignore[i] instanceof Animation && ignore[i].timeline === this) { this.remove(ignore[i]); } } } if (typeof(offsetOrLabel) === "string") { return this._parseTimeOrLabel(offsetOrLabel, (appendIfAbsent && typeof(timeOrLabel) === "number" && this._labels[offsetOrLabel] == null) ? timeOrLabel - this.duration() : 0, appendIfAbsent); } offsetOrLabel = offsetOrLabel || 0; if (typeof(timeOrLabel) === "string" && (isNaN(timeOrLabel) || this._labels[timeOrLabel] != null)) { //if the string is a number like "1", check to see if there's a label with that name, otherwise interpret it as a number (absolute value). i = timeOrLabel.indexOf("="); if (i === -1) { if (this._labels[timeOrLabel] == null) { return appendIfAbsent ? (this._labels[timeOrLabel] = this.duration() + offsetOrLabel) : offsetOrLabel; } return this._labels[timeOrLabel] + offsetOrLabel; } offsetOrLabel = parseInt(timeOrLabel.charAt(i-1) + "1", 10) * Number(timeOrLabel.substr(i+1)); timeOrLabel = (i > 1) ? this._parseTimeOrLabel(timeOrLabel.substr(0, i-1), 0, appendIfAbsent) : this.duration(); } else if (timeOrLabel == null) { timeOrLabel = this.duration(); } return Number(timeOrLabel) + offsetOrLabel; }; p.seek = function(position, suppressEvents) { return this.totalTime((typeof(position) === "number") ? position : this._parseTimeOrLabel(position), (suppressEvents !== false)); }; p.stop = function() { return this.paused(true); }; p.gotoAndPlay = function(position, suppressEvents) { return this.play(position, suppressEvents); }; p.gotoAndStop = function(position, suppressEvents) { return this.pause(position, suppressEvents); }; p.render = function(time, suppressEvents, force) { if (this._gc) { this._enabled(true, false); } var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(), prevTime = this._time, prevStart = this._startTime, prevTimeScale = this._timeScale, prevPaused = this._paused, tween, isComplete, next, callback, internalForce, pauseTween, curTime; if (time >= totalDur - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts. this._totalTime = this._time = totalDur; if (!this._reversed) if (!this._hasPausedChild()) { isComplete = true; callback = "onComplete"; internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline. if (this._duration === 0) if ((time <= 0 && time >= -0.0000001) || this._rawPrevTime < 0 || this._rawPrevTime === _tinyNum) if (this._rawPrevTime !== time && this._first) { internalForce = true; if (this._rawPrevTime > _tinyNum) { callback = "onReverseComplete"; } } } this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. time = totalDur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7. } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0. this._totalTime = this._time = 0; if (prevTime !== 0 || (this._duration === 0 && this._rawPrevTime !== _tinyNum && (this._rawPrevTime > 0 || (time < 0 && this._rawPrevTime >= 0)))) { callback = "onReverseComplete"; isComplete = this._reversed; } if (time < 0) { this._active = false; if (this._timeline.autoRemoveChildren && this._reversed) { //ensures proper GC if a timeline is resumed after it's finished reversing. internalForce = isComplete = true; callback = "onReverseComplete"; } else if (this._rawPrevTime >= 0 && this._first) { //when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state. internalForce = true; } this._rawPrevTime = time; } else { this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. if (time === 0 && isComplete) { //if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good). tween = this._first; while (tween && tween._startTime === 0) { if (!tween._duration) { isComplete = false; } tween = tween._next; } } time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline) if (!this._initted) { internalForce = true; } } } else { if (this._hasPause && !this._forcingPlayhead && !suppressEvents) { if (time >= prevTime) { tween = this._first; while (tween && tween._startTime <= time && !pauseTween) { if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) { pauseTween = tween; } tween = tween._next; } } else { tween = this._last; while (tween && tween._startTime >= time && !pauseTween) { if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) { pauseTween = tween; } tween = tween._prev; } } if (pauseTween) { this._time = time = pauseTween._startTime; this._totalTime = time + (this._cycle * (this._totalDuration + this._repeatDelay)); } } this._totalTime = this._time = this._rawPrevTime = time; } if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) { return; } else if (!this._initted) { this._initted = true; } if (!this._active) if (!this._paused && this._time !== prevTime && time > 0) { this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example. } if (prevTime === 0) if (this.vars.onStart) if (this._time !== 0 || !this._duration) if (!suppressEvents) { this._callback("onStart"); } curTime = this._time; if (curTime >= prevTime) { tween = this._first; while (tween) { next = tween._next; //record it here because the value could change after rendering... if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete break; } else if (tween._active || (tween._startTime <= curTime && !tween._paused && !tween._gc)) { if (pauseTween === tween) { this.pause(); } if (!tween._reversed) { tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force); } else { tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force); } } tween = next; } } else { tween = this._last; while (tween) { next = tween._prev; //record it here because the value could change after rendering... if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete break; } else if (tween._active || (tween._startTime <= prevTime && !tween._paused && !tween._gc)) { if (pauseTween === tween) { pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse. while (pauseTween && pauseTween.endTime() > this._time) { pauseTween.render( (pauseTween._reversed ? pauseTween.totalDuration() - ((time - pauseTween._startTime) * pauseTween._timeScale) : (time - pauseTween._startTime) * pauseTween._timeScale), suppressEvents, force); pauseTween = pauseTween._prev; } pauseTween = null; this.pause(); } if (!tween._reversed) { tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force); } else { tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force); } } tween = next; } } if (this._onUpdate) if (!suppressEvents) { if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values. _lazyRender(); } this._callback("onUpdate"); } if (callback) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate if (isComplete) { if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values. _lazyRender(); } if (this._timeline.autoRemoveChildren) { this._enabled(false, false); } this._active = false; } if (!suppressEvents && this.vars[callback]) { this._callback(callback); } } }; p._hasPausedChild = function() { var tween = this._first; while (tween) { if (tween._paused || ((tween instanceof TimelineLite) && tween._hasPausedChild())) { return true; } tween = tween._next; } return false; }; p.getChildren = function(nested, tweens, timelines, ignoreBeforeTime) { ignoreBeforeTime = ignoreBeforeTime || -9999999999; var a = [], tween = this._first, cnt = 0; while (tween) { if (tween._startTime < ignoreBeforeTime) { //do nothing } else if (tween instanceof TweenLite) { if (tweens !== false) { a[cnt++] = tween; } } else { if (timelines !== false) { a[cnt++] = tween; } if (nested !== false) { a = a.concat(tween.getChildren(true, tweens, timelines)); cnt = a.length; } } tween = tween._next; } return a; }; p.getTweensOf = function(target, nested) { var disabled = this._gc, a = [], cnt = 0, tweens, i; if (disabled) { this._enabled(true, true); //getTweensOf() filters out disabled tweens, and we have to mark them as _gc = true when the timeline completes in order to allow clean garbage collection, so temporarily re-enable the timeline here. } tweens = TweenLite.getTweensOf(target); i = tweens.length; while (--i > -1) { if (tweens[i].timeline === this || (nested && this._contains(tweens[i]))) { a[cnt++] = tweens[i]; } } if (disabled) { this._enabled(false, true); } return a; }; p.recent = function() { return this._recent; }; p._contains = function(tween) { var tl = tween.timeline; while (tl) { if (tl === this) { return true; } tl = tl.timeline; } return false; }; p.shiftChildren = function(amount, adjustLabels, ignoreBeforeTime) { ignoreBeforeTime = ignoreBeforeTime || 0; var tween = this._first, labels = this._labels, p; while (tween) { if (tween._startTime >= ignoreBeforeTime) { tween._startTime += amount; } tween = tween._next; } if (adjustLabels) { for (p in labels) { if (labels[p] >= ignoreBeforeTime) { labels[p] += amount; } } } return this._uncache(true); }; p._kill = function(vars, target) { if (!vars && !target) { return this._enabled(false, false); } var tweens = (!target) ? this.getChildren(true, true, false) : this.getTweensOf(target), i = tweens.length, changed = false; while (--i > -1) { if (tweens[i]._kill(vars, target)) { changed = true; } } return changed; }; p.clear = function(labels) { var tweens = this.getChildren(false, true, true), i = tweens.length; this._time = this._totalTime = 0; while (--i > -1) { tweens[i]._enabled(false, false); } if (labels !== false) { this._labels = {}; } return this._uncache(true); }; p.invalidate = function() { var tween = this._first; while (tween) { tween.invalidate(); tween = tween._next; } return Animation.prototype.invalidate.call(this);; }; p._enabled = function(enabled, ignoreTimeline) { if (enabled === this._gc) { var tween = this._first; while (tween) { tween._enabled(enabled, true); tween = tween._next; } } return SimpleTimeline.prototype._enabled.call(this, enabled, ignoreTimeline); }; p.totalTime = function(time, suppressEvents, uncapped) { this._forcingPlayhead = true; var val = Animation.prototype.totalTime.apply(this, arguments); this._forcingPlayhead = false; return val; }; p.duration = function(value) { if (!arguments.length) { if (this._dirty) { this.totalDuration(); //just triggers recalculation } return this._duration; } if (this.duration() !== 0 && value !== 0) { this.timeScale(this._duration / value); } return this; }; p.totalDuration = function(value) { if (!arguments.length) { if (this._dirty) { var max = 0, tween = this._last, prevStart = 999999999999, prev, end; while (tween) { prev = tween._prev; //record it here in case the tween changes position in the sequence... if (tween._dirty) { tween.totalDuration(); //could change the tween._startTime, so make sure the tween's cache is clean before analyzing it. } if (tween._startTime > prevStart && this._sortChildren && !tween._paused) { //in case one of the tweens shifted out of order, it needs to be re-inserted into the correct position in the sequence this.add(tween, tween._startTime - tween._delay); } else { prevStart = tween._startTime; } if (tween._startTime < 0 && !tween._paused) { //children aren't allowed to have negative startTimes unless smoothChildTiming is true, so adjust here if one is found. max -= tween._startTime; if (this._timeline.smoothChildTiming) { this._startTime += tween._startTime / this._timeScale; } this.shiftChildren(-tween._startTime, false, -9999999999); prevStart = 0; } end = tween._startTime + (tween._totalDuration / tween._timeScale); if (end > max) { max = end; } tween = prev; } this._duration = this._totalDuration = max; this._dirty = false; } return this._totalDuration; } return (value && this.totalDuration()) ? this.timeScale(this._totalDuration / value) : this; }; p.paused = function(value) { if (!value) { //if there's a pause directly at the spot from where we're unpausing, skip it. var tween = this._first, time = this._time; while (tween) { if (tween._startTime === time && tween.data === "isPause") { tween._rawPrevTime = 0; //remember, _rawPrevTime is how zero-duration tweens/callbacks sense directionality and determine whether or not to fire. If _rawPrevTime is the same as _startTime on the next render, it won't fire. } tween = tween._next; } } return Animation.prototype.paused.apply(this, arguments); }; p.usesFrames = function() { var tl = this._timeline; while (tl._timeline) { tl = tl._timeline; } return (tl === Animation._rootFramesTimeline); }; p.rawTime = function(wrapRepeats) { return (wrapRepeats && (this._paused || (this._repeat && this.time() > 0 && this.totalProgress() < 1))) ? this._totalTime % (this._duration + this._repeatDelay) : this._paused ? this._totalTime : (this._timeline.rawTime(wrapRepeats) - this._startTime) * this._timeScale; }; return TimelineLite; }, true); /* * ---------------------------------------------------------------- * TimelineMax * ---------------------------------------------------------------- */ _gsScope._gsDefine("TimelineMax", ["TimelineLite","TweenLite","easing.Ease"], function(TimelineLite, TweenLite, Ease) { var TimelineMax = function(vars) { TimelineLite.call(this, vars); this._repeat = this.vars.repeat || 0; this._repeatDelay = this.vars.repeatDelay || 0; this._cycle = 0; this._yoyo = (this.vars.yoyo === true); this._dirty = true; }, _tinyNum = 0.0000000001, TweenLiteInternals = TweenLite._internals, _lazyTweens = TweenLiteInternals.lazyTweens, _lazyRender = TweenLiteInternals.lazyRender, _globals = _gsScope._gsDefine.globals, _easeNone = new Ease(null, null, 1, 0), p = TimelineMax.prototype = new TimelineLite(); p.constructor = TimelineMax; p.kill()._gc = false; TimelineMax.version = "1.19.1"; p.invalidate = function() { this._yoyo = (this.vars.yoyo === true); this._repeat = this.vars.repeat || 0; this._repeatDelay = this.vars.repeatDelay || 0; this._uncache(true); return TimelineLite.prototype.invalidate.call(this); }; p.addCallback = function(callback, position, params, scope) { return this.add( TweenLite.delayedCall(0, callback, params, scope), position); }; p.removeCallback = function(callback, position) { if (callback) { if (position == null) { this._kill(null, callback); } else { var a = this.getTweensOf(callback, false), i = a.length, time = this._parseTimeOrLabel(position); while (--i > -1) { if (a[i]._startTime === time) { a[i]._enabled(false, false); } } } } return this; }; p.removePause = function(position) { return this.removeCallback(TimelineLite._internals.pauseCallback, position); }; p.tweenTo = function(position, vars) { vars = vars || {}; var copy = {ease:_easeNone, useFrames:this.usesFrames(), immediateRender:false}, Engine = (vars.repeat && _globals.TweenMax) || TweenLite, duration, p, t; for (p in vars) { copy[p] = vars[p]; } copy.time = this._parseTimeOrLabel(position); duration = (Math.abs(Number(copy.time) - this._time) / this._timeScale) || 0.001; t = new Engine(this, duration, copy); copy.onStart = function() { t.target.paused(true); if (t.vars.time !== t.target.time() && duration === t.duration()) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all. t.duration( Math.abs( t.vars.time - t.target.time()) / t.target._timeScale ); } if (vars.onStart) { //in case the user had an onStart in the vars - we don't want to overwrite it. vars.onStart.apply(vars.onStartScope || vars.callbackScope || t, vars.onStartParams || []); //don't use t._callback("onStart") or it'll point to the copy.onStart and we'll get a recursion error. } }; return t; }; p.tweenFromTo = function(fromPosition, toPosition, vars) { vars = vars || {}; fromPosition = this._parseTimeOrLabel(fromPosition); vars.startAt = {onComplete:this.seek, onCompleteParams:[fromPosition], callbackScope:this}; vars.immediateRender = (vars.immediateRender !== false); var t = this.tweenTo(toPosition, vars); return t.duration((Math.abs( t.vars.time - fromPosition) / this._timeScale) || 0.001); }; p.render = function(time, suppressEvents, force) { if (this._gc) { this._enabled(true, false); } var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(), dur = this._duration, prevTime = this._time, prevTotalTime = this._totalTime, prevStart = this._startTime, prevTimeScale = this._timeScale, prevRawPrevTime = this._rawPrevTime, prevPaused = this._paused, prevCycle = this._cycle, tween, isComplete, next, callback, internalForce, cycleDuration, pauseTween, curTime; if (time >= totalDur - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts. if (!this._locked) { this._totalTime = totalDur; this._cycle = this._repeat; } if (!this._reversed) if (!this._hasPausedChild()) { isComplete = true; callback = "onComplete"; internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline. if (this._duration === 0) if ((time <= 0 && time >= -0.0000001) || prevRawPrevTime < 0 || prevRawPrevTime === _tinyNum) if (prevRawPrevTime !== time && this._first) { internalForce = true; if (prevRawPrevTime > _tinyNum) { callback = "onReverseComplete"; } } } this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. if (this._yoyo && (this._cycle & 1) !== 0) { this._time = time = 0; } else { this._time = dur; time = dur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7. We cannot do less then 0.0001 because the same issue can occur when the duration is extremely large like 999999999999 in which case adding 0.00000001, for example, causes it to act like nothing was added. } } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0. if (!this._locked) { this._totalTime = this._cycle = 0; } this._time = 0; if (prevTime !== 0 || (dur === 0 && prevRawPrevTime !== _tinyNum && (prevRawPrevTime > 0 || (time < 0 && prevRawPrevTime >= 0)) && !this._locked)) { //edge case for checking time < 0 && prevRawPrevTime >= 0: a zero-duration fromTo() tween inside a zero-duration timeline (yeah, very rare) callback = "onReverseComplete"; isComplete = this._reversed; } if (time < 0) { this._active = false; if (this._timeline.autoRemoveChildren && this._reversed) { internalForce = isComplete = true; callback = "onReverseComplete"; } else if (prevRawPrevTime >= 0 && this._first) { //when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state. internalForce = true; } this._rawPrevTime = time; } else { this._rawPrevTime = (dur || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient. if (time === 0 && isComplete) { //if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good). tween = this._first; while (tween && tween._startTime === 0) { if (!tween._duration) { isComplete = false; } tween = tween._next; } } time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline) if (!this._initted) { internalForce = true; } } } else { if (dur === 0 && prevRawPrevTime < 0) { //without this, zero-duration repeating timelines (like with a simple callback nested at the very beginning and a repeatDelay) wouldn't render the first time through. internalForce = true; } this._time = this._rawPrevTime = time; if (!this._locked) { this._totalTime = time; if (this._repeat !== 0) { cycleDuration = dur + this._repeatDelay; this._cycle = (this._totalTime / cycleDuration) >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but it gets reported as 0.79999999!) if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration && prevTotalTime <= time) { this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) } this._time = this._totalTime - (this._cycle * cycleDuration); if (this._yoyo) if ((this._cycle & 1) !== 0) { this._time = dur - this._time; } if (this._time > dur) { this._time = dur; time = dur + 0.0001; //to avoid occasional floating point rounding error } else if (this._time < 0) { this._time = time = 0; } else { time = this._time; } } } if (this._hasPause && !this._forcingPlayhead && !suppressEvents && time < dur) { time = this._time; if (time >= prevTime || (this._repeat && prevCycle !== this._cycle)) { tween = this._first; while (tween && tween._startTime <= time && !pauseTween) { if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) { pauseTween = tween; } tween = tween._next; } } else { tween = this._last; while (tween && tween._startTime >= time && !pauseTween) { if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) { pauseTween = tween; } tween = tween._prev; } } if (pauseTween) { this._time = time = pauseTween._startTime; this._totalTime = time + (this._cycle * (this._totalDuration + this._repeatDelay)); } } } if (this._cycle !== prevCycle) if (!this._locked) { /* make sure children at the end/beginning of the timeline are rendered properly. If, for example, a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So we need to push the timeline to the end (and/or beginning depending on its yoyo value). Also we must ensure that zero-duration tweens at the very beginning or end of the TimelineMax work. */ var backwards = (this._yoyo && (prevCycle & 1) !== 0), wrap = (backwards === (this._yoyo && (this._cycle & 1) !== 0)), recTotalTime = this._totalTime, recCycle = this._cycle, recRawPrevTime = this._rawPrevTime, recTime = this._time; this._totalTime = prevCycle * dur; if (this._cycle < prevCycle) { backwards = !backwards; } else { this._totalTime += dur; } this._time = prevTime; //temporarily revert _time so that render() renders the children in the correct order. Without this, tweens won't rewind correctly. We could arhictect things in a "cleaner" way by splitting out the rendering queue into a separate method but for performance reasons, we kept it all inside this method. this._rawPrevTime = (dur === 0) ? prevRawPrevTime - 0.0001 : prevRawPrevTime; this._cycle = prevCycle; this._locked = true; //prevents changes to totalTime and skips repeat/yoyo behavior when we recursively call render() prevTime = (backwards) ? 0 : dur; this.render(prevTime, suppressEvents, (dur === 0)); if (!suppressEvents) if (!this._gc) { if (this.vars.onRepeat) { this._cycle = recCycle; //in case the onRepeat alters the playhead or invalidates(), we shouldn't stay locked or use the previous cycle. this._locked = false; this._callback("onRepeat"); } } if (prevTime !== this._time) { //in case there's a callback like onComplete in a nested tween/timeline that changes the playhead position, like via seek(), we should just abort. return; } if (wrap) { this._cycle = prevCycle; //if there's an onRepeat, we reverted this above, so make sure it's set properly again. We also unlocked in that scenario, so reset that too. this._locked = true; prevTime = (backwards) ? dur + 0.0001 : -0.0001; this.render(prevTime, true, false); } this._locked = false; if (this._paused && !prevPaused) { //if the render() triggered callback that paused this timeline, we should abort (very rare, but possible) return; } this._time = recTime; this._totalTime = recTotalTime; this._cycle = recCycle; this._rawPrevTime = recRawPrevTime; } if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) { if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) { //so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate. this._callback("onUpdate"); } return; } else if (!this._initted) { this._initted = true; } if (!this._active) if (!this._paused && this._totalTime !== prevTotalTime && time > 0) { this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example. } if (prevTotalTime === 0) if (this.vars.onStart) if (this._totalTime !== 0 || !this._totalDuration) if (!suppressEvents) { this._callback("onStart"); } curTime = this._time; if (curTime >= prevTime) { tween = this._first; while (tween) { next = tween._next; //record it here because the value could change after rendering... if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete break; } else if (tween._active || (tween._startTime <= this._time && !tween._paused && !tween._gc)) { if (pauseTween === tween) { this.pause(); } if (!tween._reversed) { tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force); } else { tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force); } } tween = next; } } else { tween = this._last; while (tween) { next = tween._prev; //record it here because the value could change after rendering... if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete break; } else if (tween._active || (tween._startTime <= prevTime && !tween._paused && !tween._gc)) { if (pauseTween === tween) { pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse. while (pauseTween && pauseTween.endTime() > this._time) { pauseTween.render( (pauseTween._reversed ? pauseTween.totalDuration() - ((time - pauseTween._startTime) * pauseTween._timeScale) : (time - pauseTween._startTime) * pauseTween._timeScale), suppressEvents, force); pauseTween = pauseTween._prev; } pauseTween = null; this.pause(); } if (!tween._reversed) { tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force); } else { tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force); } } tween = next; } } if (this._onUpdate) if (!suppressEvents) { if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values. _lazyRender(); } this._callback("onUpdate"); } if (callback) if (!this._locked) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate if (isComplete) { if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values. _lazyRender(); } if (this._timeline.autoRemoveChildren) { this._enabled(false, false); } this._active = false; } if (!suppressEvents && this.vars[callback]) { this._callback(callback); } } }; p.getActive = function(nested, tweens, timelines) { if (nested == null) { nested = true; } if (tweens == null) { tweens = true; } if (timelines == null) { timelines = false; } var a = [], all = this.getChildren(nested, tweens, timelines), cnt = 0, l = all.length, i, tween; for (i = 0; i < l; i++) { tween = all[i]; if (tween.isActive()) { a[cnt++] = tween; } } return a; }; p.getLabelAfter = function(time) { if (!time) if (time !== 0) { //faster than isNan() time = this._time; } var labels = this.getLabelsArray(), l = labels.length, i; for (i = 0; i < l; i++) { if (labels[i].time > time) { return labels[i].name; } } return null; }; p.getLabelBefore = function(time) { if (time == null) { time = this._time; } var labels = this.getLabelsArray(), i = labels.length; while (--i > -1) { if (labels[i].time < time) { return labels[i].name; } } return null; }; p.getLabelsArray = function() { var a = [], cnt = 0, p; for (p in this._labels) { a[cnt++] = {time:this._labels[p], name:p}; } a.sort(function(a,b) { return a.time - b.time; }); return a; }; p.invalidate = function() { this._locked = false; //unlock and set cycle in case invalidate() is called from inside an onRepeat return TimelineLite.prototype.invalidate.call(this); }; //---- GETTERS / SETTERS ------------------------------------------------------------------------------------------------------- p.progress = function(value, suppressEvents) { return (!arguments.length) ? this._time / this.duration() : this.totalTime( this.duration() * ((this._yoyo && (this._cycle & 1) !== 0) ? 1 - value : value) + (this._cycle * (this._duration + this._repeatDelay)), suppressEvents); }; p.totalProgress = function(value, suppressEvents) { return (!arguments.length) ? this._totalTime / this.totalDuration() : this.totalTime( this.totalDuration() * value, suppressEvents); }; p.totalDuration = function(value) { if (!arguments.length) { if (this._dirty) { TimelineLite.prototype.totalDuration.call(this); //just forces refresh //Instead of Infinity, we use 999999999999 so that we can accommodate reverses. this._totalDuration = (this._repeat === -1) ? 999999999999 : this._duration * (this._repeat + 1) + (this._repeatDelay * this._repeat); } return this._totalDuration; } return (this._repeat === -1 || !value) ? this : this.timeScale( this.totalDuration() / value ); }; p.time = function(value, suppressEvents) { if (!arguments.length) { return this._time; } if (this._dirty) { this.totalDuration(); } if (value > this._duration) { value = this._duration; } if (this._yoyo && (this._cycle & 1) !== 0) { value = (this._duration - value) + (this._cycle * (this._duration + this._repeatDelay)); } else if (this._repeat !== 0) { value += this._cycle * (this._duration + this._repeatDelay); } return this.totalTime(value, suppressEvents); }; p.repeat = function(value) { if (!arguments.length) { return this._repeat; } this._repeat = value; return this._uncache(true); }; p.repeatDelay = function(value) { if (!arguments.length) { return this._repeatDelay; } this._repeatDelay = value; return this._uncache(true); }; p.yoyo = function(value) { if (!arguments.length) { return this._yoyo; } this._yoyo = value; return this; }; p.currentLabel = function(value) { if (!arguments.length) { return this.getLabelBefore(this._time + 0.00000001); } return this.seek(value, true); }; return TimelineMax; }, true); /* * ---------------------------------------------------------------- * BezierPlugin * ---------------------------------------------------------------- */ (function() { var _RAD2DEG = 180 / Math.PI, _r1 = [], _r2 = [], _r3 = [], _corProps = {}, _globals = _gsScope._gsDefine.globals, Segment = function(a, b, c, d) { if (c === d) { //if c and d match, the final autoRotate value could lock at -90 degrees, so differentiate them slightly. c = d - (d - b) / 1000000; } if (a === b) { //if a and b match, the starting autoRotate value could lock at -90 degrees, so differentiate them slightly. b = a + (c - a) / 1000000; } this.a = a; this.b = b; this.c = c; this.d = d; this.da = d - a; this.ca = c - a; this.ba = b - a; }, _correlate = ",x,y,z,left,top,right,bottom,marginTop,marginLeft,marginRight,marginBottom,paddingLeft,paddingTop,paddingRight,paddingBottom,backgroundPosition,backgroundPosition_y,", cubicToQuadratic = function(a, b, c, d) { var q1 = {a:a}, q2 = {}, q3 = {}, q4 = {c:d}, mab = (a + b) / 2, mbc = (b + c) / 2, mcd = (c + d) / 2, mabc = (mab + mbc) / 2, mbcd = (mbc + mcd) / 2, m8 = (mbcd - mabc) / 8; q1.b = mab + (a - mab) / 4; q2.b = mabc + m8; q1.c = q2.a = (q1.b + q2.b) / 2; q2.c = q3.a = (mabc + mbcd) / 2; q3.b = mbcd - m8; q4.b = mcd + (d - mcd) / 4; q3.c = q4.a = (q3.b + q4.b) / 2; return [q1, q2, q3, q4]; }, _calculateControlPoints = function(a, curviness, quad, basic, correlate) { var l = a.length - 1, ii = 0, cp1 = a[0].a, i, p1, p2, p3, seg, m1, m2, mm, cp2, qb, r1, r2, tl; for (i = 0; i < l; i++) { seg = a[ii]; p1 = seg.a; p2 = seg.d; p3 = a[ii+1].d; if (correlate) { r1 = _r1[i]; r2 = _r2[i]; tl = ((r2 + r1) * curviness * 0.25) / (basic ? 0.5 : _r3[i] || 0.5); m1 = p2 - (p2 - p1) * (basic ? curviness * 0.5 : (r1 !== 0 ? tl / r1 : 0)); m2 = p2 + (p3 - p2) * (basic ? curviness * 0.5 : (r2 !== 0 ? tl / r2 : 0)); mm = p2 - (m1 + (((m2 - m1) * ((r1 * 3 / (r1 + r2)) + 0.5) / 4) || 0)); } else { m1 = p2 - (p2 - p1) * curviness * 0.5; m2 = p2 + (p3 - p2) * curviness * 0.5; mm = p2 - (m1 + m2) / 2; } m1 += mm; m2 += mm; seg.c = cp2 = m1; if (i !== 0) { seg.b = cp1; } else { seg.b = cp1 = seg.a + (seg.c - seg.a) * 0.6; //instead of placing b on a exactly, we move it inline with c so that if the user specifies an ease like Back.easeIn or Elastic.easeIn which goes BEYOND the beginning, it will do so smoothly. } seg.da = p2 - p1; seg.ca = cp2 - p1; seg.ba = cp1 - p1; if (quad) { qb = cubicToQuadratic(p1, cp1, cp2, p2); a.splice(ii, 1, qb[0], qb[1], qb[2], qb[3]); ii += 4; } else { ii++; } cp1 = m2; } seg = a[ii]; seg.b = cp1; seg.c = cp1 + (seg.d - cp1) * 0.4; //instead of placing c on d exactly, we move it inline with b so that if the user specifies an ease like Back.easeOut or Elastic.easeOut which goes BEYOND the end, it will do so smoothly. seg.da = seg.d - seg.a; seg.ca = seg.c - seg.a; seg.ba = cp1 - seg.a; if (quad) { qb = cubicToQuadratic(seg.a, cp1, seg.c, seg.d); a.splice(ii, 1, qb[0], qb[1], qb[2], qb[3]); } }, _parseAnchors = function(values, p, correlate, prepend) { var a = [], l, i, p1, p2, p3, tmp; if (prepend) { values = [prepend].concat(values); i = values.length; while (--i > -1) { if (typeof( (tmp = values[i][p]) ) === "string") if (tmp.charAt(1) === "=") { values[i][p] = prepend[p] + Number(tmp.charAt(0) + tmp.substr(2)); //accommodate relative values. Do it inline instead of breaking it out into a function for speed reasons } } } l = values.length - 2; if (l < 0) { a[0] = new Segment(values[0][p], 0, 0, values[(l < -1) ? 0 : 1][p]); return a; } for (i = 0; i < l; i++) { p1 = values[i][p]; p2 = values[i+1][p]; a[i] = new Segment(p1, 0, 0, p2); if (correlate) { p3 = values[i+2][p]; _r1[i] = (_r1[i] || 0) + (p2 - p1) * (p2 - p1); _r2[i] = (_r2[i] || 0) + (p3 - p2) * (p3 - p2); } } a[i] = new Segment(values[i][p], 0, 0, values[i+1][p]); return a; }, bezierThrough = function(values, curviness, quadratic, basic, correlate, prepend) { var obj = {}, props = [], first = prepend || values[0], i, p, a, j, r, l, seamless, last; correlate = (typeof(correlate) === "string") ? ","+correlate+"," : _correlate; if (curviness == null) { curviness = 1; } for (p in values[0]) { props.push(p); } //check to see if the last and first values are identical (well, within 0.05). If so, make seamless by appending the second element to the very end of the values array and the 2nd-to-last element to the very beginning (we'll remove those segments later) if (values.length > 1) { last = values[values.length - 1]; seamless = true; i = props.length; while (--i > -1) { p = props[i]; if (Math.abs(first[p] - last[p]) > 0.05) { //build in a tolerance of +/-0.05 to accommodate rounding errors. seamless = false; break; } } if (seamless) { values = values.concat(); //duplicate the array to avoid contaminating the original which the user may be reusing for other tweens if (prepend) { values.unshift(prepend); } values.push(values[1]); prepend = values[values.length - 3]; } } _r1.length = _r2.length = _r3.length = 0; i = props.length; while (--i > -1) { p = props[i]; _corProps[p] = (correlate.indexOf(","+p+",") !== -1); obj[p] = _parseAnchors(values, p, _corProps[p], prepend); } i = _r1.length; while (--i > -1) { _r1[i] = Math.sqrt(_r1[i]); _r2[i] = Math.sqrt(_r2[i]); } if (!basic) { i = props.length; while (--i > -1) { if (_corProps[p]) { a = obj[props[i]]; l = a.length - 1; for (j = 0; j < l; j++) { r = (a[j+1].da / _r2[j] + a[j].da / _r1[j]) || 0; _r3[j] = (_r3[j] || 0) + r * r; } } } i = _r3.length; while (--i > -1) { _r3[i] = Math.sqrt(_r3[i]); } } i = props.length; j = quadratic ? 4 : 1; while (--i > -1) { p = props[i]; a = obj[p]; _calculateControlPoints(a, curviness, quadratic, basic, _corProps[p]); //this method requires that _parseAnchors() and _setSegmentRatios() ran first so that _r1, _r2, and _r3 values are populated for all properties if (seamless) { a.splice(0, j); a.splice(a.length - j, j); } } return obj; }, _parseBezierData = function(values, type, prepend) { type = type || "soft"; var obj = {}, inc = (type === "cubic") ? 3 : 2, soft = (type === "soft"), props = [], a, b, c, d, cur, i, j, l, p, cnt, tmp; if (soft && prepend) { values = [prepend].concat(values); } if (values == null || values.length < inc + 1) { throw "invalid Bezier data"; } for (p in values[0]) { props.push(p); } i = props.length; while (--i > -1) { p = props[i]; obj[p] = cur = []; cnt = 0; l = values.length; for (j = 0; j < l; j++) { a = (prepend == null) ? values[j][p] : (typeof( (tmp = values[j][p]) ) === "string" && tmp.charAt(1) === "=") ? prepend[p] + Number(tmp.charAt(0) + tmp.substr(2)) : Number(tmp); if (soft) if (j > 1) if (j < l - 1) { cur[cnt++] = (a + cur[cnt-2]) / 2; } cur[cnt++] = a; } l = cnt - inc + 1; cnt = 0; for (j = 0; j < l; j += inc) { a = cur[j]; b = cur[j+1]; c = cur[j+2]; d = (inc === 2) ? 0 : cur[j+3]; cur[cnt++] = tmp = (inc === 3) ? new Segment(a, b, c, d) : new Segment(a, (2 * b + a) / 3, (2 * b + c) / 3, c); } cur.length = cnt; } return obj; }, _addCubicLengths = function(a, steps, resolution) { var inc = 1 / resolution, j = a.length, d, d1, s, da, ca, ba, p, i, inv, bez, index; while (--j > -1) { bez = a[j]; s = bez.a; da = bez.d - s; ca = bez.c - s; ba = bez.b - s; d = d1 = 0; for (i = 1; i <= resolution; i++) { p = inc * i; inv = 1 - p; d = d1 - (d1 = (p * p * da + 3 * inv * (p * ca + inv * ba)) * p); index = j * resolution + i - 1; steps[index] = (steps[index] || 0) + d * d; } } }, _parseLengthData = function(obj, resolution) { resolution = resolution >> 0 || 6; var a = [], lengths = [], d = 0, total = 0, threshold = resolution - 1, segments = [], curLS = [], //current length segments array p, i, l, index; for (p in obj) { _addCubicLengths(obj[p], a, resolution); } l = a.length; for (i = 0; i < l; i++) { d += Math.sqrt(a[i]); index = i % resolution; curLS[index] = d; if (index === threshold) { total += d; index = (i / resolution) >> 0; segments[index] = curLS; lengths[index] = total; d = 0; curLS = []; } } return {length:total, lengths:lengths, segments:segments}; }, BezierPlugin = _gsScope._gsDefine.plugin({ propName: "bezier", priority: -1, version: "1.3.7", API: 2, global:true, //gets called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. init: function(target, vars, tween) { this._target = target; if (vars instanceof Array) { vars = {values:vars}; } this._func = {}; this._mod = {}; this._props = []; this._timeRes = (vars.timeResolution == null) ? 6 : parseInt(vars.timeResolution, 10); var values = vars.values || [], first = {}, second = values[0], autoRotate = vars.autoRotate || tween.vars.orientToBezier, p, isFunc, i, j, prepend; this._autoRotate = autoRotate ? (autoRotate instanceof Array) ? autoRotate : [["x","y","rotation",((autoRotate === true) ? 0 : Number(autoRotate) || 0)]] : null; for (p in second) { this._props.push(p); } i = this._props.length; while (--i > -1) { p = this._props[i]; this._overwriteProps.push(p); isFunc = this._func[p] = (typeof(target[p]) === "function"); first[p] = (!isFunc) ? parseFloat(target[p]) : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ](); if (!prepend) if (first[p] !== values[0][p]) { prepend = first; } } this._beziers = (vars.type !== "cubic" && vars.type !== "quadratic" && vars.type !== "soft") ? bezierThrough(values, isNaN(vars.curviness) ? 1 : vars.curviness, false, (vars.type === "thruBasic"), vars.correlate, prepend) : _parseBezierData(values, vars.type, first); this._segCount = this._beziers[p].length; if (this._timeRes) { var ld = _parseLengthData(this._beziers, this._timeRes); this._length = ld.length; this._lengths = ld.lengths; this._segments = ld.segments; this._l1 = this._li = this._s1 = this._si = 0; this._l2 = this._lengths[0]; this._curSeg = this._segments[0]; this._s2 = this._curSeg[0]; this._prec = 1 / this._curSeg.length; } if ((autoRotate = this._autoRotate)) { this._initialRotations = []; if (!(autoRotate[0] instanceof Array)) { this._autoRotate = autoRotate = [autoRotate]; } i = autoRotate.length; while (--i > -1) { for (j = 0; j < 3; j++) { p = autoRotate[i][j]; this._func[p] = (typeof(target[p]) === "function") ? target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ] : false; } p = autoRotate[i][2]; this._initialRotations[i] = (this._func[p] ? this._func[p].call(this._target) : this._target[p]) || 0; this._overwriteProps.push(p); } } this._startRatio = tween.vars.runBackwards ? 1 : 0; //we determine the starting ratio when the tween inits which is always 0 unless the tween has runBackwards:true (indicating it's a from() tween) in which case it's 1. return true; }, //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.) set: function(v) { var segments = this._segCount, func = this._func, target = this._target, notStart = (v !== this._startRatio), curIndex, inv, i, p, b, t, val, l, lengths, curSeg; if (!this._timeRes) { curIndex = (v < 0) ? 0 : (v >= 1) ? segments - 1 : (segments * v) >> 0; t = (v - (curIndex * (1 / segments))) * segments; } else { lengths = this._lengths; curSeg = this._curSeg; v *= this._length; i = this._li; //find the appropriate segment (if the currently cached one isn't correct) if (v > this._l2 && i < segments - 1) { l = segments - 1; while (i < l && (this._l2 = lengths[++i]) <= v) { } this._l1 = lengths[i-1]; this._li = i; this._curSeg = curSeg = this._segments[i]; this._s2 = curSeg[(this._s1 = this._si = 0)]; } else if (v < this._l1 && i > 0) { while (i > 0 && (this._l1 = lengths[--i]) >= v) { } if (i === 0 && v < this._l1) { this._l1 = 0; } else { i++; } this._l2 = lengths[i]; this._li = i; this._curSeg = curSeg = this._segments[i]; this._s1 = curSeg[(this._si = curSeg.length - 1) - 1] || 0; this._s2 = curSeg[this._si]; } curIndex = i; //now find the appropriate sub-segment (we split it into the number of pieces that was defined by "precision" and measured each one) v -= this._l1; i = this._si; if (v > this._s2 && i < curSeg.length - 1) { l = curSeg.length - 1; while (i < l && (this._s2 = curSeg[++i]) <= v) { } this._s1 = curSeg[i-1]; this._si = i; } else if (v < this._s1 && i > 0) { while (i > 0 && (this._s1 = curSeg[--i]) >= v) { } if (i === 0 && v < this._s1) { this._s1 = 0; } else { i++; } this._s2 = curSeg[i]; this._si = i; } t = ((i + (v - this._s1) / (this._s2 - this._s1)) * this._prec) || 0; } inv = 1 - t; i = this._props.length; while (--i > -1) { p = this._props[i]; b = this._beziers[p][curIndex]; val = (t * t * b.da + 3 * inv * (t * b.ca + inv * b.ba)) * t + b.a; if (this._mod[p]) { val = this._mod[p](val, target); } if (func[p]) { target[p](val); } else { target[p] = val; } } if (this._autoRotate) { var ar = this._autoRotate, b2, x1, y1, x2, y2, add, conv; i = ar.length; while (--i > -1) { p = ar[i][2]; add = ar[i][3] || 0; conv = (ar[i][4] === true) ? 1 : _RAD2DEG; b = this._beziers[ar[i][0]]; b2 = this._beziers[ar[i][1]]; if (b && b2) { //in case one of the properties got overwritten. b = b[curIndex]; b2 = b2[curIndex]; x1 = b.a + (b.b - b.a) * t; x2 = b.b + (b.c - b.b) * t; x1 += (x2 - x1) * t; x2 += ((b.c + (b.d - b.c) * t) - x2) * t; y1 = b2.a + (b2.b - b2.a) * t; y2 = b2.b + (b2.c - b2.b) * t; y1 += (y2 - y1) * t; y2 += ((b2.c + (b2.d - b2.c) * t) - y2) * t; val = notStart ? Math.atan2(y2 - y1, x2 - x1) * conv + add : this._initialRotations[i]; if (this._mod[p]) { val = this._mod[p](val, target); //for modProps } if (func[p]) { target[p](val); } else { target[p] = val; } } } } } }), p = BezierPlugin.prototype; BezierPlugin.bezierThrough = bezierThrough; BezierPlugin.cubicToQuadratic = cubicToQuadratic; BezierPlugin._autoCSS = true; //indicates that this plugin can be inserted into the "css" object using the autoCSS feature of TweenLite BezierPlugin.quadraticToCubic = function(a, b, c) { return new Segment(a, (2 * b + a) / 3, (2 * b + c) / 3, c); }; BezierPlugin._cssRegister = function() { var CSSPlugin = _globals.CSSPlugin; if (!CSSPlugin) { return; } var _internals = CSSPlugin._internals, _parseToProxy = _internals._parseToProxy, _setPluginRatio = _internals._setPluginRatio, CSSPropTween = _internals.CSSPropTween; _internals._registerComplexSpecialProp("bezier", {parser:function(t, e, prop, cssp, pt, plugin) { if (e instanceof Array) { e = {values:e}; } plugin = new BezierPlugin(); var values = e.values, l = values.length - 1, pluginValues = [], v = {}, i, p, data; if (l < 0) { return pt; } for (i = 0; i <= l; i++) { data = _parseToProxy(t, values[i], cssp, pt, plugin, (l !== i)); pluginValues[i] = data.end; } for (p in e) { v[p] = e[p]; //duplicate the vars object because we need to alter some things which would cause problems if the user plans to reuse the same vars object for another tween. } v.values = pluginValues; pt = new CSSPropTween(t, "bezier", 0, 0, data.pt, 2); pt.data = data; pt.plugin = plugin; pt.setRatio = _setPluginRatio; if (v.autoRotate === 0) { v.autoRotate = true; } if (v.autoRotate && !(v.autoRotate instanceof Array)) { i = (v.autoRotate === true) ? 0 : Number(v.autoRotate); v.autoRotate = (data.end.left != null) ? [["left","top","rotation",i,false]] : (data.end.x != null) ? [["x","y","rotation",i,false]] : false; } if (v.autoRotate) { if (!cssp._transform) { cssp._enableTransforms(false); } data.autoRotate = cssp._target._gsTransform; data.proxy.rotation = data.autoRotate.rotation || 0; cssp._overwriteProps.push("rotation"); } plugin._onInitTween(data.proxy, v, cssp._tween); return pt; }}); }; p._mod = function(lookup) { var op = this._overwriteProps, i = op.length, val; while (--i > -1) { val = lookup[op[i]]; if (val && typeof(val) === "function") { this._mod[op[i]] = val; } } }; p._kill = function(lookup) { var a = this._props, p, i; for (p in this._beziers) { if (p in lookup) { delete this._beziers[p]; delete this._func[p]; i = a.length; while (--i > -1) { if (a[i] === p) { a.splice(i, 1); } } } } a = this._autoRotate; if (a) { i = a.length; while (--i > -1) { if (lookup[a[i][2]]) { a.splice(i, 1); } } } return this._super._kill.call(this, lookup); }; }()); /* * ---------------------------------------------------------------- * CSSPlugin * ---------------------------------------------------------------- */ _gsScope._gsDefine("plugins.CSSPlugin", ["plugins.TweenPlugin","TweenLite"], function(TweenPlugin, TweenLite) { /** @constructor **/ var CSSPlugin = function() { TweenPlugin.call(this, "css"); this._overwriteProps.length = 0; this.setRatio = CSSPlugin.prototype.setRatio; //speed optimization (avoid prototype lookup on this "hot" method) }, _globals = _gsScope._gsDefine.globals, _hasPriority, //turns true whenever a CSSPropTween instance is created that has a priority other than 0. This helps us discern whether or not we should spend the time organizing the linked list or not after a CSSPlugin's _onInitTween() method is called. _suffixMap, //we set this in _onInitTween() each time as a way to have a persistent variable we can use in other methods like _parse() without having to pass it around as a parameter and we keep _parse() decoupled from a particular CSSPlugin instance _cs, //computed style (we store this in a shared variable to conserve memory and make minification tighter _overwriteProps, //alias to the currently instantiating CSSPlugin's _overwriteProps array. We use this closure in order to avoid having to pass a reference around from method to method and aid in minification. _specialProps = {}, p = CSSPlugin.prototype = new TweenPlugin("css"); p.constructor = CSSPlugin; CSSPlugin.version = "1.19.1"; CSSPlugin.API = 2; CSSPlugin.defaultTransformPerspective = 0; CSSPlugin.defaultSkewType = "compensated"; CSSPlugin.defaultSmoothOrigin = true; p = "px"; //we'll reuse the "p" variable to keep file size down CSSPlugin.suffixMap = {top:p, right:p, bottom:p, left:p, width:p, height:p, fontSize:p, padding:p, margin:p, perspective:p, lineHeight:""}; var _numExp = /(?:\-|\.|\b)(\d|\.|e\-)+/g, _relNumExp = /(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g, _valuesExp = /(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi, //finds all the values that begin with numbers or += or -= and then a number. Includes suffixes. We use this to split complex values apart like "1px 5px 20px rgb(255,102,51)" _NaNExp = /(?![+-]?\d*\.?\d+|[+-]|e[+-]\d+)[^0-9]/g, //also allows scientific notation and doesn't kill the leading -/+ in -= and += _suffixExp = /(?:\d|\-|\+|=|#|\.)*/g, _opacityExp = /opacity *= *([^)]*)/i, _opacityValExp = /opacity:([^;]*)/i, _alphaFilterExp = /alpha\(opacity *=.+?\)/i, _rgbhslExp = /^(rgb|hsl)/, _capsExp = /([A-Z])/g, _camelExp = /-([a-z])/gi, _urlExp = /(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi, //for pulling out urls from url(...) or url("...") strings (some browsers wrap urls in quotes, some don't when reporting things like backgroundImage) _camelFunc = function(s, g) { return g.toUpperCase(); }, _horizExp = /(?:Left|Right|Width)/i, _ieGetMatrixExp = /(M11|M12|M21|M22)=[\d\-\.e]+/gi, _ieSetMatrixExp = /progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i, _commasOutsideParenExp = /,(?=[^\)]*(?:\(|$))/gi, //finds any commas that are not within parenthesis _complexExp = /[\s,\(]/i, //for testing a string to find if it has a space, comma, or open parenthesis (clues that it's a complex value) _DEG2RAD = Math.PI / 180, _RAD2DEG = 180 / Math.PI, _forcePT = {}, _dummyElement = {style:{}}, _doc = _gsScope.document || {createElement: function() {return _dummyElement;}}, _createElement = function(type, ns) { return _doc.createElementNS ? _doc.createElementNS(ns || "http://www.w3.org/1999/xhtml", type) : _doc.createElement(type); }, _tempDiv = _createElement("div"), _tempImg = _createElement("img"), _internals = CSSPlugin._internals = {_specialProps:_specialProps}, //provides a hook to a few internal methods that we need to access from inside other plugins _agent = (_gsScope.navigator || {}).userAgent || "", _autoRound, _reqSafariFix, //we won't apply the Safari transform fix until we actually come across a tween that affects a transform property (to maintain best performance). _isSafari, _isFirefox, //Firefox has a bug that causes 3D transformed elements to randomly disappear unless a repaint is forced after each update on each element. _isSafariLT6, //Safari (and Android 4 which uses a flavor of Safari) has a bug that prevents changes to "top" and "left" properties from rendering properly if changed on the same frame as a transform UNLESS we set the element's WebkitBackfaceVisibility to hidden (weird, I know). Doing this for Android 3 and earlier seems to actually cause other problems, though (fun!) _ieVers, _supportsOpacity = (function() { //we set _isSafari, _ieVers, _isFirefox, and _supportsOpacity all in one function here to reduce file size slightly, especially in the minified version. var i = _agent.indexOf("Android"), a = _createElement("a"); _isSafari = (_agent.indexOf("Safari") !== -1 && _agent.indexOf("Chrome") === -1 && (i === -1 || parseFloat(_agent.substr(i+8, 2)) > 3)); _isSafariLT6 = (_isSafari && (parseFloat(_agent.substr(_agent.indexOf("Version/")+8, 2)) < 6)); _isFirefox = (_agent.indexOf("Firefox") !== -1); if ((/MSIE ([0-9]{1,}[\.0-9]{0,})/).exec(_agent) || (/Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/).exec(_agent)) { _ieVers = parseFloat( RegExp.$1 ); } if (!a) { return false; } a.style.cssText = "top:1px;opacity:.55;"; return /^0.55/.test(a.style.opacity); }()), _getIEOpacity = function(v) { return (_opacityExp.test( ((typeof(v) === "string") ? v : (v.currentStyle ? v.currentStyle.filter : v.style.filter) || "") ) ? ( parseFloat( RegExp.$1 ) / 100 ) : 1); }, _log = function(s) {//for logging messages, but in a way that won't throw errors in old versions of IE. if (_gsScope.console) { console.log(s); } }, _target, //when initting a CSSPlugin, we set this variable so that we can access it from within many other functions without having to pass it around as params _index, //when initting a CSSPlugin, we set this variable so that we can access it from within many other functions without having to pass it around as params _prefixCSS = "", //the non-camelCase vendor prefix like "-o-", "-moz-", "-ms-", or "-webkit-" _prefix = "", //camelCase vendor prefix like "O", "ms", "Webkit", or "Moz". // @private feed in a camelCase property name like "transform" and it will check to see if it is valid as-is or if it needs a vendor prefix. It returns the corrected camelCase property name (i.e. "WebkitTransform" or "MozTransform" or "transform" or null if no such property is found, like if the browser is IE8 or before, "transform" won't be found at all) _checkPropPrefix = function(p, e) { e = e || _tempDiv; var s = e.style, a, i; if (s[p] !== undefined) { return p; } p = p.charAt(0).toUpperCase() + p.substr(1); a = ["O","Moz","ms","Ms","Webkit"]; i = 5; while (--i > -1 && s[a[i]+p] === undefined) { } if (i >= 0) { _prefix = (i === 3) ? "ms" : a[i]; _prefixCSS = "-" + _prefix.toLowerCase() + "-"; return _prefix + p; } return null; }, _getComputedStyle = _doc.defaultView ? _doc.defaultView.getComputedStyle : function() {}, /** * @private Returns the css style for a particular property of an element. For example, to get whatever the current "left" css value for an element with an ID of "myElement", you could do: * var currentLeft = CSSPlugin.getStyle( document.getElementById("myElement"), "left"); * * @param {!Object} t Target element whose style property you want to query * @param {!string} p Property name (like "left" or "top" or "marginTop", etc.) * @param {Object=} cs Computed style object. This just provides a way to speed processing if you're going to get several properties on the same element in quick succession - you can reuse the result of the getComputedStyle() call. * @param {boolean=} calc If true, the value will not be read directly from the element's "style" property (if it exists there), but instead the getComputedStyle() result will be used. This can be useful when you want to ensure that the browser itself is interpreting the value. * @param {string=} dflt Default value that should be returned in the place of null, "none", "auto" or "auto auto". * @return {?string} The current property value */ _getStyle = CSSPlugin.getStyle = function(t, p, cs, calc, dflt) { var rv; if (!_supportsOpacity) if (p === "opacity") { //several versions of IE don't use the standard "opacity" property - they use things like filter:alpha(opacity=50), so we parse that here. return _getIEOpacity(t); } if (!calc && t.style[p]) { rv = t.style[p]; } else if ((cs = cs || _getComputedStyle(t))) { rv = cs[p] || cs.getPropertyValue(p) || cs.getPropertyValue(p.replace(_capsExp, "-$1").toLowerCase()); } else if (t.currentStyle) { rv = t.currentStyle[p]; } return (dflt != null && (!rv || rv === "none" || rv === "auto" || rv === "auto auto")) ? dflt : rv; }, /** * @private Pass the target element, the property name, the numeric value, and the suffix (like "%", "em", "px", etc.) and it will spit back the equivalent pixel number. * @param {!Object} t Target element * @param {!string} p Property name (like "left", "top", "marginLeft", etc.) * @param {!number} v Value * @param {string=} sfx Suffix (like "px" or "%" or "em") * @param {boolean=} recurse If true, the call is a recursive one. In some browsers (like IE7/8), occasionally the value isn't accurately reported initially, but if we run the function again it will take effect. * @return {number} value in pixels */ _convertToPixels = _internals.convertToPixels = function(t, p, v, sfx, recurse) { if (sfx === "px" || !sfx) { return v; } if (sfx === "auto" || !v) { return 0; } var horiz = _horizExp.test(p), node = t, style = _tempDiv.style, neg = (v < 0), precise = (v === 1), pix, cache, time; if (neg) { v = -v; } if (precise) { v *= 100; } if (sfx === "%" && p.indexOf("border") !== -1) { pix = (v / 100) * (horiz ? t.clientWidth : t.clientHeight); } else { style.cssText = "border:0 solid red;position:" + _getStyle(t, "position") + ";line-height:0;"; if (sfx === "%" || !node.appendChild || sfx.charAt(0) === "v" || sfx === "rem") { node = t.parentNode || _doc.body; cache = node._gsCache; time = TweenLite.ticker.frame; if (cache && horiz && cache.time === time) { //performance optimization: we record the width of elements along with the ticker frame so that we can quickly get it again on the same tick (seems relatively safe to assume it wouldn't change on the same tick) return cache.width * v / 100; } style[(horiz ? "width" : "height")] = v + sfx; } else { style[(horiz ? "borderLeftWidth" : "borderTopWidth")] = v + sfx; } node.appendChild(_tempDiv); pix = parseFloat(_tempDiv[(horiz ? "offsetWidth" : "offsetHeight")]); node.removeChild(_tempDiv); if (horiz && sfx === "%" && CSSPlugin.cacheWidths !== false) { cache = node._gsCache = node._gsCache || {}; cache.time = time; cache.width = pix / v * 100; } if (pix === 0 && !recurse) { pix = _convertToPixels(t, p, v, sfx, true); } } if (precise) { pix /= 100; } return neg ? -pix : pix; }, _calculateOffset = _internals.calculateOffset = function(t, p, cs) { //for figuring out "top" or "left" in px when it's "auto". We need to factor in margin with the offsetLeft/offsetTop if (_getStyle(t, "position", cs) !== "absolute") { return 0; } var dim = ((p === "left") ? "Left" : "Top"), v = _getStyle(t, "margin" + dim, cs); return t["offset" + dim] - (_convertToPixels(t, p, parseFloat(v), v.replace(_suffixExp, "")) || 0); }, // @private returns at object containing ALL of the style properties in camelCase and their associated values. _getAllStyles = function(t, cs) { var s = {}, i, tr, p; if ((cs = cs || _getComputedStyle(t, null))) { if ((i = cs.length)) { while (--i > -1) { p = cs[i]; if (p.indexOf("-transform") === -1 || _transformPropCSS === p) { //Some webkit browsers duplicate transform values, one non-prefixed and one prefixed ("transform" and "WebkitTransform"), so we must weed out the extra one here. s[p.replace(_camelExp, _camelFunc)] = cs.getPropertyValue(p); } } } else { //some browsers behave differently - cs.length is always 0, so we must do a for...in loop. for (i in cs) { if (i.indexOf("Transform") === -1 || _transformProp === i) { //Some webkit browsers duplicate transform values, one non-prefixed and one prefixed ("transform" and "WebkitTransform"), so we must weed out the extra one here. s[i] = cs[i]; } } } } else if ((cs = t.currentStyle || t.style)) { for (i in cs) { if (typeof(i) === "string" && s[i] === undefined) { s[i.replace(_camelExp, _camelFunc)] = cs[i]; } } } if (!_supportsOpacity) { s.opacity = _getIEOpacity(t); } tr = _getTransform(t, cs, false); s.rotation = tr.rotation; s.skewX = tr.skewX; s.scaleX = tr.scaleX; s.scaleY = tr.scaleY; s.x = tr.x; s.y = tr.y; if (_supports3D) { s.z = tr.z; s.rotationX = tr.rotationX; s.rotationY = tr.rotationY; s.scaleZ = tr.scaleZ; } if (s.filters) { delete s.filters; } return s; }, // @private analyzes two style objects (as returned by _getAllStyles()) and only looks for differences between them that contain tweenable values (like a number or color). It returns an object with a "difs" property which refers to an object containing only those isolated properties and values for tweening, and a "firstMPT" property which refers to the first MiniPropTween instance in a linked list that recorded all the starting values of the different properties so that we can revert to them at the end or beginning of the tween - we don't want the cascading to get messed up. The forceLookup parameter is an optional generic object with properties that should be forced into the results - this is necessary for className tweens that are overwriting others because imagine a scenario where a rollover/rollout adds/removes a class and the user swipes the mouse over the target SUPER fast, thus nothing actually changed yet and the subsequent comparison of the properties would indicate they match (especially when px rounding is taken into consideration), thus no tweening is necessary even though it SHOULD tween and remove those properties after the tween (otherwise the inline styles will contaminate things). See the className SpecialProp code for details. _cssDif = function(t, s1, s2, vars, forceLookup) { var difs = {}, style = t.style, val, p, mpt; for (p in s2) { if (p !== "cssText") if (p !== "length") if (isNaN(p)) if (s1[p] !== (val = s2[p]) || (forceLookup && forceLookup[p])) if (p.indexOf("Origin") === -1) if (typeof(val) === "number" || typeof(val) === "string") { difs[p] = (val === "auto" && (p === "left" || p === "top")) ? _calculateOffset(t, p) : ((val === "" || val === "auto" || val === "none") && typeof(s1[p]) === "string" && s1[p].replace(_NaNExp, "") !== "") ? 0 : val; //if the ending value is defaulting ("" or "auto"), we check the starting value and if it can be parsed into a number (a string which could have a suffix too, like 700px), then we swap in 0 for "" or "auto" so that things actually tween. if (style[p] !== undefined) { //for className tweens, we must remember which properties already existed inline - the ones that didn't should be removed when the tween isn't in progress because they were only introduced to facilitate the transition between classes. mpt = new MiniPropTween(style, p, style[p], mpt); } } } if (vars) { for (p in vars) { //copy properties (except className) if (p !== "className") { difs[p] = vars[p]; } } } return {difs:difs, firstMPT:mpt}; }, _dimensions = {width:["Left","Right"], height:["Top","Bottom"]}, _margins = ["marginLeft","marginRight","marginTop","marginBottom"], /** * @private Gets the width or height of an element * @param {!Object} t Target element * @param {!string} p Property name ("width" or "height") * @param {Object=} cs Computed style object (if one exists). Just a speed optimization. * @return {number} Dimension (in pixels) */ _getDimension = function(t, p, cs) { if ((t.nodeName + "").toLowerCase() === "svg") { //Chrome no longer supports offsetWidth/offsetHeight on SVG elements. return (cs || _getComputedStyle(t))[p] || 0; } else if (t.getCTM && _isSVG(t)) { return t.getBBox()[p] || 0; } var v = parseFloat((p === "width") ? t.offsetWidth : t.offsetHeight), a = _dimensions[p], i = a.length; cs = cs || _getComputedStyle(t, null); while (--i > -1) { v -= parseFloat( _getStyle(t, "padding" + a[i], cs, true) ) || 0; v -= parseFloat( _getStyle(t, "border" + a[i] + "Width", cs, true) ) || 0; } return v; }, // @private Parses position-related complex strings like "top left" or "50px 10px" or "70% 20%", etc. which are used for things like transformOrigin or backgroundPosition. Optionally decorates a supplied object (recObj) with the following properties: "ox" (offsetX), "oy" (offsetY), "oxp" (if true, "ox" is a percentage not a pixel value), and "oxy" (if true, "oy" is a percentage not a pixel value) _parsePosition = function(v, recObj) { if (v === "contain" || v === "auto" || v === "auto auto") { //note: Firefox uses "auto auto" as default whereas Chrome uses "auto". return v + " "; } if (v == null || v === "") { v = "0 0"; } var a = v.split(" "), x = (v.indexOf("left") !== -1) ? "0%" : (v.indexOf("right") !== -1) ? "100%" : a[0], y = (v.indexOf("top") !== -1) ? "0%" : (v.indexOf("bottom") !== -1) ? "100%" : a[1], i; if (a.length > 3 && !recObj) { //multiple positions a = v.split(", ").join(",").split(","); v = []; for (i = 0; i < a.length; i++) { v.push(_parsePosition(a[i])); } return v.join(","); } if (y == null) { y = (x === "center") ? "50%" : "0"; } else if (y === "center") { y = "50%"; } if (x === "center" || (isNaN(parseFloat(x)) && (x + "").indexOf("=") === -1)) { //remember, the user could flip-flop the values and say "bottom center" or "center bottom", etc. "center" is ambiguous because it could be used to describe horizontal or vertical, hence the isNaN(). If there's an "=" sign in the value, it's relative. x = "50%"; } v = x + " " + y + ((a.length > 2) ? " " + a[2] : ""); if (recObj) { recObj.oxp = (x.indexOf("%") !== -1); recObj.oyp = (y.indexOf("%") !== -1); recObj.oxr = (x.charAt(1) === "="); recObj.oyr = (y.charAt(1) === "="); recObj.ox = parseFloat(x.replace(_NaNExp, "")); recObj.oy = parseFloat(y.replace(_NaNExp, "")); recObj.v = v; } return recObj || v; }, /** * @private Takes an ending value (typically a string, but can be a number) and a starting value and returns the change between the two, looking for relative value indicators like += and -= and it also ignores suffixes (but make sure the ending value starts with a number or +=/-= and that the starting value is a NUMBER!) * @param {(number|string)} e End value which is typically a string, but could be a number * @param {(number|string)} b Beginning value which is typically a string but could be a number * @return {number} Amount of change between the beginning and ending values (relative values that have a "+=" or "-=" are recognized) */ _parseChange = function(e, b) { if (typeof(e) === "function") { e = e(_index, _target); } return (typeof(e) === "string" && e.charAt(1) === "=") ? parseInt(e.charAt(0) + "1", 10) * parseFloat(e.substr(2)) : (parseFloat(e) - parseFloat(b)) || 0; }, /** * @private Takes a value and a default number, checks if the value is relative, null, or numeric and spits back a normalized number accordingly. Primarily used in the _parseTransform() function. * @param {Object} v Value to be parsed * @param {!number} d Default value (which is also used for relative calculations if "+=" or "-=" is found in the first parameter) * @return {number} Parsed value */ _parseVal = function(v, d) { if (typeof(v) === "function") { v = v(_index, _target); } return (v == null) ? d : (typeof(v) === "string" && v.charAt(1) === "=") ? parseInt(v.charAt(0) + "1", 10) * parseFloat(v.substr(2)) + d : parseFloat(v) || 0; }, /** * @private Translates strings like "40deg" or "40" or 40rad" or "+=40deg" or "270_short" or "-90_cw" or "+=45_ccw" to a numeric radian angle. Of course a starting/default value must be fed in too so that relative values can be calculated properly. * @param {Object} v Value to be parsed * @param {!number} d Default value (which is also used for relative calculations if "+=" or "-=" is found in the first parameter) * @param {string=} p property name for directionalEnd (optional - only used when the parsed value is directional ("_short", "_cw", or "_ccw" suffix). We need a way to store the uncompensated value so that at the end of the tween, we set it to exactly what was requested with no directional compensation). Property name would be "rotation", "rotationX", or "rotationY" * @param {Object=} directionalEnd An object that will store the raw end values for directional angles ("_short", "_cw", or "_ccw" suffix). We need a way to store the uncompensated value so that at the end of the tween, we set it to exactly what was requested with no directional compensation. * @return {number} parsed angle in radians */ _parseAngle = function(v, d, p, directionalEnd) { var min = 0.000001, cap, split, dif, result, isRelative; if (typeof(v) === "function") { v = v(_index, _target); } if (v == null) { result = d; } else if (typeof(v) === "number") { result = v; } else { cap = 360; split = v.split("_"); isRelative = (v.charAt(1) === "="); dif = (isRelative ? parseInt(v.charAt(0) + "1", 10) * parseFloat(split[0].substr(2)) : parseFloat(split[0])) * ((v.indexOf("rad") === -1) ? 1 : _RAD2DEG) - (isRelative ? 0 : d); if (split.length) { if (directionalEnd) { directionalEnd[p] = d + dif; } if (v.indexOf("short") !== -1) { dif = dif % cap; if (dif !== dif % (cap / 2)) { dif = (dif < 0) ? dif + cap : dif - cap; } } if (v.indexOf("_cw") !== -1 && dif < 0) { dif = ((dif + cap * 9999999999) % cap) - ((dif / cap) | 0) * cap; } else if (v.indexOf("ccw") !== -1 && dif > 0) { dif = ((dif - cap * 9999999999) % cap) - ((dif / cap) | 0) * cap; } } result = d + dif; } if (result < min && result > -min) { result = 0; } return result; }, _colorLookup = {aqua:[0,255,255], lime:[0,255,0], silver:[192,192,192], black:[0,0,0], maroon:[128,0,0], teal:[0,128,128], blue:[0,0,255], navy:[0,0,128], white:[255,255,255], fuchsia:[255,0,255], olive:[128,128,0], yellow:[255,255,0], orange:[255,165,0], gray:[128,128,128], purple:[128,0,128], green:[0,128,0], red:[255,0,0], pink:[255,192,203], cyan:[0,255,255], transparent:[255,255,255,0]}, _hue = function(h, m1, m2) { h = (h < 0) ? h + 1 : (h > 1) ? h - 1 : h; return ((((h * 6 < 1) ? m1 + (m2 - m1) * h * 6 : (h < 0.5) ? m2 : (h * 3 < 2) ? m1 + (m2 - m1) * (2 / 3 - h) * 6 : m1) * 255) + 0.5) | 0; }, /** * @private Parses a color (like #9F0, #FF9900, rgb(255,51,153) or hsl(108, 50%, 10%)) into an array with 3 elements for red, green, and blue or if toHSL parameter is true, it will populate the array with hue, saturation, and lightness values. If a relative value is found in an hsl() or hsla() string, it will preserve those relative prefixes and all the values in the array will be strings instead of numbers (in all other cases it will be populated with numbers). * @param {(string|number)} v The value the should be parsed which could be a string like #9F0 or rgb(255,102,51) or rgba(255,0,0,0.5) or it could be a number like 0xFF00CC or even a named color like red, blue, purple, etc. * @param {(boolean)} toHSL If true, an hsl() or hsla() value will be returned instead of rgb() or rgba() * @return {Array.} An array containing red, green, and blue (and optionally alpha) in that order, or if the toHSL parameter was true, the array will contain hue, saturation and lightness (and optionally alpha) in that order. Always numbers unless there's a relative prefix found in an hsl() or hsla() string and toHSL is true. */ _parseColor = CSSPlugin.parseColor = function(v, toHSL) { var a, r, g, b, h, s, l, max, min, d, wasHSL; if (!v) { a = _colorLookup.black; } else if (typeof(v) === "number") { a = [v >> 16, (v >> 8) & 255, v & 255]; } else { if (v.charAt(v.length - 1) === ",") { //sometimes a trailing comma is included and we should chop it off (typically from a comma-delimited list of values like a textShadow:"2px 2px 2px blue, 5px 5px 5px rgb(255,0,0)" - in this example "blue," has a trailing comma. We could strip it out inside parseComplex() but we'd need to do it to the beginning and ending values plus it wouldn't provide protection from other potential scenarios like if the user passes in a similar value. v = v.substr(0, v.length - 1); } if (_colorLookup[v]) { a = _colorLookup[v]; } else if (v.charAt(0) === "#") { if (v.length === 4) { //for shorthand like #9F0 r = v.charAt(1); g = v.charAt(2); b = v.charAt(3); v = "#" + r + r + g + g + b + b; } v = parseInt(v.substr(1), 16); a = [v >> 16, (v >> 8) & 255, v & 255]; } else if (v.substr(0, 3) === "hsl") { a = wasHSL = v.match(_numExp); if (!toHSL) { h = (Number(a[0]) % 360) / 360; s = Number(a[1]) / 100; l = Number(a[2]) / 100; g = (l <= 0.5) ? l * (s + 1) : l + s - l * s; r = l * 2 - g; if (a.length > 3) { a[3] = Number(v[3]); } a[0] = _hue(h + 1 / 3, r, g); a[1] = _hue(h, r, g); a[2] = _hue(h - 1 / 3, r, g); } else if (v.indexOf("=") !== -1) { //if relative values are found, just return the raw strings with the relative prefixes in place. return v.match(_relNumExp); } } else { a = v.match(_numExp) || _colorLookup.transparent; } a[0] = Number(a[0]); a[1] = Number(a[1]); a[2] = Number(a[2]); if (a.length > 3) { a[3] = Number(a[3]); } } if (toHSL && !wasHSL) { r = a[0] / 255; g = a[1] / 255; b = a[2] / 255; max = Math.max(r, g, b); min = Math.min(r, g, b); l = (max + min) / 2; if (max === min) { h = s = 0; } else { d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); h = (max === r) ? (g - b) / d + (g < b ? 6 : 0) : (max === g) ? (b - r) / d + 2 : (r - g) / d + 4; h *= 60; } a[0] = (h + 0.5) | 0; a[1] = (s * 100 + 0.5) | 0; a[2] = (l * 100 + 0.5) | 0; } return a; }, _formatColors = function(s, toHSL) { var colors = s.match(_colorExp) || [], charIndex = 0, parsed = colors.length ? "" : s, i, color, temp; for (i = 0; i < colors.length; i++) { color = colors[i]; temp = s.substr(charIndex, s.indexOf(color, charIndex)-charIndex); charIndex += temp.length + color.length; color = _parseColor(color, toHSL); if (color.length === 3) { color.push(1); } parsed += temp + (toHSL ? "hsla(" + color[0] + "," + color[1] + "%," + color[2] + "%," + color[3] : "rgba(" + color.join(",")) + ")"; } return parsed + s.substr(charIndex); }, _colorExp = "(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#(?:[0-9a-f]{3}){1,2}\\b"; //we'll dynamically build this Regular Expression to conserve file size. After building it, it will be able to find rgb(), rgba(), # (hexadecimal), and named color values like red, blue, purple, etc. for (p in _colorLookup) { _colorExp += "|" + p + "\\b"; } _colorExp = new RegExp(_colorExp+")", "gi"); CSSPlugin.colorStringFilter = function(a) { var combined = a[0] + a[1], toHSL; if (_colorExp.test(combined)) { toHSL = (combined.indexOf("hsl(") !== -1 || combined.indexOf("hsla(") !== -1); a[0] = _formatColors(a[0], toHSL); a[1] = _formatColors(a[1], toHSL); } _colorExp.lastIndex = 0; }; if (!TweenLite.defaultStringFilter) { TweenLite.defaultStringFilter = CSSPlugin.colorStringFilter; } /** * @private Returns a formatter function that handles taking a string (or number in some cases) and returning a consistently formatted one in terms of delimiters, quantity of values, etc. For example, we may get boxShadow values defined as "0px red" or "0px 0px 10px rgb(255,0,0)" or "0px 0px 20px 20px #F00" and we need to ensure that what we get back is described with 4 numbers and a color. This allows us to feed it into the _parseComplex() method and split the values up appropriately. The neat thing about this _getFormatter() function is that the dflt defines a pattern as well as a default, so for example, _getFormatter("0px 0px 0px 0px #777", true) not only sets the default as 0px for all distances and #777 for the color, but also sets the pattern such that 4 numbers and a color will always get returned. * @param {!string} dflt The default value and pattern to follow. So "0px 0px 0px 0px #777" will ensure that 4 numbers and a color will always get returned. * @param {boolean=} clr If true, the values should be searched for color-related data. For example, boxShadow values typically contain a color whereas borderRadius don't. * @param {boolean=} collapsible If true, the value is a top/left/right/bottom style one that acts like margin or padding, where if only one value is received, it's used for all 4; if 2 are received, the first is duplicated for 3rd (bottom) and the 2nd is duplicated for the 4th spot (left), etc. * @return {Function} formatter function */ var _getFormatter = function(dflt, clr, collapsible, multi) { if (dflt == null) { return function(v) {return v;}; } var dColor = clr ? (dflt.match(_colorExp) || [""])[0] : "", dVals = dflt.split(dColor).join("").match(_valuesExp) || [], pfx = dflt.substr(0, dflt.indexOf(dVals[0])), sfx = (dflt.charAt(dflt.length - 1) === ")") ? ")" : "", delim = (dflt.indexOf(" ") !== -1) ? " " : ",", numVals = dVals.length, dSfx = (numVals > 0) ? dVals[0].replace(_numExp, "") : "", formatter; if (!numVals) { return function(v) {return v;}; } if (clr) { formatter = function(v) { var color, vals, i, a; if (typeof(v) === "number") { v += dSfx; } else if (multi && _commasOutsideParenExp.test(v)) { a = v.replace(_commasOutsideParenExp, "|").split("|"); for (i = 0; i < a.length; i++) { a[i] = formatter(a[i]); } return a.join(","); } color = (v.match(_colorExp) || [dColor])[0]; vals = v.split(color).join("").match(_valuesExp) || []; i = vals.length; if (numVals > i--) { while (++i < numVals) { vals[i] = collapsible ? vals[(((i - 1) / 2) | 0)] : dVals[i]; } } return pfx + vals.join(delim) + delim + color + sfx + (v.indexOf("inset") !== -1 ? " inset" : ""); }; return formatter; } formatter = function(v) { var vals, a, i; if (typeof(v) === "number") { v += dSfx; } else if (multi && _commasOutsideParenExp.test(v)) { a = v.replace(_commasOutsideParenExp, "|").split("|"); for (i = 0; i < a.length; i++) { a[i] = formatter(a[i]); } return a.join(","); } vals = v.match(_valuesExp) || []; i = vals.length; if (numVals > i--) { while (++i < numVals) { vals[i] = collapsible ? vals[(((i - 1) / 2) | 0)] : dVals[i]; } } return pfx + vals.join(delim) + sfx; }; return formatter; }, /** * @private returns a formatter function that's used for edge-related values like marginTop, marginLeft, paddingBottom, paddingRight, etc. Just pass a comma-delimited list of property names related to the edges. * @param {!string} props a comma-delimited list of property names in order from top to left, like "marginTop,marginRight,marginBottom,marginLeft" * @return {Function} a formatter function */ _getEdgeParser = function(props) { props = props.split(","); return function(t, e, p, cssp, pt, plugin, vars) { var a = (e + "").split(" "), i; vars = {}; for (i = 0; i < 4; i++) { vars[props[i]] = a[i] = a[i] || a[(((i - 1) / 2) >> 0)]; } return cssp.parse(t, vars, pt, plugin); }; }, // @private used when other plugins must tween values first, like BezierPlugin or ThrowPropsPlugin, etc. That plugin's setRatio() gets called first so that the values are updated, and then we loop through the MiniPropTweens which handle copying the values into their appropriate slots so that they can then be applied correctly in the main CSSPlugin setRatio() method. Remember, we typically create a proxy object that has a bunch of uniquely-named properties that we feed to the sub-plugin and it does its magic normally, and then we must interpret those values and apply them to the css because often numbers must get combined/concatenated, suffixes added, etc. to work with css, like boxShadow could have 4 values plus a color. _setPluginRatio = _internals._setPluginRatio = function(v) { this.plugin.setRatio(v); var d = this.data, proxy = d.proxy, mpt = d.firstMPT, min = 0.000001, val, pt, i, str, p; while (mpt) { val = proxy[mpt.v]; if (mpt.r) { val = Math.round(val); } else if (val < min && val > -min) { val = 0; } mpt.t[mpt.p] = val; mpt = mpt._next; } if (d.autoRotate) { d.autoRotate.rotation = d.mod ? d.mod(proxy.rotation, this.t) : proxy.rotation; //special case for ModifyPlugin to hook into an auto-rotating bezier } //at the end, we must set the CSSPropTween's "e" (end) value dynamically here because that's what is used in the final setRatio() method. Same for "b" at the beginning. if (v === 1 || v === 0) { mpt = d.firstMPT; p = (v === 1) ? "e" : "b"; while (mpt) { pt = mpt.t; if (!pt.type) { pt[p] = pt.s + pt.xs0; } else if (pt.type === 1) { str = pt.xs0 + pt.s + pt.xs1; for (i = 1; i < pt.l; i++) { str += pt["xn"+i] + pt["xs"+(i+1)]; } pt[p] = str; } mpt = mpt._next; } } }, /** * @private @constructor Used by a few SpecialProps to hold important values for proxies. For example, _parseToProxy() creates a MiniPropTween instance for each property that must get tweened on the proxy, and we record the original property name as well as the unique one we create for the proxy, plus whether or not the value needs to be rounded plus the original value. * @param {!Object} t target object whose property we're tweening (often a CSSPropTween) * @param {!string} p property name * @param {(number|string|object)} v value * @param {MiniPropTween=} next next MiniPropTween in the linked list * @param {boolean=} r if true, the tweened value should be rounded to the nearest integer */ MiniPropTween = function(t, p, v, next, r) { this.t = t; this.p = p; this.v = v; this.r = r; if (next) { next._prev = this; this._next = next; } }, /** * @private Most other plugins (like BezierPlugin and ThrowPropsPlugin and others) can only tween numeric values, but CSSPlugin must accommodate special values that have a bunch of extra data (like a suffix or strings between numeric values, etc.). For example, boxShadow has values like "10px 10px 20px 30px rgb(255,0,0)" which would utterly confuse other plugins. This method allows us to split that data apart and grab only the numeric data and attach it to uniquely-named properties of a generic proxy object ({}) so that we can feed that to virtually any plugin to have the numbers tweened. However, we must also keep track of which properties from the proxy go with which CSSPropTween values and instances. So we create a linked list of MiniPropTweens. Each one records a target (the original CSSPropTween), property (like "s" or "xn1" or "xn2") that we're tweening and the unique property name that was used for the proxy (like "boxShadow_xn1" and "boxShadow_xn2") and whether or not they need to be rounded. That way, in the _setPluginRatio() method we can simply copy the values over from the proxy to the CSSPropTween instance(s). Then, when the main CSSPlugin setRatio() method runs and applies the CSSPropTween values accordingly, they're updated nicely. So the external plugin tweens the numbers, _setPluginRatio() copies them over, and setRatio() acts normally, applying css-specific values to the element. * This method returns an object that has the following properties: * - proxy: a generic object containing the starting values for all the properties that will be tweened by the external plugin. This is what we feed to the external _onInitTween() as the target * - end: a generic object containing the ending values for all the properties that will be tweened by the external plugin. This is what we feed to the external plugin's _onInitTween() as the destination values * - firstMPT: the first MiniPropTween in the linked list * - pt: the first CSSPropTween in the linked list that was created when parsing. If shallow is true, this linked list will NOT attach to the one passed into the _parseToProxy() as the "pt" (4th) parameter. * @param {!Object} t target object to be tweened * @param {!(Object|string)} vars the object containing the information about the tweening values (typically the end/destination values) that should be parsed * @param {!CSSPlugin} cssp The CSSPlugin instance * @param {CSSPropTween=} pt the next CSSPropTween in the linked list * @param {TweenPlugin=} plugin the external TweenPlugin instance that will be handling tweening the numeric values * @param {boolean=} shallow if true, the resulting linked list from the parse will NOT be attached to the CSSPropTween that was passed in as the "pt" (4th) parameter. * @return An object containing the following properties: proxy, end, firstMPT, and pt (see above for descriptions) */ _parseToProxy = _internals._parseToProxy = function(t, vars, cssp, pt, plugin, shallow) { var bpt = pt, start = {}, end = {}, transform = cssp._transform, oldForce = _forcePT, i, p, xp, mpt, firstPT; cssp._transform = null; _forcePT = vars; pt = firstPT = cssp.parse(t, vars, pt, plugin); _forcePT = oldForce; //break off from the linked list so the new ones are isolated. if (shallow) { cssp._transform = transform; if (bpt) { bpt._prev = null; if (bpt._prev) { bpt._prev._next = null; } } } while (pt && pt !== bpt) { if (pt.type <= 1) { p = pt.p; end[p] = pt.s + pt.c; start[p] = pt.s; if (!shallow) { mpt = new MiniPropTween(pt, "s", p, mpt, pt.r); pt.c = 0; } if (pt.type === 1) { i = pt.l; while (--i > 0) { xp = "xn" + i; p = pt.p + "_" + xp; end[p] = pt.data[xp]; start[p] = pt[xp]; if (!shallow) { mpt = new MiniPropTween(pt, xp, p, mpt, pt.rxp[xp]); } } } } pt = pt._next; } return {proxy:start, end:end, firstMPT:mpt, pt:firstPT}; }, /** * @constructor Each property that is tweened has at least one CSSPropTween associated with it. These instances store important information like the target, property, starting value, amount of change, etc. They can also optionally have a number of "extra" strings and numeric values named xs1, xn1, xs2, xn2, xs3, xn3, etc. where "s" indicates string and "n" indicates number. These can be pieced together in a complex-value tween (type:1) that has alternating types of data like a string, number, string, number, etc. For example, boxShadow could be "5px 5px 8px rgb(102, 102, 51)". In that value, there are 6 numbers that may need to tween and then pieced back together into a string again with spaces, suffixes, etc. xs0 is special in that it stores the suffix for standard (type:0) tweens, -OR- the first string (prefix) in a complex-value (type:1) CSSPropTween -OR- it can be the non-tweening value in a type:-1 CSSPropTween. We do this to conserve memory. * CSSPropTweens have the following optional properties as well (not defined through the constructor): * - l: Length in terms of the number of extra properties that the CSSPropTween has (default: 0). For example, for a boxShadow we may need to tween 5 numbers in which case l would be 5; Keep in mind that the start/end values for the first number that's tweened are always stored in the s and c properties to conserve memory. All additional values thereafter are stored in xn1, xn2, etc. * - xfirst: The first instance of any sub-CSSPropTweens that are tweening properties of this instance. For example, we may split up a boxShadow tween so that there's a main CSSPropTween of type:1 that has various xs* and xn* values associated with the h-shadow, v-shadow, blur, color, etc. Then we spawn a CSSPropTween for each of those that has a higher priority and runs BEFORE the main CSSPropTween so that the values are all set by the time it needs to re-assemble them. The xfirst gives us an easy way to identify the first one in that chain which typically ends at the main one (because they're all prepende to the linked list) * - plugin: The TweenPlugin instance that will handle the tweening of any complex values. For example, sometimes we don't want to use normal subtweens (like xfirst refers to) to tween the values - we might want ThrowPropsPlugin or BezierPlugin some other plugin to do the actual tweening, so we create a plugin instance and store a reference here. We need this reference so that if we get a request to round values or disable a tween, we can pass along that request. * - data: Arbitrary data that needs to be stored with the CSSPropTween. Typically if we're going to have a plugin handle the tweening of a complex-value tween, we create a generic object that stores the END values that we're tweening to and the CSSPropTween's xs1, xs2, etc. have the starting values. We store that object as data. That way, we can simply pass that object to the plugin and use the CSSPropTween as the target. * - setRatio: Only used for type:2 tweens that require custom functionality. In this case, we call the CSSPropTween's setRatio() method and pass the ratio each time the tween updates. This isn't quite as efficient as doing things directly in the CSSPlugin's setRatio() method, but it's very convenient and flexible. * @param {!Object} t Target object whose property will be tweened. Often a DOM element, but not always. It could be anything. * @param {string} p Property to tween (name). For example, to tween element.width, p would be "width". * @param {number} s Starting numeric value * @param {number} c Change in numeric value over the course of the entire tween. For example, if element.width starts at 5 and should end at 100, c would be 95. * @param {CSSPropTween=} next The next CSSPropTween in the linked list. If one is defined, we will define its _prev as the new instance, and the new instance's _next will be pointed at it. * @param {number=} type The type of CSSPropTween where -1 = a non-tweening value, 0 = a standard simple tween, 1 = a complex value (like one that has multiple numbers in a comma- or space-delimited string like border:"1px solid red"), and 2 = one that uses a custom setRatio function that does all of the work of applying the values on each update. * @param {string=} n Name of the property that should be used for overwriting purposes which is typically the same as p but not always. For example, we may need to create a subtween for the 2nd part of a "clip:rect(...)" tween in which case "p" might be xs1 but "n" is still "clip" * @param {boolean=} r If true, the value(s) should be rounded * @param {number=} pr Priority in the linked list order. Higher priority CSSPropTweens will be updated before lower priority ones. The default priority is 0. * @param {string=} b Beginning value. We store this to ensure that it is EXACTLY what it was when the tween began without any risk of interpretation issues. * @param {string=} e Ending value. We store this to ensure that it is EXACTLY what the user defined at the end of the tween without any risk of interpretation issues. */ CSSPropTween = _internals.CSSPropTween = function(t, p, s, c, next, type, n, r, pr, b, e) { this.t = t; //target this.p = p; //property this.s = s; //starting value this.c = c; //change value this.n = n || p; //name that this CSSPropTween should be associated to (usually the same as p, but not always - n is what overwriting looks at) if (!(t instanceof CSSPropTween)) { _overwriteProps.push(this.n); } this.r = r; //round (boolean) this.type = type || 0; //0 = normal tween, -1 = non-tweening (in which case xs0 will be applied to the target's property, like tp.t[tp.p] = tp.xs0), 1 = complex-value SpecialProp, 2 = custom setRatio() that does all the work if (pr) { this.pr = pr; _hasPriority = true; } this.b = (b === undefined) ? s : b; this.e = (e === undefined) ? s + c : e; if (next) { this._next = next; next._prev = this; } }, _addNonTweeningNumericPT = function(target, prop, start, end, next, overwriteProp) { //cleans up some code redundancies and helps minification. Just a fast way to add a NUMERIC non-tweening CSSPropTween var pt = new CSSPropTween(target, prop, start, end - start, next, -1, overwriteProp); pt.b = start; pt.e = pt.xs0 = end; return pt; }, /** * Takes a target, the beginning value and ending value (as strings) and parses them into a CSSPropTween (possibly with child CSSPropTweens) that accommodates multiple numbers, colors, comma-delimited values, etc. For example: * sp.parseComplex(element, "boxShadow", "5px 10px 20px rgb(255,102,51)", "0px 0px 0px red", true, "0px 0px 0px rgb(0,0,0,0)", pt); * It will walk through the beginning and ending values (which should be in the same format with the same number and type of values) and figure out which parts are numbers, what strings separate the numeric/tweenable values, and then create the CSSPropTweens accordingly. If a plugin is defined, no child CSSPropTweens will be created. Instead, the ending values will be stored in the "data" property of the returned CSSPropTween like: {s:-5, xn1:-10, xn2:-20, xn3:255, xn4:0, xn5:0} so that it can be fed to any other plugin and it'll be plain numeric tweens but the recomposition of the complex value will be handled inside CSSPlugin's setRatio(). * If a setRatio is defined, the type of the CSSPropTween will be set to 2 and recomposition of the values will be the responsibility of that method. * * @param {!Object} t Target whose property will be tweened * @param {!string} p Property that will be tweened (its name, like "left" or "backgroundColor" or "boxShadow") * @param {string} b Beginning value * @param {string} e Ending value * @param {boolean} clrs If true, the value could contain a color value like "rgb(255,0,0)" or "#F00" or "red". The default is false, so no colors will be recognized (a performance optimization) * @param {(string|number|Object)} dflt The default beginning value that should be used if no valid beginning value is defined or if the number of values inside the complex beginning and ending values don't match * @param {?CSSPropTween} pt CSSPropTween instance that is the current head of the linked list (we'll prepend to this). * @param {number=} pr Priority in the linked list order. Higher priority properties will be updated before lower priority ones. The default priority is 0. * @param {TweenPlugin=} plugin If a plugin should handle the tweening of extra properties, pass the plugin instance here. If one is defined, then NO subtweens will be created for any extra properties (the properties will be created - just not additional CSSPropTween instances to tween them) because the plugin is expected to do so. However, the end values WILL be populated in the "data" property, like {s:100, xn1:50, xn2:300} * @param {function(number)=} setRatio If values should be set in a custom function instead of being pieced together in a type:1 (complex-value) CSSPropTween, define that custom function here. * @return {CSSPropTween} The first CSSPropTween in the linked list which includes the new one(s) added by the parseComplex() call. */ _parseComplex = CSSPlugin.parseComplex = function(t, p, b, e, clrs, dflt, pt, pr, plugin, setRatio) { //DEBUG: _log("parseComplex: "+p+", b: "+b+", e: "+e); b = b || dflt || ""; if (typeof(e) === "function") { e = e(_index, _target); } pt = new CSSPropTween(t, p, 0, 0, pt, (setRatio ? 2 : 1), null, false, pr, b, e); e += ""; //ensures it's a string if (clrs && _colorExp.test(e + b)) { //if colors are found, normalize the formatting to rgba() or hsla(). e = [b, e]; CSSPlugin.colorStringFilter(e); b = e[0]; e = e[1]; } var ba = b.split(", ").join(",").split(" "), //beginning array ea = e.split(", ").join(",").split(" "), //ending array l = ba.length, autoRound = (_autoRound !== false), i, xi, ni, bv, ev, bnums, enums, bn, hasAlpha, temp, cv, str, useHSL; if (e.indexOf(",") !== -1 || b.indexOf(",") !== -1) { ba = ba.join(" ").replace(_commasOutsideParenExp, ", ").split(" "); ea = ea.join(" ").replace(_commasOutsideParenExp, ", ").split(" "); l = ba.length; } if (l !== ea.length) { //DEBUG: _log("mismatched formatting detected on " + p + " (" + b + " vs " + e + ")"); ba = (dflt || "").split(" "); l = ba.length; } pt.plugin = plugin; pt.setRatio = setRatio; _colorExp.lastIndex = 0; for (i = 0; i < l; i++) { bv = ba[i]; ev = ea[i]; bn = parseFloat(bv); //if the value begins with a number (most common). It's fine if it has a suffix like px if (bn || bn === 0) { pt.appendXtra("", bn, _parseChange(ev, bn), ev.replace(_relNumExp, ""), (autoRound && ev.indexOf("px") !== -1), true); //if the value is a color } else if (clrs && _colorExp.test(bv)) { str = ev.indexOf(")") + 1; str = ")" + (str ? ev.substr(str) : ""); //if there's a comma or ) at the end, retain it. useHSL = (ev.indexOf("hsl") !== -1 && _supportsOpacity); bv = _parseColor(bv, useHSL); ev = _parseColor(ev, useHSL); hasAlpha = (bv.length + ev.length > 6); if (hasAlpha && !_supportsOpacity && ev[3] === 0) { //older versions of IE don't support rgba(), so if the destination alpha is 0, just use "transparent" for the end color pt["xs" + pt.l] += pt.l ? " transparent" : "transparent"; pt.e = pt.e.split(ea[i]).join("transparent"); } else { if (!_supportsOpacity) { //old versions of IE don't support rgba(). hasAlpha = false; } if (useHSL) { pt.appendXtra((hasAlpha ? "hsla(" : "hsl("), bv[0], _parseChange(ev[0], bv[0]), ",", false, true) .appendXtra("", bv[1], _parseChange(ev[1], bv[1]), "%,", false) .appendXtra("", bv[2], _parseChange(ev[2], bv[2]), (hasAlpha ? "%," : "%" + str), false); } else { pt.appendXtra((hasAlpha ? "rgba(" : "rgb("), bv[0], ev[0] - bv[0], ",", true, true) .appendXtra("", bv[1], ev[1] - bv[1], ",", true) .appendXtra("", bv[2], ev[2] - bv[2], (hasAlpha ? "," : str), true); } if (hasAlpha) { bv = (bv.length < 4) ? 1 : bv[3]; pt.appendXtra("", bv, ((ev.length < 4) ? 1 : ev[3]) - bv, str, false); } } _colorExp.lastIndex = 0; //otherwise the test() on the RegExp could move the lastIndex and taint future results. } else { bnums = bv.match(_numExp); //gets each group of numbers in the beginning value string and drops them into an array //if no number is found, treat it as a non-tweening value and just append the string to the current xs. if (!bnums) { pt["xs" + pt.l] += (pt.l || pt["xs" + pt.l]) ? " " + ev : ev; //loop through all the numbers that are found and construct the extra values on the pt. } else { enums = ev.match(_relNumExp); //get each group of numbers in the end value string and drop them into an array. We allow relative values too, like +=50 or -=.5 if (!enums || enums.length !== bnums.length) { //DEBUG: _log("mismatched formatting detected on " + p + " (" + b + " vs " + e + ")"); return pt; } ni = 0; for (xi = 0; xi < bnums.length; xi++) { cv = bnums[xi]; temp = bv.indexOf(cv, ni); pt.appendXtra(bv.substr(ni, temp - ni), Number(cv), _parseChange(enums[xi], cv), "", (autoRound && bv.substr(temp + cv.length, 2) === "px"), (xi === 0)); ni = temp + cv.length; } pt["xs" + pt.l] += bv.substr(ni); } } } //if there are relative values ("+=" or "-=" prefix), we need to adjust the ending value to eliminate the prefixes and combine the values properly. if (e.indexOf("=") !== -1) if (pt.data) { str = pt.xs0 + pt.data.s; for (i = 1; i < pt.l; i++) { str += pt["xs" + i] + pt.data["xn" + i]; } pt.e = str + pt["xs" + i]; } if (!pt.l) { pt.type = -1; pt.xs0 = pt.e; } return pt.xfirst || pt; }, i = 9; p = CSSPropTween.prototype; p.l = p.pr = 0; //length (number of extra properties like xn1, xn2, xn3, etc. while (--i > 0) { p["xn" + i] = 0; p["xs" + i] = ""; } p.xs0 = ""; p._next = p._prev = p.xfirst = p.data = p.plugin = p.setRatio = p.rxp = null; /** * Appends and extra tweening value to a CSSPropTween and automatically manages any prefix and suffix strings. The first extra value is stored in the s and c of the main CSSPropTween instance, but thereafter any extras are stored in the xn1, xn2, xn3, etc. The prefixes and suffixes are stored in the xs0, xs1, xs2, etc. properties. For example, if I walk through a clip value like "rect(10px, 5px, 0px, 20px)", the values would be stored like this: * xs0:"rect(", s:10, xs1:"px, ", xn1:5, xs2:"px, ", xn2:0, xs3:"px, ", xn3:20, xn4:"px)" * And they'd all get joined together when the CSSPlugin renders (in the setRatio() method). * @param {string=} pfx Prefix (if any) * @param {!number} s Starting value * @param {!number} c Change in numeric value over the course of the entire tween. For example, if the start is 5 and the end is 100, the change would be 95. * @param {string=} sfx Suffix (if any) * @param {boolean=} r Round (if true). * @param {boolean=} pad If true, this extra value should be separated by the previous one by a space. If there is no previous extra and pad is true, it will automatically drop the space. * @return {CSSPropTween} returns itself so that multiple methods can be chained together. */ p.appendXtra = function(pfx, s, c, sfx, r, pad) { var pt = this, l = pt.l; pt["xs" + l] += (pad && (l || pt["xs" + l])) ? " " + pfx : pfx || ""; if (!c) if (l !== 0 && !pt.plugin) { //typically we'll combine non-changing values right into the xs to optimize performance, but we don't combine them when there's a plugin that will be tweening the values because it may depend on the values being split apart, like for a bezier, if a value doesn't change between the first and second iteration but then it does on the 3rd, we'll run into trouble because there's no xn slot for that value! pt["xs" + l] += s + (sfx || ""); return pt; } pt.l++; pt.type = pt.setRatio ? 2 : 1; pt["xs" + pt.l] = sfx || ""; if (l > 0) { pt.data["xn" + l] = s + c; pt.rxp["xn" + l] = r; //round extra property (we need to tap into this in the _parseToProxy() method) pt["xn" + l] = s; if (!pt.plugin) { pt.xfirst = new CSSPropTween(pt, "xn" + l, s, c, pt.xfirst || pt, 0, pt.n, r, pt.pr); pt.xfirst.xs0 = 0; //just to ensure that the property stays numeric which helps modern browsers speed up processing. Remember, in the setRatio() method, we do pt.t[pt.p] = val + pt.xs0 so if pt.xs0 is "" (the default), it'll cast the end value as a string. When a property is a number sometimes and a string sometimes, it prevents the compiler from locking in the data type, slowing things down slightly. } return pt; } pt.data = {s:s + c}; pt.rxp = {}; pt.s = s; pt.c = c; pt.r = r; return pt; }; /** * @constructor A SpecialProp is basically a css property that needs to be treated in a non-standard way, like if it may contain a complex value like boxShadow:"5px 10px 15px rgb(255, 102, 51)" or if it is associated with another plugin like ThrowPropsPlugin or BezierPlugin. Every SpecialProp is associated with a particular property name like "boxShadow" or "throwProps" or "bezier" and it will intercept those values in the vars object that's passed to the CSSPlugin and handle them accordingly. * @param {!string} p Property name (like "boxShadow" or "throwProps") * @param {Object=} options An object containing any of the following configuration options: * - defaultValue: the default value * - parser: A function that should be called when the associated property name is found in the vars. This function should return a CSSPropTween instance and it should ensure that it is properly inserted into the linked list. It will receive 4 paramters: 1) The target, 2) The value defined in the vars, 3) The CSSPlugin instance (whose _firstPT should be used for the linked list), and 4) A computed style object if one was calculated (this is a speed optimization that allows retrieval of starting values quicker) * - formatter: a function that formats any value received for this special property (for example, boxShadow could take "5px 5px red" and format it to "5px 5px 0px 0px red" so that both the beginning and ending values have a common order and quantity of values.) * - prefix: if true, we'll determine whether or not this property requires a vendor prefix (like Webkit or Moz or ms or O) * - color: set this to true if the value for this SpecialProp may contain color-related values like rgb(), rgba(), etc. * - priority: priority in the linked list order. Higher priority SpecialProps will be updated before lower priority ones. The default priority is 0. * - multi: if true, the formatter should accommodate a comma-delimited list of values, like boxShadow could have multiple boxShadows listed out. * - collapsible: if true, the formatter should treat the value like it's a top/right/bottom/left value that could be collapsed, like "5px" would apply to all, "5px, 10px" would use 5px for top/bottom and 10px for right/left, etc. * - keyword: a special keyword that can [optionally] be found inside the value (like "inset" for boxShadow). This allows us to validate beginning/ending values to make sure they match (if the keyword is found in one, it'll be added to the other for consistency by default). */ var SpecialProp = function(p, options) { options = options || {}; this.p = options.prefix ? _checkPropPrefix(p) || p : p; _specialProps[p] = _specialProps[this.p] = this; this.format = options.formatter || _getFormatter(options.defaultValue, options.color, options.collapsible, options.multi); if (options.parser) { this.parse = options.parser; } this.clrs = options.color; this.multi = options.multi; this.keyword = options.keyword; this.dflt = options.defaultValue; this.pr = options.priority || 0; }, //shortcut for creating a new SpecialProp that can accept multiple properties as a comma-delimited list (helps minification). dflt can be an array for multiple values (we don't do a comma-delimited list because the default value may contain commas, like rect(0px,0px,0px,0px)). We attach this method to the SpecialProp class/object instead of using a private _createSpecialProp() method so that we can tap into it externally if necessary, like from another plugin. _registerComplexSpecialProp = _internals._registerComplexSpecialProp = function(p, options, defaults) { if (typeof(options) !== "object") { options = {parser:defaults}; //to make backwards compatible with older versions of BezierPlugin and ThrowPropsPlugin } var a = p.split(","), d = options.defaultValue, i, temp; defaults = defaults || [d]; for (i = 0; i < a.length; i++) { options.prefix = (i === 0 && options.prefix); options.defaultValue = defaults[i] || d; temp = new SpecialProp(a[i], options); } }, //creates a placeholder special prop for a plugin so that the property gets caught the first time a tween of it is attempted, and at that time it makes the plugin register itself, thus taking over for all future tweens of that property. This allows us to not mandate that things load in a particular order and it also allows us to log() an error that informs the user when they attempt to tween an external plugin-related property without loading its .js file. _registerPluginProp = _internals._registerPluginProp = function(p) { if (!_specialProps[p]) { var pluginName = p.charAt(0).toUpperCase() + p.substr(1) + "Plugin"; _registerComplexSpecialProp(p, {parser:function(t, e, p, cssp, pt, plugin, vars) { var pluginClass = _globals.com.greensock.plugins[pluginName]; if (!pluginClass) { _log("Error: " + pluginName + " js file not loaded."); return pt; } pluginClass._cssRegister(); return _specialProps[p].parse(t, e, p, cssp, pt, plugin, vars); }}); } }; p = SpecialProp.prototype; /** * Alias for _parseComplex() that automatically plugs in certain values for this SpecialProp, like its property name, whether or not colors should be sensed, the default value, and priority. It also looks for any keyword that the SpecialProp defines (like "inset" for boxShadow) and ensures that the beginning and ending values have the same number of values for SpecialProps where multi is true (like boxShadow and textShadow can have a comma-delimited list) * @param {!Object} t target element * @param {(string|number|object)} b beginning value * @param {(string|number|object)} e ending (destination) value * @param {CSSPropTween=} pt next CSSPropTween in the linked list * @param {TweenPlugin=} plugin If another plugin will be tweening the complex value, that TweenPlugin instance goes here. * @param {function=} setRatio If a custom setRatio() method should be used to handle this complex value, that goes here. * @return {CSSPropTween=} First CSSPropTween in the linked list */ p.parseComplex = function(t, b, e, pt, plugin, setRatio) { var kwd = this.keyword, i, ba, ea, l, bi, ei; //if this SpecialProp's value can contain a comma-delimited list of values (like boxShadow or textShadow), we must parse them in a special way, and look for a keyword (like "inset" for boxShadow) and ensure that the beginning and ending BOTH have it if the end defines it as such. We also must ensure that there are an equal number of values specified (we can't tween 1 boxShadow to 3 for example) if (this.multi) if (_commasOutsideParenExp.test(e) || _commasOutsideParenExp.test(b)) { ba = b.replace(_commasOutsideParenExp, "|").split("|"); ea = e.replace(_commasOutsideParenExp, "|").split("|"); } else if (kwd) { ba = [b]; ea = [e]; } if (ea) { l = (ea.length > ba.length) ? ea.length : ba.length; for (i = 0; i < l; i++) { b = ba[i] = ba[i] || this.dflt; e = ea[i] = ea[i] || this.dflt; if (kwd) { bi = b.indexOf(kwd); ei = e.indexOf(kwd); if (bi !== ei) { if (ei === -1) { //if the keyword isn't in the end value, remove it from the beginning one. ba[i] = ba[i].split(kwd).join(""); } else if (bi === -1) { //if the keyword isn't in the beginning, add it. ba[i] += " " + kwd; } } } } b = ba.join(", "); e = ea.join(", "); } return _parseComplex(t, this.p, b, e, this.clrs, this.dflt, pt, this.pr, plugin, setRatio); }; /** * Accepts a target and end value and spits back a CSSPropTween that has been inserted into the CSSPlugin's linked list and conforms with all the conventions we use internally, like type:-1, 0, 1, or 2, setting up any extra property tweens, priority, etc. For example, if we have a boxShadow SpecialProp and call: * this._firstPT = sp.parse(element, "5px 10px 20px rgb(2550,102,51)", "boxShadow", this); * It should figure out the starting value of the element's boxShadow, compare it to the provided end value and create all the necessary CSSPropTweens of the appropriate types to tween the boxShadow. The CSSPropTween that gets spit back should already be inserted into the linked list (the 4th parameter is the current head, so prepend to that). * @param {!Object} t Target object whose property is being tweened * @param {Object} e End value as provided in the vars object (typically a string, but not always - like a throwProps would be an object). * @param {!string} p Property name * @param {!CSSPlugin} cssp The CSSPlugin instance that should be associated with this tween. * @param {?CSSPropTween} pt The CSSPropTween that is the current head of the linked list (we'll prepend to it) * @param {TweenPlugin=} plugin If a plugin will be used to tween the parsed value, this is the plugin instance. * @param {Object=} vars Original vars object that contains the data for parsing. * @return {CSSPropTween} The first CSSPropTween in the linked list which includes the new one(s) added by the parse() call. */ p.parse = function(t, e, p, cssp, pt, plugin, vars) { return this.parseComplex(t.style, this.format(_getStyle(t, this.p, _cs, false, this.dflt)), this.format(e), pt, plugin); }; /** * Registers a special property that should be intercepted from any "css" objects defined in tweens. This allows you to handle them however you want without CSSPlugin doing it for you. The 2nd parameter should be a function that accepts 3 parameters: * 1) Target object whose property should be tweened (typically a DOM element) * 2) The end/destination value (could be a string, number, object, or whatever you want) * 3) The tween instance (you probably don't need to worry about this, but it can be useful for looking up information like the duration) * * Then, your function should return a function which will be called each time the tween gets rendered, passing a numeric "ratio" parameter to your function that indicates the change factor (usually between 0 and 1). For example: * * CSSPlugin.registerSpecialProp("myCustomProp", function(target, value, tween) { * var start = target.style.width; * return function(ratio) { * target.style.width = (start + value * ratio) + "px"; * console.log("set width to " + target.style.width); * } * }, 0); * * Then, when I do this tween, it will trigger my special property: * * TweenLite.to(element, 1, {css:{myCustomProp:100}}); * * In the example, of course, we're just changing the width, but you can do anything you want. * * @param {!string} name Property name (or comma-delimited list of property names) that should be intercepted and handled by your function. For example, if I define "myCustomProp", then it would handle that portion of the following tween: TweenLite.to(element, 1, {css:{myCustomProp:100}}) * @param {!function(Object, Object, Object, string):function(number)} onInitTween The function that will be called when a tween of this special property is performed. The function will receive 4 parameters: 1) Target object that should be tweened, 2) Value that was passed to the tween, 3) The tween instance itself (rarely used), and 4) The property name that's being tweened. Your function should return a function that should be called on every update of the tween. That function will receive a single parameter that is a "change factor" value (typically between 0 and 1) indicating the amount of change as a ratio. You can use this to determine how to set the values appropriately in your function. * @param {number=} priority Priority that helps the engine determine the order in which to set the properties (default: 0). Higher priority properties will be updated before lower priority ones. */ CSSPlugin.registerSpecialProp = function(name, onInitTween, priority) { _registerComplexSpecialProp(name, {parser:function(t, e, p, cssp, pt, plugin, vars) { var rv = new CSSPropTween(t, p, 0, 0, pt, 2, p, false, priority); rv.plugin = plugin; rv.setRatio = onInitTween(t, e, cssp._tween, p); return rv; }, priority:priority}); }; //transform-related methods and properties CSSPlugin.useSVGTransformAttr = true; //Safari and Firefox both have some rendering bugs when applying CSS transforms to SVG elements, so default to using the "transform" attribute instead (users can override this). var _transformProps = ("scaleX,scaleY,scaleZ,x,y,z,skewX,skewY,rotation,rotationX,rotationY,perspective,xPercent,yPercent").split(","), _transformProp = _checkPropPrefix("transform"), //the Javascript (camelCase) transform property, like msTransform, WebkitTransform, MozTransform, or OTransform. _transformPropCSS = _prefixCSS + "transform", _transformOriginProp = _checkPropPrefix("transformOrigin"), _supports3D = (_checkPropPrefix("perspective") !== null), Transform = _internals.Transform = function() { this.perspective = parseFloat(CSSPlugin.defaultTransformPerspective) || 0; this.force3D = (CSSPlugin.defaultForce3D === false || !_supports3D) ? false : CSSPlugin.defaultForce3D || "auto"; }, _SVGElement = _gsScope.SVGElement, _useSVGTransformAttr, //Some browsers (like Firefox and IE) don't honor transform-origin properly in SVG elements, so we need to manually adjust the matrix accordingly. We feature detect here rather than always doing the conversion for certain browsers because they may fix the problem at some point in the future. _createSVG = function(type, container, attributes) { var element = _doc.createElementNS("http://www.w3.org/2000/svg", type), reg = /([a-z])([A-Z])/g, p; for (p in attributes) { element.setAttributeNS(null, p.replace(reg, "$1-$2").toLowerCase(), attributes[p]); } container.appendChild(element); return element; }, _docElement = _doc.documentElement || {}, _forceSVGTransformAttr = (function() { //IE and Android stock don't support CSS transforms on SVG elements, so we must write them to the "transform" attribute. We populate this variable in the _parseTransform() method, and only if/when we come across an SVG element var force = _ieVers || (/Android/i.test(_agent) && !_gsScope.chrome), svg, rect, width; if (_doc.createElementNS && !force) { //IE8 and earlier doesn't support SVG anyway svg = _createSVG("svg", _docElement); rect = _createSVG("rect", svg, {width:100, height:50, x:100}); width = rect.getBoundingClientRect().width; rect.style[_transformOriginProp] = "50% 50%"; rect.style[_transformProp] = "scaleX(0.5)"; force = (width === rect.getBoundingClientRect().width && !(_isFirefox && _supports3D)); //note: Firefox fails the test even though it does support CSS transforms in 3D. Since we can't push 3D stuff into the transform attribute, we force Firefox to pass the test here (as long as it does truly support 3D). _docElement.removeChild(svg); } return force; })(), _parseSVGOrigin = function(e, local, decoratee, absolute, smoothOrigin, skipRecord) { var tm = e._gsTransform, m = _getMatrix(e, true), v, x, y, xOrigin, yOrigin, a, b, c, d, tx, ty, determinant, xOriginOld, yOriginOld; if (tm) { xOriginOld = tm.xOrigin; //record the original values before we alter them. yOriginOld = tm.yOrigin; } if (!absolute || (v = absolute.split(" ")).length < 2) { b = e.getBBox(); if (b.x === 0 && b.y === 0 && b.width + b.height === 0) { //some browsers (like Firefox) misreport the bounds if the element has zero width and height (it just assumes it's at x:0, y:0), thus we need to manually grab the position in that case. b = {x: parseFloat(e.hasAttribute("x") ? e.getAttribute("x") : e.hasAttribute("cx") ? e.getAttribute("cx") : 0) || 0, y: parseFloat(e.hasAttribute("y") ? e.getAttribute("y") : e.hasAttribute("cy") ? e.getAttribute("cy") : 0) || 0, width:0, height:0}; } local = _parsePosition(local).split(" "); v = [(local[0].indexOf("%") !== -1 ? parseFloat(local[0]) / 100 * b.width : parseFloat(local[0])) + b.x, (local[1].indexOf("%") !== -1 ? parseFloat(local[1]) / 100 * b.height : parseFloat(local[1])) + b.y]; } decoratee.xOrigin = xOrigin = parseFloat(v[0]); decoratee.yOrigin = yOrigin = parseFloat(v[1]); if (absolute && m !== _identity2DMatrix) { //if svgOrigin is being set, we must invert the matrix and determine where the absolute point is, factoring in the current transforms. Otherwise, the svgOrigin would be based on the element's non-transformed position on the canvas. a = m[0]; b = m[1]; c = m[2]; d = m[3]; tx = m[4]; ty = m[5]; determinant = (a * d - b * c); if (determinant) { //if it's zero (like if scaleX and scaleY are zero), skip it to avoid errors with dividing by zero. x = xOrigin * (d / determinant) + yOrigin * (-c / determinant) + ((c * ty - d * tx) / determinant); y = xOrigin * (-b / determinant) + yOrigin * (a / determinant) - ((a * ty - b * tx) / determinant); xOrigin = decoratee.xOrigin = v[0] = x; yOrigin = decoratee.yOrigin = v[1] = y; } } if (tm) { //avoid jump when transformOrigin is changed - adjust the x/y values accordingly if (skipRecord) { decoratee.xOffset = tm.xOffset; decoratee.yOffset = tm.yOffset; tm = decoratee; } if (smoothOrigin || (smoothOrigin !== false && CSSPlugin.defaultSmoothOrigin !== false)) { x = xOrigin - xOriginOld; y = yOrigin - yOriginOld; //originally, we simply adjusted the x and y values, but that would cause problems if, for example, you created a rotational tween part-way through an x/y tween. Managing the offset in a separate variable gives us ultimate flexibility. //tm.x -= x - (x * m[0] + y * m[2]); //tm.y -= y - (x * m[1] + y * m[3]); tm.xOffset += (x * m[0] + y * m[2]) - x; tm.yOffset += (x * m[1] + y * m[3]) - y; } else { tm.xOffset = tm.yOffset = 0; } } if (!skipRecord) { e.setAttribute("data-svg-origin", v.join(" ")); } }, _getBBoxHack = function(swapIfPossible) { //works around issues in some browsers (like Firefox) that don't correctly report getBBox() on SVG elements inside a element and/or . We try creating an SVG, adding it to the documentElement and toss the element in there so that it's definitely part of the rendering tree, then grab the bbox and if it works, we actually swap out the original getBBox() method for our own that does these extra steps whenever getBBox is needed. This helps ensure that performance is optimal (only do all these extra steps when absolutely necessary...most elements don't need it). var svg = _createElement("svg", this.ownerSVGElement.getAttribute("xmlns") || "http://www.w3.org/2000/svg"), oldParent = this.parentNode, oldSibling = this.nextSibling, oldCSS = this.style.cssText, bbox; _docElement.appendChild(svg); svg.appendChild(this); this.style.display = "block"; if (swapIfPossible) { try { bbox = this.getBBox(); this._originalGetBBox = this.getBBox; this.getBBox = _getBBoxHack; } catch (e) { } } else if (this._originalGetBBox) { bbox = this._originalGetBBox(); } if (oldSibling) { oldParent.insertBefore(this, oldSibling); } else { oldParent.appendChild(this); } _docElement.removeChild(svg); this.style.cssText = oldCSS; return bbox; }, _getBBox = function(e) { try { return e.getBBox(); //Firefox throws errors if you try calling getBBox() on an SVG element that's not rendered (like in a or ). https://bugzilla.mozilla.org/show_bug.cgi?id=612118 } catch (error) { return _getBBoxHack.call(e, true); } }, _isSVG = function(e) { //reports if the element is an SVG on which getBBox() actually works return !!(_SVGElement && e.getCTM && _getBBox(e) && (!e.parentNode || e.ownerSVGElement)); }, _identity2DMatrix = [1,0,0,1,0,0], _getMatrix = function(e, force2D) { var tm = e._gsTransform || new Transform(), rnd = 100000, style = e.style, isDefault, s, m, n, dec, none; if (_transformProp) { s = _getStyle(e, _transformPropCSS, null, true); } else if (e.currentStyle) { //for older versions of IE, we need to interpret the filter portion that is in the format: progid:DXImageTransform.Microsoft.Matrix(M11=6.123233995736766e-17, M12=-1, M21=1, M22=6.123233995736766e-17, sizingMethod='auto expand') Notice that we need to swap b and c compared to a normal matrix. s = e.currentStyle.filter.match(_ieGetMatrixExp); s = (s && s.length === 4) ? [s[0].substr(4), Number(s[2].substr(4)), Number(s[1].substr(4)), s[3].substr(4), (tm.x || 0), (tm.y || 0)].join(",") : ""; } isDefault = (!s || s === "none" || s === "matrix(1, 0, 0, 1, 0, 0)"); if (isDefault && _transformProp && ((none = (_getComputedStyle(e).display === "none")) || !e.parentNode)) { if (none) { //browsers don't report transforms accurately unless the element is in the DOM and has a display value that's not "none". n = style.display; style.display = "block"; } if (!e.parentNode) { dec = 1; //flag _docElement.appendChild(e); } s = _getStyle(e, _transformPropCSS, null, true); isDefault = (!s || s === "none" || s === "matrix(1, 0, 0, 1, 0, 0)"); if (n) { style.display = n; } else if (none) { _removeProp(style, "display"); } if (dec) { _docElement.removeChild(e); } } if (tm.svg || (e.getCTM && _isSVG(e))) { if (isDefault && (style[_transformProp] + "").indexOf("matrix") !== -1) { //some browsers (like Chrome 40) don't correctly report transforms that are applied inline on an SVG element (they don't get included in the computed style), so we double-check here and accept matrix values s = style[_transformProp]; isDefault = 0; } m = e.getAttribute("transform"); if (isDefault && m) { if (m.indexOf("matrix") !== -1) { //just in case there's a "transform" value specified as an attribute instead of CSS style. Accept either a matrix() or simple translate() value though. s = m; isDefault = 0; } else if (m.indexOf("translate") !== -1) { s = "matrix(1,0,0,1," + m.match(/(?:\-|\b)[\d\-\.e]+\b/gi).join(",") + ")"; isDefault = 0; } } } if (isDefault) { return _identity2DMatrix; } //split the matrix values out into an array (m for matrix) m = (s || "").match(_numExp) || []; i = m.length; while (--i > -1) { n = Number(m[i]); m[i] = (dec = n - (n |= 0)) ? ((dec * rnd + (dec < 0 ? -0.5 : 0.5)) | 0) / rnd + n : n; //convert strings to Numbers and round to 5 decimal places to avoid issues with tiny numbers. Roughly 20x faster than Number.toFixed(). We also must make sure to round before dividing so that values like 0.9999999999 become 1 to avoid glitches in browser rendering and interpretation of flipped/rotated 3D matrices. And don't just multiply the number by rnd, floor it, and then divide by rnd because the bitwise operations max out at a 32-bit signed integer, thus it could get clipped at a relatively low value (like 22,000.00000 for example). } return (force2D && m.length > 6) ? [m[0], m[1], m[4], m[5], m[12], m[13]] : m; }, /** * Parses the transform values for an element, returning an object with x, y, z, scaleX, scaleY, scaleZ, rotation, rotationX, rotationY, skewX, and skewY properties. Note: by default (for performance reasons), all skewing is combined into skewX and rotation but skewY still has a place in the transform object so that we can record how much of the skew is attributed to skewX vs skewY. Remember, a skewY of 10 looks the same as a rotation of 10 and skewX of -10. * @param {!Object} t target element * @param {Object=} cs computed style object (optional) * @param {boolean=} rec if true, the transform values will be recorded to the target element's _gsTransform object, like target._gsTransform = {x:0, y:0, z:0, scaleX:1...} * @param {boolean=} parse if true, we'll ignore any _gsTransform values that already exist on the element, and force a reparsing of the css (calculated style) * @return {object} object containing all of the transform properties/values like {x:0, y:0, z:0, scaleX:1...} */ _getTransform = _internals.getTransform = function(t, cs, rec, parse) { if (t._gsTransform && rec && !parse) { return t._gsTransform; //if the element already has a _gsTransform, use that. Note: some browsers don't accurately return the calculated style for the transform (particularly for SVG), so it's almost always safest to just use the values we've already applied rather than re-parsing things. } var tm = rec ? t._gsTransform || new Transform() : new Transform(), invX = (tm.scaleX < 0), //in order to interpret things properly, we need to know if the user applied a negative scaleX previously so that we can adjust the rotation and skewX accordingly. Otherwise, if we always interpret a flipped matrix as affecting scaleY and the user only wants to tween the scaleX on multiple sequential tweens, it would keep the negative scaleY without that being the user's intent. min = 0.00002, rnd = 100000, zOrigin = _supports3D ? parseFloat(_getStyle(t, _transformOriginProp, cs, false, "0 0 0").split(" ")[2]) || tm.zOrigin || 0 : 0, defaultTransformPerspective = parseFloat(CSSPlugin.defaultTransformPerspective) || 0, m, i, scaleX, scaleY, rotation, skewX; tm.svg = !!(t.getCTM && _isSVG(t)); if (tm.svg) { _parseSVGOrigin(t, _getStyle(t, _transformOriginProp, cs, false, "50% 50%") + "", tm, t.getAttribute("data-svg-origin")); _useSVGTransformAttr = CSSPlugin.useSVGTransformAttr || _forceSVGTransformAttr; } m = _getMatrix(t); if (m !== _identity2DMatrix) { if (m.length === 16) { //we'll only look at these position-related 6 variables first because if x/y/z all match, it's relatively safe to assume we don't need to re-parse everything which risks losing important rotational information (like rotationX:180 plus rotationY:180 would look the same as rotation:180 - there's no way to know for sure which direction was taken based solely on the matrix3d() values) var a11 = m[0], a21 = m[1], a31 = m[2], a41 = m[3], a12 = m[4], a22 = m[5], a32 = m[6], a42 = m[7], a13 = m[8], a23 = m[9], a33 = m[10], a14 = m[12], a24 = m[13], a34 = m[14], a43 = m[11], angle = Math.atan2(a32, a33), t1, t2, t3, t4, cos, sin; //we manually compensate for non-zero z component of transformOrigin to work around bugs in Safari if (tm.zOrigin) { a34 = -tm.zOrigin; a14 = a13*a34-m[12]; a24 = a23*a34-m[13]; a34 = a33*a34+tm.zOrigin-m[14]; } tm.rotationX = angle * _RAD2DEG; //rotationX if (angle) { cos = Math.cos(-angle); sin = Math.sin(-angle); t1 = a12*cos+a13*sin; t2 = a22*cos+a23*sin; t3 = a32*cos+a33*sin; a13 = a12*-sin+a13*cos; a23 = a22*-sin+a23*cos; a33 = a32*-sin+a33*cos; a43 = a42*-sin+a43*cos; a12 = t1; a22 = t2; a32 = t3; } //rotationY angle = Math.atan2(-a31, a33); tm.rotationY = angle * _RAD2DEG; if (angle) { cos = Math.cos(-angle); sin = Math.sin(-angle); t1 = a11*cos-a13*sin; t2 = a21*cos-a23*sin; t3 = a31*cos-a33*sin; a23 = a21*sin+a23*cos; a33 = a31*sin+a33*cos; a43 = a41*sin+a43*cos; a11 = t1; a21 = t2; a31 = t3; } //rotationZ angle = Math.atan2(a21, a11); tm.rotation = angle * _RAD2DEG; if (angle) { cos = Math.cos(-angle); sin = Math.sin(-angle); a11 = a11*cos+a12*sin; t2 = a21*cos+a22*sin; a22 = a21*-sin+a22*cos; a32 = a31*-sin+a32*cos; a21 = t2; } if (tm.rotationX && Math.abs(tm.rotationX) + Math.abs(tm.rotation) > 359.9) { //when rotationY is set, it will often be parsed as 180 degrees different than it should be, and rotationX and rotation both being 180 (it looks the same), so we adjust for that here. tm.rotationX = tm.rotation = 0; tm.rotationY = 180 - tm.rotationY; } tm.scaleX = ((Math.sqrt(a11 * a11 + a21 * a21) * rnd + 0.5) | 0) / rnd; tm.scaleY = ((Math.sqrt(a22 * a22 + a23 * a23) * rnd + 0.5) | 0) / rnd; tm.scaleZ = ((Math.sqrt(a32 * a32 + a33 * a33) * rnd + 0.5) | 0) / rnd; if (tm.rotationX || tm.rotationY) { tm.skewX = 0; } else { tm.skewX = (a12 || a22) ? Math.atan2(a12, a22) * _RAD2DEG + tm.rotation : tm.skewX || 0; if (Math.abs(tm.skewX) > 90 && Math.abs(tm.skewX) < 270) { if (invX) { tm.scaleX *= -1; tm.skewX += (tm.rotation <= 0) ? 180 : -180; tm.rotation += (tm.rotation <= 0) ? 180 : -180; } else { tm.scaleY *= -1; tm.skewX += (tm.skewX <= 0) ? 180 : -180; } } } tm.perspective = a43 ? 1 / ((a43 < 0) ? -a43 : a43) : 0; tm.x = a14; tm.y = a24; tm.z = a34; if (tm.svg) { tm.x -= tm.xOrigin - (tm.xOrigin * a11 - tm.yOrigin * a12); tm.y -= tm.yOrigin - (tm.yOrigin * a21 - tm.xOrigin * a22); } } else if ((!_supports3D || parse || !m.length || tm.x !== m[4] || tm.y !== m[5] || (!tm.rotationX && !tm.rotationY))) { //sometimes a 6-element matrix is returned even when we performed 3D transforms, like if rotationX and rotationY are 180. In cases like this, we still need to honor the 3D transforms. If we just rely on the 2D info, it could affect how the data is interpreted, like scaleY might get set to -1 or rotation could get offset by 180 degrees. For example, do a TweenLite.to(element, 1, {css:{rotationX:180, rotationY:180}}) and then later, TweenLite.to(element, 1, {css:{rotationX:0}}) and without this conditional logic in place, it'd jump to a state of being unrotated when the 2nd tween starts. Then again, we need to honor the fact that the user COULD alter the transforms outside of CSSPlugin, like by manually applying new css, so we try to sense that by looking at x and y because if those changed, we know the changes were made outside CSSPlugin and we force a reinterpretation of the matrix values. Also, in Webkit browsers, if the element's "display" is "none", its calculated style value will always return empty, so if we've already recorded the values in the _gsTransform object, we'll just rely on those. var k = (m.length >= 6), a = k ? m[0] : 1, b = m[1] || 0, c = m[2] || 0, d = k ? m[3] : 1; tm.x = m[4] || 0; tm.y = m[5] || 0; scaleX = Math.sqrt(a * a + b * b); scaleY = Math.sqrt(d * d + c * c); rotation = (a || b) ? Math.atan2(b, a) * _RAD2DEG : tm.rotation || 0; //note: if scaleX is 0, we cannot accurately measure rotation. Same for skewX with a scaleY of 0. Therefore, we default to the previously recorded value (or zero if that doesn't exist). skewX = (c || d) ? Math.atan2(c, d) * _RAD2DEG + rotation : tm.skewX || 0; if (Math.abs(skewX) > 90 && Math.abs(skewX) < 270) { if (invX) { scaleX *= -1; skewX += (rotation <= 0) ? 180 : -180; rotation += (rotation <= 0) ? 180 : -180; } else { scaleY *= -1; skewX += (skewX <= 0) ? 180 : -180; } } tm.scaleX = scaleX; tm.scaleY = scaleY; tm.rotation = rotation; tm.skewX = skewX; if (_supports3D) { tm.rotationX = tm.rotationY = tm.z = 0; tm.perspective = defaultTransformPerspective; tm.scaleZ = 1; } if (tm.svg) { tm.x -= tm.xOrigin - (tm.xOrigin * a + tm.yOrigin * c); tm.y -= tm.yOrigin - (tm.xOrigin * b + tm.yOrigin * d); } } tm.zOrigin = zOrigin; //some browsers have a hard time with very small values like 2.4492935982947064e-16 (notice the "e-" towards the end) and would render the object slightly off. So we round to 0 in these cases. The conditional logic here is faster than calling Math.abs(). Also, browsers tend to render a SLIGHTLY rotated object in a fuzzy way, so we need to snap to exactly 0 when appropriate. for (i in tm) { if (tm[i] < min) if (tm[i] > -min) { tm[i] = 0; } } } //DEBUG: _log("parsed rotation of " + t.getAttribute("id")+": "+(tm.rotationX)+", "+(tm.rotationY)+", "+(tm.rotation)+", scale: "+tm.scaleX+", "+tm.scaleY+", "+tm.scaleZ+", position: "+tm.x+", "+tm.y+", "+tm.z+", perspective: "+tm.perspective+ ", origin: "+ tm.xOrigin+ ","+ tm.yOrigin); if (rec) { t._gsTransform = tm; //record to the object's _gsTransform which we use so that tweens can control individual properties independently (we need all the properties to accurately recompose the matrix in the setRatio() method) if (tm.svg) { //if we're supposed to apply transforms to the SVG element's "transform" attribute, make sure there aren't any CSS transforms applied or they'll override the attribute ones. Also clear the transform attribute if we're using CSS, just to be clean. if (_useSVGTransformAttr && t.style[_transformProp]) { TweenLite.delayedCall(0.001, function(){ //if we apply this right away (before anything has rendered), we risk there being no transforms for a brief moment and it also interferes with adjusting the transformOrigin in a tween with immediateRender:true (it'd try reading the matrix and it wouldn't have the appropriate data in place because we just removed it). _removeProp(t.style, _transformProp); }); } else if (!_useSVGTransformAttr && t.getAttribute("transform")) { TweenLite.delayedCall(0.001, function(){ t.removeAttribute("transform"); }); } } } return tm; }, //for setting 2D transforms in IE6, IE7, and IE8 (must use a "filter" to emulate the behavior of modern day browser transforms) _setIETransformRatio = function(v) { var t = this.data, //refers to the element's _gsTransform object ang = -t.rotation * _DEG2RAD, skew = ang + t.skewX * _DEG2RAD, rnd = 100000, a = ((Math.cos(ang) * t.scaleX * rnd) | 0) / rnd, b = ((Math.sin(ang) * t.scaleX * rnd) | 0) / rnd, c = ((Math.sin(skew) * -t.scaleY * rnd) | 0) / rnd, d = ((Math.cos(skew) * t.scaleY * rnd) | 0) / rnd, style = this.t.style, cs = this.t.currentStyle, filters, val; if (!cs) { return; } val = b; //just for swapping the variables an inverting them (reused "val" to avoid creating another variable in memory). IE's filter matrix uses a non-standard matrix configuration (angle goes the opposite way, and b and c are reversed and inverted) b = -c; c = -val; filters = cs.filter; style.filter = ""; //remove filters so that we can accurately measure offsetWidth/offsetHeight var w = this.t.offsetWidth, h = this.t.offsetHeight, clip = (cs.position !== "absolute"), m = "progid:DXImageTransform.Microsoft.Matrix(M11=" + a + ", M12=" + b + ", M21=" + c + ", M22=" + d, ox = t.x + (w * t.xPercent / 100), oy = t.y + (h * t.yPercent / 100), dx, dy; //if transformOrigin is being used, adjust the offset x and y if (t.ox != null) { dx = ((t.oxp) ? w * t.ox * 0.01 : t.ox) - w / 2; dy = ((t.oyp) ? h * t.oy * 0.01 : t.oy) - h / 2; ox += dx - (dx * a + dy * b); oy += dy - (dx * c + dy * d); } if (!clip) { m += ", sizingMethod='auto expand')"; } else { dx = (w / 2); dy = (h / 2); //translate to ensure that transformations occur around the correct origin (default is center). m += ", Dx=" + (dx - (dx * a + dy * b) + ox) + ", Dy=" + (dy - (dx * c + dy * d) + oy) + ")"; } if (filters.indexOf("DXImageTransform.Microsoft.Matrix(") !== -1) { style.filter = filters.replace(_ieSetMatrixExp, m); } else { style.filter = m + " " + filters; //we must always put the transform/matrix FIRST (before alpha(opacity=xx)) to avoid an IE bug that slices part of the object when rotation is applied with alpha. } //at the end or beginning of the tween, if the matrix is normal (1, 0, 0, 1) and opacity is 100 (or doesn't exist), remove the filter to improve browser performance. if (v === 0 || v === 1) if (a === 1) if (b === 0) if (c === 0) if (d === 1) if (!clip || m.indexOf("Dx=0, Dy=0") !== -1) if (!_opacityExp.test(filters) || parseFloat(RegExp.$1) === 100) if (filters.indexOf("gradient(" && filters.indexOf("Alpha")) === -1) { style.removeAttribute("filter"); } //we must set the margins AFTER applying the filter in order to avoid some bugs in IE8 that could (in rare scenarios) cause them to be ignored intermittently (vibration). if (!clip) { var mult = (_ieVers < 8) ? 1 : -1, //in Internet Explorer 7 and before, the box model is broken, causing the browser to treat the width/height of the actual rotated filtered image as the width/height of the box itself, but Microsoft corrected that in IE8. We must use a negative offset in IE8 on the right/bottom marg, prop, dif; dx = t.ieOffsetX || 0; dy = t.ieOffsetY || 0; t.ieOffsetX = Math.round((w - ((a < 0 ? -a : a) * w + (b < 0 ? -b : b) * h)) / 2 + ox); t.ieOffsetY = Math.round((h - ((d < 0 ? -d : d) * h + (c < 0 ? -c : c) * w)) / 2 + oy); for (i = 0; i < 4; i++) { prop = _margins[i]; marg = cs[prop]; //we need to get the current margin in case it is being tweened separately (we want to respect that tween's changes) val = (marg.indexOf("px") !== -1) ? parseFloat(marg) : _convertToPixels(this.t, prop, parseFloat(marg), marg.replace(_suffixExp, "")) || 0; if (val !== t[prop]) { dif = (i < 2) ? -t.ieOffsetX : -t.ieOffsetY; //if another tween is controlling a margin, we cannot only apply the difference in the ieOffsets, so we essentially zero-out the dx and dy here in that case. We record the margin(s) later so that we can keep comparing them, making this code very flexible. } else { dif = (i < 2) ? dx - t.ieOffsetX : dy - t.ieOffsetY; } style[prop] = (t[prop] = Math.round( val - dif * ((i === 0 || i === 2) ? 1 : mult) )) + "px"; } } }, /* translates a super small decimal to a string WITHOUT scientific notation _safeDecimal = function(n) { var s = (n < 0 ? -n : n) + "", a = s.split("e-"); return (n < 0 ? "-0." : "0.") + new Array(parseInt(a[1], 10) || 0).join("0") + a[0].split(".").join(""); }, */ _setTransformRatio = _internals.set3DTransformRatio = _internals.setTransformRatio = function(v) { var t = this.data, //refers to the element's _gsTransform object style = this.t.style, angle = t.rotation, rotationX = t.rotationX, rotationY = t.rotationY, sx = t.scaleX, sy = t.scaleY, sz = t.scaleZ, x = t.x, y = t.y, z = t.z, isSVG = t.svg, perspective = t.perspective, force3D = t.force3D, skewY = t.skewY, skewX = t.skewX, t1, a11, a12, a13, a21, a22, a23, a31, a32, a33, a41, a42, a43, zOrigin, min, cos, sin, t2, transform, comma, zero, skew, rnd; if (skewY) { //for performance reasons, we combine all skewing into the skewX and rotation values. Remember, a skewY of 10 degrees looks the same as a rotation of 10 degrees plus a skewX of 10 degrees. skewX += skewY; angle += skewY; } //check to see if we should render as 2D (and SVGs must use 2D when _useSVGTransformAttr is true) if (((((v === 1 || v === 0) && force3D === "auto" && (this.tween._totalTime === this.tween._totalDuration || !this.tween._totalTime)) || !force3D) && !z && !perspective && !rotationY && !rotationX && sz === 1) || (_useSVGTransformAttr && isSVG) || !_supports3D) { //on the final render (which could be 0 for a from tween), if there are no 3D aspects, render in 2D to free up memory and improve performance especially on mobile devices. Check the tween's totalTime/totalDuration too in order to make sure it doesn't happen between repeats if it's a repeating tween. //2D if (angle || skewX || isSVG) { angle *= _DEG2RAD; skew = skewX * _DEG2RAD; rnd = 100000; a11 = Math.cos(angle) * sx; a21 = Math.sin(angle) * sx; a12 = Math.sin(angle - skew) * -sy; a22 = Math.cos(angle - skew) * sy; if (skew && t.skewType === "simple") { //by default, we compensate skewing on the other axis to make it look more natural, but you can set the skewType to "simple" to use the uncompensated skewing that CSS does t1 = Math.tan(skew - skewY * _DEG2RAD); t1 = Math.sqrt(1 + t1 * t1); a12 *= t1; a22 *= t1; if (skewY) { t1 = Math.tan(skewY * _DEG2RAD); t1 = Math.sqrt(1 + t1 * t1); a11 *= t1; a21 *= t1; } } if (isSVG) { x += t.xOrigin - (t.xOrigin * a11 + t.yOrigin * a12) + t.xOffset; y += t.yOrigin - (t.xOrigin * a21 + t.yOrigin * a22) + t.yOffset; if (_useSVGTransformAttr && (t.xPercent || t.yPercent)) { //The SVG spec doesn't support percentage-based translation in the "transform" attribute, so we merge it into the matrix to simulate it. min = this.t.getBBox(); x += t.xPercent * 0.01 * min.width; y += t.yPercent * 0.01 * min.height; } min = 0.000001; if (x < min) if (x > -min) { x = 0; } if (y < min) if (y > -min) { y = 0; } } transform = (((a11 * rnd) | 0) / rnd) + "," + (((a21 * rnd) | 0) / rnd) + "," + (((a12 * rnd) | 0) / rnd) + "," + (((a22 * rnd) | 0) / rnd) + "," + x + "," + y + ")"; if (isSVG && _useSVGTransformAttr) { this.t.setAttribute("transform", "matrix(" + transform); } else { //some browsers have a hard time with very small values like 2.4492935982947064e-16 (notice the "e-" towards the end) and would render the object slightly off. So we round to 5 decimal places. style[_transformProp] = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix(" : "matrix(") + transform; } } else { style[_transformProp] = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix(" : "matrix(") + sx + ",0,0," + sy + "," + x + "," + y + ")"; } return; } if (_isFirefox) { //Firefox has a bug (at least in v25) that causes it to render the transparent part of 32-bit PNG images as black when displayed inside an iframe and the 3D scale is very small and doesn't change sufficiently enough between renders (like if you use a Power4.easeInOut to scale from 0 to 1 where the beginning values only change a tiny amount to begin the tween before accelerating). In this case, we force the scale to be 0.00002 instead which is visually the same but works around the Firefox issue. min = 0.0001; if (sx < min && sx > -min) { sx = sz = 0.00002; } if (sy < min && sy > -min) { sy = sz = 0.00002; } if (perspective && !t.z && !t.rotationX && !t.rotationY) { //Firefox has a bug that causes elements to have an odd super-thin, broken/dotted black border on elements that have a perspective set but aren't utilizing 3D space (no rotationX, rotationY, or z). perspective = 0; } } if (angle || skewX) { angle *= _DEG2RAD; cos = a11 = Math.cos(angle); sin = a21 = Math.sin(angle); if (skewX) { angle -= skewX * _DEG2RAD; cos = Math.cos(angle); sin = Math.sin(angle); if (t.skewType === "simple") { //by default, we compensate skewing on the other axis to make it look more natural, but you can set the skewType to "simple" to use the uncompensated skewing that CSS does t1 = Math.tan((skewX - skewY) * _DEG2RAD); t1 = Math.sqrt(1 + t1 * t1); cos *= t1; sin *= t1; if (t.skewY) { t1 = Math.tan(skewY * _DEG2RAD); t1 = Math.sqrt(1 + t1 * t1); a11 *= t1; a21 *= t1; } } } a12 = -sin; a22 = cos; } else if (!rotationY && !rotationX && sz === 1 && !perspective && !isSVG) { //if we're only translating and/or 2D scaling, this is faster... style[_transformProp] = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) translate3d(" : "translate3d(") + x + "px," + y + "px," + z +"px)" + ((sx !== 1 || sy !== 1) ? " scale(" + sx + "," + sy + ")" : ""); return; } else { a11 = a22 = 1; a12 = a21 = 0; } // KEY INDEX AFFECTS // a11 0 rotation, rotationY, scaleX // a21 1 rotation, rotationY, scaleX // a31 2 rotationY, scaleX // a41 3 rotationY, scaleX // a12 4 rotation, skewX, rotationX, scaleY // a22 5 rotation, skewX, rotationX, scaleY // a32 6 rotationX, scaleY // a42 7 rotationX, scaleY // a13 8 rotationY, rotationX, scaleZ // a23 9 rotationY, rotationX, scaleZ // a33 10 rotationY, rotationX, scaleZ // a43 11 rotationY, rotationX, perspective, scaleZ // a14 12 x, zOrigin, svgOrigin // a24 13 y, zOrigin, svgOrigin // a34 14 z, zOrigin // a44 15 // rotation: Math.atan2(a21, a11) // rotationY: Math.atan2(a13, a33) (or Math.atan2(a13, a11)) // rotationX: Math.atan2(a32, a33) a33 = 1; a13 = a23 = a31 = a32 = a41 = a42 = 0; a43 = (perspective) ? -1 / perspective : 0; zOrigin = t.zOrigin; min = 0.000001; //threshold below which browsers use scientific notation which won't work. comma = ","; zero = "0"; angle = rotationY * _DEG2RAD; if (angle) { cos = Math.cos(angle); sin = Math.sin(angle); a31 = -sin; a41 = a43*-sin; a13 = a11*sin; a23 = a21*sin; a33 = cos; a43 *= cos; a11 *= cos; a21 *= cos; } angle = rotationX * _DEG2RAD; if (angle) { cos = Math.cos(angle); sin = Math.sin(angle); t1 = a12*cos+a13*sin; t2 = a22*cos+a23*sin; a32 = a33*sin; a42 = a43*sin; a13 = a12*-sin+a13*cos; a23 = a22*-sin+a23*cos; a33 = a33*cos; a43 = a43*cos; a12 = t1; a22 = t2; } if (sz !== 1) { a13*=sz; a23*=sz; a33*=sz; a43*=sz; } if (sy !== 1) { a12*=sy; a22*=sy; a32*=sy; a42*=sy; } if (sx !== 1) { a11*=sx; a21*=sx; a31*=sx; a41*=sx; } if (zOrigin || isSVG) { if (zOrigin) { x += a13*-zOrigin; y += a23*-zOrigin; z += a33*-zOrigin+zOrigin; } if (isSVG) { //due to bugs in some browsers, we need to manage the transform-origin of SVG manually x += t.xOrigin - (t.xOrigin * a11 + t.yOrigin * a12) + t.xOffset; y += t.yOrigin - (t.xOrigin * a21 + t.yOrigin * a22) + t.yOffset; } if (x < min && x > -min) { x = zero; } if (y < min && y > -min) { y = zero; } if (z < min && z > -min) { z = 0; //don't use string because we calculate perspective later and need the number. } } //optimized way of concatenating all the values into a string. If we do it all in one shot, it's slower because of the way browsers have to create temp strings and the way it affects memory. If we do it piece-by-piece with +=, it's a bit slower too. We found that doing it in these sized chunks works best overall: transform = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix3d(" : "matrix3d("); transform += ((a11 < min && a11 > -min) ? zero : a11) + comma + ((a21 < min && a21 > -min) ? zero : a21) + comma + ((a31 < min && a31 > -min) ? zero : a31); transform += comma + ((a41 < min && a41 > -min) ? zero : a41) + comma + ((a12 < min && a12 > -min) ? zero : a12) + comma + ((a22 < min && a22 > -min) ? zero : a22); if (rotationX || rotationY || sz !== 1) { //performance optimization (often there's no rotationX or rotationY, so we can skip these calculations) transform += comma + ((a32 < min && a32 > -min) ? zero : a32) + comma + ((a42 < min && a42 > -min) ? zero : a42) + comma + ((a13 < min && a13 > -min) ? zero : a13); transform += comma + ((a23 < min && a23 > -min) ? zero : a23) + comma + ((a33 < min && a33 > -min) ? zero : a33) + comma + ((a43 < min && a43 > -min) ? zero : a43) + comma; } else { transform += ",0,0,0,0,1,0,"; } transform += x + comma + y + comma + z + comma + (perspective ? (1 + (-z / perspective)) : 1) + ")"; style[_transformProp] = transform; }; p = Transform.prototype; p.x = p.y = p.z = p.skewX = p.skewY = p.rotation = p.rotationX = p.rotationY = p.zOrigin = p.xPercent = p.yPercent = p.xOffset = p.yOffset = 0; p.scaleX = p.scaleY = p.scaleZ = 1; _registerComplexSpecialProp("transform,scale,scaleX,scaleY,scaleZ,x,y,z,rotation,rotationX,rotationY,rotationZ,skewX,skewY,shortRotation,shortRotationX,shortRotationY,shortRotationZ,transformOrigin,svgOrigin,transformPerspective,directionalRotation,parseTransform,force3D,skewType,xPercent,yPercent,smoothOrigin", {parser:function(t, e, parsingProp, cssp, pt, plugin, vars) { if (cssp._lastParsedTransform === vars) { return pt; } //only need to parse the transform once, and only if the browser supports it. cssp._lastParsedTransform = vars; var scaleFunc = (vars.scale && typeof(vars.scale) === "function") ? vars.scale : 0, //if there's a function-based "scale" value, swap in the resulting numeric value temporarily. Otherwise, if it's called for both scaleX and scaleY independently, they may not match (like if the function uses Math.random()). swapFunc; if (typeof(vars[parsingProp]) === "function") { //whatever property triggers the initial parsing might be a function-based value in which case it already got called in parse(), thus we don't want to call it again in here. The most efficient way to avoid this is to temporarily swap the value directly into the vars object, and then after we do all our parsing in this function, we'll swap it back again. swapFunc = vars[parsingProp]; vars[parsingProp] = e; } if (scaleFunc) { vars.scale = scaleFunc(_index, t); } var originalGSTransform = t._gsTransform, style = t.style, min = 0.000001, i = _transformProps.length, v = vars, endRotations = {}, transformOriginString = "transformOrigin", m1 = _getTransform(t, _cs, true, v.parseTransform), orig = v.transform && ((typeof(v.transform) === "function") ? v.transform(_index, _target) : v.transform), m2, copy, has3D, hasChange, dr, x, y, matrix, p; cssp._transform = m1; if (orig && typeof(orig) === "string" && _transformProp) { //for values like transform:"rotate(60deg) scale(0.5, 0.8)" copy = _tempDiv.style; //don't use the original target because it might be SVG in which case some browsers don't report computed style correctly. copy[_transformProp] = orig; copy.display = "block"; //if display is "none", the browser often refuses to report the transform properties correctly. copy.position = "absolute"; _doc.body.appendChild(_tempDiv); m2 = _getTransform(_tempDiv, null, false); if (m1.svg) { //if it's an SVG element, x/y part of the matrix will be affected by whatever we use as the origin and the offsets, so compensate here... x = m1.xOrigin; y = m1.yOrigin; m2.x -= m1.xOffset; m2.y -= m1.yOffset; if (v.transformOrigin || v.svgOrigin) { //if this tween is altering the origin, we must factor that in here. The actual work of recording the transformOrigin values and setting up the PropTween is done later (still inside this function) so we cannot leave the changes intact here - we only want to update the x/y accordingly. orig = {}; _parseSVGOrigin(t, _parsePosition(v.transformOrigin), orig, v.svgOrigin, v.smoothOrigin, true); x = orig.xOrigin; y = orig.yOrigin; m2.x -= orig.xOffset - m1.xOffset; m2.y -= orig.yOffset - m1.yOffset; } if (x || y) { matrix = _getMatrix(_tempDiv, true); m2.x -= x - (x * matrix[0] + y * matrix[2]); m2.y -= y - (x * matrix[1] + y * matrix[3]); } } _doc.body.removeChild(_tempDiv); if (!m2.perspective) { m2.perspective = m1.perspective; //tweening to no perspective gives very unintuitive results - just keep the same perspective in that case. } if (v.xPercent != null) { m2.xPercent = _parseVal(v.xPercent, m1.xPercent); } if (v.yPercent != null) { m2.yPercent = _parseVal(v.yPercent, m1.yPercent); } } else if (typeof(v) === "object") { //for values like scaleX, scaleY, rotation, x, y, skewX, and skewY or transform:{...} (object) m2 = {scaleX:_parseVal((v.scaleX != null) ? v.scaleX : v.scale, m1.scaleX), scaleY:_parseVal((v.scaleY != null) ? v.scaleY : v.scale, m1.scaleY), scaleZ:_parseVal(v.scaleZ, m1.scaleZ), x:_parseVal(v.x, m1.x), y:_parseVal(v.y, m1.y), z:_parseVal(v.z, m1.z), xPercent:_parseVal(v.xPercent, m1.xPercent), yPercent:_parseVal(v.yPercent, m1.yPercent), perspective:_parseVal(v.transformPerspective, m1.perspective)}; dr = v.directionalRotation; if (dr != null) { if (typeof(dr) === "object") { for (copy in dr) { v[copy] = dr[copy]; } } else { v.rotation = dr; } } if (typeof(v.x) === "string" && v.x.indexOf("%") !== -1) { m2.x = 0; m2.xPercent = _parseVal(v.x, m1.xPercent); } if (typeof(v.y) === "string" && v.y.indexOf("%") !== -1) { m2.y = 0; m2.yPercent = _parseVal(v.y, m1.yPercent); } m2.rotation = _parseAngle(("rotation" in v) ? v.rotation : ("shortRotation" in v) ? v.shortRotation + "_short" : ("rotationZ" in v) ? v.rotationZ : m1.rotation, m1.rotation, "rotation", endRotations); if (_supports3D) { m2.rotationX = _parseAngle(("rotationX" in v) ? v.rotationX : ("shortRotationX" in v) ? v.shortRotationX + "_short" : m1.rotationX || 0, m1.rotationX, "rotationX", endRotations); m2.rotationY = _parseAngle(("rotationY" in v) ? v.rotationY : ("shortRotationY" in v) ? v.shortRotationY + "_short" : m1.rotationY || 0, m1.rotationY, "rotationY", endRotations); } m2.skewX = _parseAngle(v.skewX, m1.skewX); m2.skewY = _parseAngle(v.skewY, m1.skewY); } if (_supports3D && v.force3D != null) { m1.force3D = v.force3D; hasChange = true; } m1.skewType = v.skewType || m1.skewType || CSSPlugin.defaultSkewType; has3D = (m1.force3D || m1.z || m1.rotationX || m1.rotationY || m2.z || m2.rotationX || m2.rotationY || m2.perspective); if (!has3D && v.scale != null) { m2.scaleZ = 1; //no need to tween scaleZ. } while (--i > -1) { p = _transformProps[i]; orig = m2[p] - m1[p]; if (orig > min || orig < -min || v[p] != null || _forcePT[p] != null) { hasChange = true; pt = new CSSPropTween(m1, p, m1[p], orig, pt); if (p in endRotations) { pt.e = endRotations[p]; //directional rotations typically have compensated values during the tween, but we need to make sure they end at exactly what the user requested } pt.xs0 = 0; //ensures the value stays numeric in setRatio() pt.plugin = plugin; cssp._overwriteProps.push(pt.n); } } orig = v.transformOrigin; if (m1.svg && (orig || v.svgOrigin)) { x = m1.xOffset; //when we change the origin, in order to prevent things from jumping we adjust the x/y so we must record those here so that we can create PropTweens for them and flip them at the same time as the origin y = m1.yOffset; _parseSVGOrigin(t, _parsePosition(orig), m2, v.svgOrigin, v.smoothOrigin); pt = _addNonTweeningNumericPT(m1, "xOrigin", (originalGSTransform ? m1 : m2).xOrigin, m2.xOrigin, pt, transformOriginString); //note: if there wasn't a transformOrigin defined yet, just start with the destination one; it's wasteful otherwise, and it causes problems with fromTo() tweens. For example, TweenLite.to("#wheel", 3, {rotation:180, transformOrigin:"50% 50%", delay:1}); TweenLite.fromTo("#wheel", 3, {scale:0.5, transformOrigin:"50% 50%"}, {scale:1, delay:2}); would cause a jump when the from values revert at the beginning of the 2nd tween. pt = _addNonTweeningNumericPT(m1, "yOrigin", (originalGSTransform ? m1 : m2).yOrigin, m2.yOrigin, pt, transformOriginString); if (x !== m1.xOffset || y !== m1.yOffset) { pt = _addNonTweeningNumericPT(m1, "xOffset", (originalGSTransform ? x : m1.xOffset), m1.xOffset, pt, transformOriginString); pt = _addNonTweeningNumericPT(m1, "yOffset", (originalGSTransform ? y : m1.yOffset), m1.yOffset, pt, transformOriginString); } orig = "0px 0px"; //certain browsers (like firefox) completely botch transform-origin, so we must remove it to prevent it from contaminating transforms. We manage it ourselves with xOrigin and yOrigin } if (orig || (_supports3D && has3D && m1.zOrigin)) { //if anything 3D is happening and there's a transformOrigin with a z component that's non-zero, we must ensure that the transformOrigin's z-component is set to 0 so that we can manually do those calculations to get around Safari bugs. Even if the user didn't specifically define a "transformOrigin" in this particular tween (maybe they did it via css directly). if (_transformProp) { hasChange = true; p = _transformOriginProp; orig = (orig || _getStyle(t, p, _cs, false, "50% 50%")) + ""; //cast as string to avoid errors pt = new CSSPropTween(style, p, 0, 0, pt, -1, transformOriginString); pt.b = style[p]; pt.plugin = plugin; if (_supports3D) { copy = m1.zOrigin; orig = orig.split(" "); m1.zOrigin = ((orig.length > 2 && !(copy !== 0 && orig[2] === "0px")) ? parseFloat(orig[2]) : copy) || 0; //Safari doesn't handle the z part of transformOrigin correctly, so we'll manually handle it in the _set3DTransformRatio() method. pt.xs0 = pt.e = orig[0] + " " + (orig[1] || "50%") + " 0px"; //we must define a z value of 0px specifically otherwise iOS 5 Safari will stick with the old one (if one was defined)! pt = new CSSPropTween(m1, "zOrigin", 0, 0, pt, -1, pt.n); //we must create a CSSPropTween for the _gsTransform.zOrigin so that it gets reset properly at the beginning if the tween runs backward (as opposed to just setting m1.zOrigin here) pt.b = copy; pt.xs0 = pt.e = m1.zOrigin; } else { pt.xs0 = pt.e = orig; } //for older versions of IE (6-8), we need to manually calculate things inside the setRatio() function. We record origin x and y (ox and oy) and whether or not the values are percentages (oxp and oyp). } else { _parsePosition(orig + "", m1); } } if (hasChange) { cssp._transformType = (!(m1.svg && _useSVGTransformAttr) && (has3D || this._transformType === 3)) ? 3 : 2; //quicker than calling cssp._enableTransforms(); } if (swapFunc) { vars[parsingProp] = swapFunc; } if (scaleFunc) { vars.scale = scaleFunc; } return pt; }, prefix:true}); _registerComplexSpecialProp("boxShadow", {defaultValue:"0px 0px 0px 0px #999", prefix:true, color:true, multi:true, keyword:"inset"}); _registerComplexSpecialProp("borderRadius", {defaultValue:"0px", parser:function(t, e, p, cssp, pt, plugin) { e = this.format(e); var props = ["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"], style = t.style, ea1, i, es2, bs2, bs, es, bn, en, w, h, esfx, bsfx, rel, hn, vn, em; w = parseFloat(t.offsetWidth); h = parseFloat(t.offsetHeight); ea1 = e.split(" "); for (i = 0; i < props.length; i++) { //if we're dealing with percentages, we must convert things separately for the horizontal and vertical axis! if (this.p.indexOf("border")) { //older browsers used a prefix props[i] = _checkPropPrefix(props[i]); } bs = bs2 = _getStyle(t, props[i], _cs, false, "0px"); if (bs.indexOf(" ") !== -1) { bs2 = bs.split(" "); bs = bs2[0]; bs2 = bs2[1]; } es = es2 = ea1[i]; bn = parseFloat(bs); bsfx = bs.substr((bn + "").length); rel = (es.charAt(1) === "="); if (rel) { en = parseInt(es.charAt(0)+"1", 10); es = es.substr(2); en *= parseFloat(es); esfx = es.substr((en + "").length - (en < 0 ? 1 : 0)) || ""; } else { en = parseFloat(es); esfx = es.substr((en + "").length); } if (esfx === "") { esfx = _suffixMap[p] || bsfx; } if (esfx !== bsfx) { hn = _convertToPixels(t, "borderLeft", bn, bsfx); //horizontal number (we use a bogus "borderLeft" property just because the _convertToPixels() method searches for the keywords "Left", "Right", "Top", and "Bottom" to determine of it's a horizontal or vertical property, and we need "border" in the name so that it knows it should measure relative to the element itself, not its parent. vn = _convertToPixels(t, "borderTop", bn, bsfx); //vertical number if (esfx === "%") { bs = (hn / w * 100) + "%"; bs2 = (vn / h * 100) + "%"; } else if (esfx === "em") { em = _convertToPixels(t, "borderLeft", 1, "em"); bs = (hn / em) + "em"; bs2 = (vn / em) + "em"; } else { bs = hn + "px"; bs2 = vn + "px"; } if (rel) { es = (parseFloat(bs) + en) + esfx; es2 = (parseFloat(bs2) + en) + esfx; } } pt = _parseComplex(style, props[i], bs + " " + bs2, es + " " + es2, false, "0px", pt); } return pt; }, prefix:true, formatter:_getFormatter("0px 0px 0px 0px", false, true)}); _registerComplexSpecialProp("borderBottomLeftRadius,borderBottomRightRadius,borderTopLeftRadius,borderTopRightRadius", {defaultValue:"0px", parser:function(t, e, p, cssp, pt, plugin) { return _parseComplex(t.style, p, this.format(_getStyle(t, p, _cs, false, "0px 0px")), this.format(e), false, "0px", pt); }, prefix:true, formatter:_getFormatter("0px 0px", false, true)}); _registerComplexSpecialProp("backgroundPosition", {defaultValue:"0 0", parser:function(t, e, p, cssp, pt, plugin) { var bp = "background-position", cs = (_cs || _getComputedStyle(t, null)), bs = this.format( ((cs) ? _ieVers ? cs.getPropertyValue(bp + "-x") + " " + cs.getPropertyValue(bp + "-y") : cs.getPropertyValue(bp) : t.currentStyle.backgroundPositionX + " " + t.currentStyle.backgroundPositionY) || "0 0"), //Internet Explorer doesn't report background-position correctly - we must query background-position-x and background-position-y and combine them (even in IE10). Before IE9, we must do the same with the currentStyle object and use camelCase es = this.format(e), ba, ea, i, pct, overlap, src; if ((bs.indexOf("%") !== -1) !== (es.indexOf("%") !== -1) && es.split(",").length < 2) { src = _getStyle(t, "backgroundImage").replace(_urlExp, ""); if (src && src !== "none") { ba = bs.split(" "); ea = es.split(" "); _tempImg.setAttribute("src", src); //set the temp IMG's src to the background-image so that we can measure its width/height i = 2; while (--i > -1) { bs = ba[i]; pct = (bs.indexOf("%") !== -1); if (pct !== (ea[i].indexOf("%") !== -1)) { overlap = (i === 0) ? t.offsetWidth - _tempImg.width : t.offsetHeight - _tempImg.height; ba[i] = pct ? (parseFloat(bs) / 100 * overlap) + "px" : (parseFloat(bs) / overlap * 100) + "%"; } } bs = ba.join(" "); } } return this.parseComplex(t.style, bs, es, pt, plugin); }, formatter:_parsePosition}); _registerComplexSpecialProp("backgroundSize", {defaultValue:"0 0", formatter:function(v) { v += ""; //ensure it's a string return _parsePosition(v.indexOf(" ") === -1 ? v + " " + v : v); //if set to something like "100% 100%", Safari typically reports the computed style as just "100%" (no 2nd value), but we should ensure that there are two values, so copy the first one. Otherwise, it'd be interpreted as "100% 0" (wrong). }}); _registerComplexSpecialProp("perspective", {defaultValue:"0px", prefix:true}); _registerComplexSpecialProp("perspectiveOrigin", {defaultValue:"50% 50%", prefix:true}); _registerComplexSpecialProp("transformStyle", {prefix:true}); _registerComplexSpecialProp("backfaceVisibility", {prefix:true}); _registerComplexSpecialProp("userSelect", {prefix:true}); _registerComplexSpecialProp("margin", {parser:_getEdgeParser("marginTop,marginRight,marginBottom,marginLeft")}); _registerComplexSpecialProp("padding", {parser:_getEdgeParser("paddingTop,paddingRight,paddingBottom,paddingLeft")}); _registerComplexSpecialProp("clip", {defaultValue:"rect(0px,0px,0px,0px)", parser:function(t, e, p, cssp, pt, plugin){ var b, cs, delim; if (_ieVers < 9) { //IE8 and earlier don't report a "clip" value in the currentStyle - instead, the values are split apart into clipTop, clipRight, clipBottom, and clipLeft. Also, in IE7 and earlier, the values inside rect() are space-delimited, not comma-delimited. cs = t.currentStyle; delim = _ieVers < 8 ? " " : ","; b = "rect(" + cs.clipTop + delim + cs.clipRight + delim + cs.clipBottom + delim + cs.clipLeft + ")"; e = this.format(e).split(",").join(delim); } else { b = this.format(_getStyle(t, this.p, _cs, false, this.dflt)); e = this.format(e); } return this.parseComplex(t.style, b, e, pt, plugin); }}); _registerComplexSpecialProp("textShadow", {defaultValue:"0px 0px 0px #999", color:true, multi:true}); _registerComplexSpecialProp("autoRound,strictUnits", {parser:function(t, e, p, cssp, pt) {return pt;}}); //just so that we can ignore these properties (not tween them) _registerComplexSpecialProp("border", {defaultValue:"0px solid #000", parser:function(t, e, p, cssp, pt, plugin) { var bw = _getStyle(t, "borderTopWidth", _cs, false, "0px"), end = this.format(e).split(" "), esfx = end[0].replace(_suffixExp, ""); if (esfx !== "px") { //if we're animating to a non-px value, we need to convert the beginning width to that unit. bw = (parseFloat(bw) / _convertToPixels(t, "borderTopWidth", 1, esfx)) + esfx; } return this.parseComplex(t.style, this.format(bw + " " + _getStyle(t, "borderTopStyle", _cs, false, "solid") + " " + _getStyle(t, "borderTopColor", _cs, false, "#000")), end.join(" "), pt, plugin); }, color:true, formatter:function(v) { var a = v.split(" "); return a[0] + " " + (a[1] || "solid") + " " + (v.match(_colorExp) || ["#000"])[0]; }}); _registerComplexSpecialProp("borderWidth", {parser:_getEdgeParser("borderTopWidth,borderRightWidth,borderBottomWidth,borderLeftWidth")}); //Firefox doesn't pick up on borderWidth set in style sheets (only inline). _registerComplexSpecialProp("float,cssFloat,styleFloat", {parser:function(t, e, p, cssp, pt, plugin) { var s = t.style, prop = ("cssFloat" in s) ? "cssFloat" : "styleFloat"; return new CSSPropTween(s, prop, 0, 0, pt, -1, p, false, 0, s[prop], e); }}); //opacity-related var _setIEOpacityRatio = function(v) { var t = this.t, //refers to the element's style property filters = t.filter || _getStyle(this.data, "filter") || "", val = (this.s + this.c * v) | 0, skip; if (val === 100) { //for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters. if (filters.indexOf("atrix(") === -1 && filters.indexOf("radient(") === -1 && filters.indexOf("oader(") === -1) { t.removeAttribute("filter"); skip = (!_getStyle(this.data, "filter")); //if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check. } else { t.filter = filters.replace(_alphaFilterExp, ""); skip = true; } } if (!skip) { if (this.xn1) { t.filter = filters = filters || ("alpha(opacity=" + val + ")"); //works around bug in IE7/8 that prevents changes to "visibility" from being applied properly if the filter is changed to a different alpha on the same frame. } if (filters.indexOf("pacity") === -1) { //only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the "O" to avoid case-sensitivity issues if (val !== 0 || !this.xn1) { //bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as "visibility" changes (this.xn1 is 1 if this tween is an "autoAlpha" tween) t.filter = filters + " alpha(opacity=" + val + ")"; //we round the value because otherwise, bugs in IE7/8 can prevent "visibility" changes from being applied properly. } } else { t.filter = filters.replace(_opacityExp, "opacity=" + val); } } }; _registerComplexSpecialProp("opacity,alpha,autoAlpha", {defaultValue:"1", parser:function(t, e, p, cssp, pt, plugin) { var b = parseFloat(_getStyle(t, "opacity", _cs, false, "1")), style = t.style, isAutoAlpha = (p === "autoAlpha"); if (typeof(e) === "string" && e.charAt(1) === "=") { e = ((e.charAt(0) === "-") ? -1 : 1) * parseFloat(e.substr(2)) + b; } if (isAutoAlpha && b === 1 && _getStyle(t, "visibility", _cs) === "hidden" && e !== 0) { //if visibility is initially set to "hidden", we should interpret that as intent to make opacity 0 (a convenience) b = 0; } if (_supportsOpacity) { pt = new CSSPropTween(style, "opacity", b, e - b, pt); } else { pt = new CSSPropTween(style, "opacity", b * 100, (e - b) * 100, pt); pt.xn1 = isAutoAlpha ? 1 : 0; //we need to record whether or not this is an autoAlpha so that in the setRatio(), we know to duplicate the setting of the alpha in order to work around a bug in IE7 and IE8 that prevents changes to "visibility" from taking effect if the filter is changed to a different alpha(opacity) at the same time. Setting it to the SAME value first, then the new value works around the IE7/8 bug. style.zoom = 1; //helps correct an IE issue. pt.type = 2; pt.b = "alpha(opacity=" + pt.s + ")"; pt.e = "alpha(opacity=" + (pt.s + pt.c) + ")"; pt.data = t; pt.plugin = plugin; pt.setRatio = _setIEOpacityRatio; } if (isAutoAlpha) { //we have to create the "visibility" PropTween after the opacity one in the linked list so that they run in the order that works properly in IE8 and earlier pt = new CSSPropTween(style, "visibility", 0, 0, pt, -1, null, false, 0, ((b !== 0) ? "inherit" : "hidden"), ((e === 0) ? "hidden" : "inherit")); pt.xs0 = "inherit"; cssp._overwriteProps.push(pt.n); cssp._overwriteProps.push(p); } return pt; }}); var _removeProp = function(s, p) { if (p) { if (s.removeProperty) { if (p.substr(0,2) === "ms" || p.substr(0,6) === "webkit") { //Microsoft and some Webkit browsers don't conform to the standard of capitalizing the first prefix character, so we adjust so that when we prefix the caps with a dash, it's correct (otherwise it'd be "ms-transform" instead of "-ms-transform" for IE9, for example) p = "-" + p; } s.removeProperty(p.replace(_capsExp, "-$1").toLowerCase()); } else { //note: old versions of IE use "removeAttribute()" instead of "removeProperty()" s.removeAttribute(p); } } }, _setClassNameRatio = function(v) { this.t._gsClassPT = this; if (v === 1 || v === 0) { this.t.setAttribute("class", (v === 0) ? this.b : this.e); var mpt = this.data, //first MiniPropTween s = this.t.style; while (mpt) { if (!mpt.v) { _removeProp(s, mpt.p); } else { s[mpt.p] = mpt.v; } mpt = mpt._next; } if (v === 1 && this.t._gsClassPT === this) { this.t._gsClassPT = null; } } else if (this.t.getAttribute("class") !== this.e) { this.t.setAttribute("class", this.e); } }; _registerComplexSpecialProp("className", {parser:function(t, e, p, cssp, pt, plugin, vars) { var b = t.getAttribute("class") || "", //don't use t.className because it doesn't work consistently on SVG elements; getAttribute("class") and setAttribute("class", value") is more reliable. cssText = t.style.cssText, difData, bs, cnpt, cnptLookup, mpt; pt = cssp._classNamePT = new CSSPropTween(t, p, 0, 0, pt, 2); pt.setRatio = _setClassNameRatio; pt.pr = -11; _hasPriority = true; pt.b = b; bs = _getAllStyles(t, _cs); //if there's a className tween already operating on the target, force it to its end so that the necessary inline styles are removed and the class name is applied before we determine the end state (we don't want inline styles interfering that were there just for class-specific values) cnpt = t._gsClassPT; if (cnpt) { cnptLookup = {}; mpt = cnpt.data; //first MiniPropTween which stores the inline styles - we need to force these so that the inline styles don't contaminate things. Otherwise, there's a small chance that a tween could start and the inline values match the destination values and they never get cleaned. while (mpt) { cnptLookup[mpt.p] = 1; mpt = mpt._next; } cnpt.setRatio(1); } t._gsClassPT = pt; pt.e = (e.charAt(1) !== "=") ? e : b.replace(new RegExp("(?:\\s|^)" + e.substr(2) + "(?![\\w-])"), "") + ((e.charAt(0) === "+") ? " " + e.substr(2) : ""); t.setAttribute("class", pt.e); difData = _cssDif(t, bs, _getAllStyles(t), vars, cnptLookup); t.setAttribute("class", b); pt.data = difData.firstMPT; t.style.cssText = cssText; //we recorded cssText before we swapped classes and ran _getAllStyles() because in cases when a className tween is overwritten, we remove all the related tweening properties from that class change (otherwise class-specific stuff can't override properties we've directly set on the target's style object due to specificity). pt = pt.xfirst = cssp.parse(t, difData.difs, pt, plugin); //we record the CSSPropTween as the xfirst so that we can handle overwriting propertly (if "className" gets overwritten, we must kill all the properties associated with the className part of the tween, so we can loop through from xfirst to the pt itself) return pt; }}); var _setClearPropsRatio = function(v) { if (v === 1 || v === 0) if (this.data._totalTime === this.data._totalDuration && this.data.data !== "isFromStart") { //this.data refers to the tween. Only clear at the END of the tween (remember, from() tweens make the ratio go from 1 to 0, so we can't just check that and if the tween is the zero-duration one that's created internally to render the starting values in a from() tween, ignore that because otherwise, for example, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in). var s = this.t.style, transformParse = _specialProps.transform.parse, a, p, i, clearTransform, transform; if (this.e === "all") { s.cssText = ""; clearTransform = true; } else { a = this.e.split(" ").join("").split(","); i = a.length; while (--i > -1) { p = a[i]; if (_specialProps[p]) { if (_specialProps[p].parse === transformParse) { clearTransform = true; } else { p = (p === "transformOrigin") ? _transformOriginProp : _specialProps[p].p; //ensures that special properties use the proper browser-specific property name, like "scaleX" might be "-webkit-transform" or "boxShadow" might be "-moz-box-shadow" } } _removeProp(s, p); } } if (clearTransform) { _removeProp(s, _transformProp); transform = this.t._gsTransform; if (transform) { if (transform.svg) { this.t.removeAttribute("data-svg-origin"); this.t.removeAttribute("transform"); } delete this.t._gsTransform; } } } }; _registerComplexSpecialProp("clearProps", {parser:function(t, e, p, cssp, pt) { pt = new CSSPropTween(t, p, 0, 0, pt, 2); pt.setRatio = _setClearPropsRatio; pt.e = e; pt.pr = -10; pt.data = cssp._tween; _hasPriority = true; return pt; }}); p = "bezier,throwProps,physicsProps,physics2D".split(","); i = p.length; while (i--) { _registerPluginProp(p[i]); } p = CSSPlugin.prototype; p._firstPT = p._lastParsedTransform = p._transform = null; //gets called when the tween renders for the first time. This kicks everything off, recording start/end values, etc. p._onInitTween = function(target, vars, tween, index) { if (!target.nodeType) { //css is only for dom elements return false; } this._target = _target = target; this._tween = tween; this._vars = vars; _index = index; _autoRound = vars.autoRound; _hasPriority = false; _suffixMap = vars.suffixMap || CSSPlugin.suffixMap; _cs = _getComputedStyle(target, ""); _overwriteProps = this._overwriteProps; var style = target.style, v, pt, pt2, first, last, next, zIndex, tpt, threeD; if (_reqSafariFix) if (style.zIndex === "") { v = _getStyle(target, "zIndex", _cs); if (v === "auto" || v === "") { //corrects a bug in [non-Android] Safari that prevents it from repainting elements in their new positions if they don't have a zIndex set. We also can't just apply this inside _parseTransform() because anything that's moved in any way (like using "left" or "top" instead of transforms like "x" and "y") can be affected, so it is best to ensure that anything that's tweening has a z-index. Setting "WebkitPerspective" to a non-zero value worked too except that on iOS Safari things would flicker randomly. Plus zIndex is less memory-intensive. this._addLazySet(style, "zIndex", 0); } } if (typeof(vars) === "string") { first = style.cssText; v = _getAllStyles(target, _cs); style.cssText = first + ";" + vars; v = _cssDif(target, v, _getAllStyles(target)).difs; if (!_supportsOpacity && _opacityValExp.test(vars)) { v.opacity = parseFloat( RegExp.$1 ); } vars = v; style.cssText = first; } if (vars.className) { //className tweens will combine any differences they find in the css with the vars that are passed in, so {className:"myClass", scale:0.5, left:20} would work. this._firstPT = pt = _specialProps.className.parse(target, vars.className, "className", this, null, null, vars); } else { this._firstPT = pt = this.parse(target, vars, null); } if (this._transformType) { threeD = (this._transformType === 3); if (!_transformProp) { style.zoom = 1; //helps correct an IE issue. } else if (_isSafari) { _reqSafariFix = true; //if zIndex isn't set, iOS Safari doesn't repaint things correctly sometimes (seemingly at random). if (style.zIndex === "") { zIndex = _getStyle(target, "zIndex", _cs); if (zIndex === "auto" || zIndex === "") { this._addLazySet(style, "zIndex", 0); } } //Setting WebkitBackfaceVisibility corrects 3 bugs: // 1) [non-Android] Safari skips rendering changes to "top" and "left" that are made on the same frame/render as a transform update. // 2) iOS Safari sometimes neglects to repaint elements in their new positions. Setting "WebkitPerspective" to a non-zero value worked too except that on iOS Safari things would flicker randomly. // 3) Safari sometimes displayed odd artifacts when tweening the transform (or WebkitTransform) property, like ghosts of the edges of the element remained. Definitely a browser bug. //Note: we allow the user to override the auto-setting by defining WebkitBackfaceVisibility in the vars of the tween. if (_isSafariLT6) { this._addLazySet(style, "WebkitBackfaceVisibility", this._vars.WebkitBackfaceVisibility || (threeD ? "visible" : "hidden")); } } pt2 = pt; while (pt2 && pt2._next) { pt2 = pt2._next; } tpt = new CSSPropTween(target, "transform", 0, 0, null, 2); this._linkCSSP(tpt, null, pt2); tpt.setRatio = _transformProp ? _setTransformRatio : _setIETransformRatio; tpt.data = this._transform || _getTransform(target, _cs, true); tpt.tween = tween; tpt.pr = -1; //ensures that the transforms get applied after the components are updated. _overwriteProps.pop(); //we don't want to force the overwrite of all "transform" tweens of the target - we only care about individual transform properties like scaleX, rotation, etc. The CSSPropTween constructor automatically adds the property to _overwriteProps which is why we need to pop() here. } if (_hasPriority) { //reorders the linked list in order of pr (priority) while (pt) { next = pt._next; pt2 = first; while (pt2 && pt2.pr > pt.pr) { pt2 = pt2._next; } if ((pt._prev = pt2 ? pt2._prev : last)) { pt._prev._next = pt; } else { first = pt; } if ((pt._next = pt2)) { pt2._prev = pt; } else { last = pt; } pt = next; } this._firstPT = first; } return true; }; p.parse = function(target, vars, pt, plugin) { var style = target.style, p, sp, bn, en, bs, es, bsfx, esfx, isStr, rel; for (p in vars) { es = vars[p]; //ending value string if (typeof(es) === "function") { es = es(_index, _target); } sp = _specialProps[p]; //SpecialProp lookup. if (sp) { pt = sp.parse(target, es, p, this, pt, plugin, vars); } else { bs = _getStyle(target, p, _cs) + ""; isStr = (typeof(es) === "string"); if (p === "color" || p === "fill" || p === "stroke" || p.indexOf("Color") !== -1 || (isStr && _rgbhslExp.test(es))) { //Opera uses background: to define color sometimes in addition to backgroundColor: if (!isStr) { es = _parseColor(es); es = ((es.length > 3) ? "rgba(" : "rgb(") + es.join(",") + ")"; } pt = _parseComplex(style, p, bs, es, true, "transparent", pt, 0, plugin); } else if (isStr && _complexExp.test(es)) { pt = _parseComplex(style, p, bs, es, true, null, pt, 0, plugin); } else { bn = parseFloat(bs); bsfx = (bn || bn === 0) ? bs.substr((bn + "").length) : ""; //remember, bs could be non-numeric like "normal" for fontWeight, so we should default to a blank suffix in that case. if (bs === "" || bs === "auto") { if (p === "width" || p === "height") { bn = _getDimension(target, p, _cs); bsfx = "px"; } else if (p === "left" || p === "top") { bn = _calculateOffset(target, p, _cs); bsfx = "px"; } else { bn = (p !== "opacity") ? 0 : 1; bsfx = ""; } } rel = (isStr && es.charAt(1) === "="); if (rel) { en = parseInt(es.charAt(0) + "1", 10); es = es.substr(2); en *= parseFloat(es); esfx = es.replace(_suffixExp, ""); } else { en = parseFloat(es); esfx = isStr ? es.replace(_suffixExp, "") : ""; } if (esfx === "") { esfx = (p in _suffixMap) ? _suffixMap[p] : bsfx; //populate the end suffix, prioritizing the map, then if none is found, use the beginning suffix. } es = (en || en === 0) ? (rel ? en + bn : en) + esfx : vars[p]; //ensures that any += or -= prefixes are taken care of. Record the end value before normalizing the suffix because we always want to end the tween on exactly what they intended even if it doesn't match the beginning value's suffix. //if the beginning/ending suffixes don't match, normalize them... if (bsfx !== esfx) if (esfx !== "") if (en || en === 0) if (bn) { //note: if the beginning value (bn) is 0, we don't need to convert units! bn = _convertToPixels(target, p, bn, bsfx); if (esfx === "%") { bn /= _convertToPixels(target, p, 100, "%") / 100; if (vars.strictUnits !== true) { //some browsers report only "px" values instead of allowing "%" with getComputedStyle(), so we assume that if we're tweening to a %, we should start there too unless strictUnits:true is defined. This approach is particularly useful for responsive designs that use from() tweens. bs = bn + "%"; } } else if (esfx === "em" || esfx === "rem" || esfx === "vw" || esfx === "vh") { bn /= _convertToPixels(target, p, 1, esfx); //otherwise convert to pixels. } else if (esfx !== "px") { en = _convertToPixels(target, p, en, esfx); esfx = "px"; //we don't use bsfx after this, so we don't need to set it to px too. } if (rel) if (en || en === 0) { es = (en + bn) + esfx; //the changes we made affect relative calculations, so adjust the end value here. } } if (rel) { en += bn; } if ((bn || bn === 0) && (en || en === 0)) { //faster than isNaN(). Also, previously we required en !== bn but that doesn't really gain much performance and it prevents _parseToProxy() from working properly if beginning and ending values match but need to get tweened by an external plugin anyway. For example, a bezier tween where the target starts at left:0 and has these points: [{left:50},{left:0}] wouldn't work properly because when parsing the last point, it'd match the first (current) one and a non-tweening CSSPropTween would be recorded when we actually need a normal tween (type:0) so that things get updated during the tween properly. pt = new CSSPropTween(style, p, bn, en - bn, pt, 0, p, (_autoRound !== false && (esfx === "px" || p === "zIndex")), 0, bs, es); pt.xs0 = esfx; //DEBUG: _log("tween "+p+" from "+pt.b+" ("+bn+esfx+") to "+pt.e+" with suffix: "+pt.xs0); } else if (style[p] === undefined || !es && (es + "" === "NaN" || es == null)) { _log("invalid " + p + " tween value: " + vars[p]); } else { pt = new CSSPropTween(style, p, en || bn || 0, 0, pt, -1, p, false, 0, bs, es); pt.xs0 = (es === "none" && (p === "display" || p.indexOf("Style") !== -1)) ? bs : es; //intermediate value should typically be set immediately (end value) except for "display" or things like borderTopStyle, borderBottomStyle, etc. which should use the beginning value during the tween. //DEBUG: _log("non-tweening value "+p+": "+pt.xs0); } } } if (plugin) if (pt && !pt.plugin) { pt.plugin = plugin; } } return pt; }; //gets called every time the tween updates, passing the new ratio (typically a value between 0 and 1, but not always (for example, if an Elastic.easeOut is used, the value can jump above 1 mid-tween). It will always start and 0 and end at 1. p.setRatio = function(v) { var pt = this._firstPT, min = 0.000001, val, str, i; //at the end of the tween, we set the values to exactly what we received in order to make sure non-tweening values (like "position" or "float" or whatever) are set and so that if the beginning/ending suffixes (units) didn't match and we normalized to px, the value that the user passed in is used here. We check to see if the tween is at its beginning in case it's a from() tween in which case the ratio will actually go from 1 to 0 over the course of the tween (backwards). if (v === 1 && (this._tween._time === this._tween._duration || this._tween._time === 0)) { while (pt) { if (pt.type !== 2) { if (pt.r && pt.type !== -1) { val = Math.round(pt.s + pt.c); if (!pt.type) { pt.t[pt.p] = val + pt.xs0; } else if (pt.type === 1) { //complex value (one that typically has multiple numbers inside a string, like "rect(5px,10px,20px,25px)" i = pt.l; str = pt.xs0 + val + pt.xs1; for (i = 1; i < pt.l; i++) { str += pt["xn"+i] + pt["xs"+(i+1)]; } pt.t[pt.p] = str; } } else { pt.t[pt.p] = pt.e; } } else { pt.setRatio(v); } pt = pt._next; } } else if (v || !(this._tween._time === this._tween._duration || this._tween._time === 0) || this._tween._rawPrevTime === -0.000001) { while (pt) { val = pt.c * v + pt.s; if (pt.r) { val = Math.round(val); } else if (val < min) if (val > -min) { val = 0; } if (!pt.type) { pt.t[pt.p] = val + pt.xs0; } else if (pt.type === 1) { //complex value (one that typically has multiple numbers inside a string, like "rect(5px,10px,20px,25px)" i = pt.l; if (i === 2) { pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2; } else if (i === 3) { pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3; } else if (i === 4) { pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3 + pt.xn3 + pt.xs4; } else if (i === 5) { pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3 + pt.xn3 + pt.xs4 + pt.xn4 + pt.xs5; } else { str = pt.xs0 + val + pt.xs1; for (i = 1; i < pt.l; i++) { str += pt["xn"+i] + pt["xs"+(i+1)]; } pt.t[pt.p] = str; } } else if (pt.type === -1) { //non-tweening value pt.t[pt.p] = pt.xs0; } else if (pt.setRatio) { //custom setRatio() for things like SpecialProps, external plugins, etc. pt.setRatio(v); } pt = pt._next; } //if the tween is reversed all the way back to the beginning, we need to restore the original values which may have different units (like % instead of px or em or whatever). } else { while (pt) { if (pt.type !== 2) { pt.t[pt.p] = pt.b; } else { pt.setRatio(v); } pt = pt._next; } } }; /** * @private * Forces rendering of the target's transforms (rotation, scale, etc.) whenever the CSSPlugin's setRatio() is called. * Basically, this tells the CSSPlugin to create a CSSPropTween (type 2) after instantiation that runs last in the linked * list and calls the appropriate (3D or 2D) rendering function. We separate this into its own method so that we can call * it from other plugins like BezierPlugin if, for example, it needs to apply an autoRotation and this CSSPlugin * doesn't have any transform-related properties of its own. You can call this method as many times as you * want and it won't create duplicate CSSPropTweens. * * @param {boolean} threeD if true, it should apply 3D tweens (otherwise, just 2D ones are fine and typically faster) */ p._enableTransforms = function(threeD) { this._transform = this._transform || _getTransform(this._target, _cs, true); //ensures that the element has a _gsTransform property with the appropriate values. this._transformType = (!(this._transform.svg && _useSVGTransformAttr) && (threeD || this._transformType === 3)) ? 3 : 2; }; var lazySet = function(v) { this.t[this.p] = this.e; this.data._linkCSSP(this, this._next, null, true); //we purposefully keep this._next even though it'd make sense to null it, but this is a performance optimization, as this happens during the while (pt) {} loop in setRatio() at the bottom of which it sets pt = pt._next, so if we null it, the linked list will be broken in that loop. }; /** @private Gives us a way to set a value on the first render (and only the first render). **/ p._addLazySet = function(t, p, v) { var pt = this._firstPT = new CSSPropTween(t, p, 0, 0, this._firstPT, 2); pt.e = v; pt.setRatio = lazySet; pt.data = this; }; /** @private **/ p._linkCSSP = function(pt, next, prev, remove) { if (pt) { if (next) { next._prev = pt; } if (pt._next) { pt._next._prev = pt._prev; } if (pt._prev) { pt._prev._next = pt._next; } else if (this._firstPT === pt) { this._firstPT = pt._next; remove = true; //just to prevent resetting this._firstPT 5 lines down in case pt._next is null. (optimized for speed) } if (prev) { prev._next = pt; } else if (!remove && this._firstPT === null) { this._firstPT = pt; } pt._next = next; pt._prev = prev; } return pt; }; p._mod = function(lookup) { var pt = this._firstPT; while (pt) { if (typeof(lookup[pt.p]) === "function" && lookup[pt.p] === Math.round) { //only gets called by RoundPropsPlugin (ModifyPlugin manages all the rendering internally for CSSPlugin properties that need modification). Remember, we handle rounding a bit differently in this plugin for performance reasons, leveraging "r" as an indicator that the value should be rounded internally.. pt.r = 1; } pt = pt._next; } }; //we need to make sure that if alpha or autoAlpha is killed, opacity is too. And autoAlpha affects the "visibility" property. p._kill = function(lookup) { var copy = lookup, pt, p, xfirst; if (lookup.autoAlpha || lookup.alpha) { copy = {}; for (p in lookup) { //copy the lookup so that we're not changing the original which may be passed elsewhere. copy[p] = lookup[p]; } copy.opacity = 1; if (copy.autoAlpha) { copy.visibility = 1; } } if (lookup.className && (pt = this._classNamePT)) { //for className tweens, we need to kill any associated CSSPropTweens too; a linked list starts at the className's "xfirst". xfirst = pt.xfirst; if (xfirst && xfirst._prev) { this._linkCSSP(xfirst._prev, pt._next, xfirst._prev._prev); //break off the prev } else if (xfirst === this._firstPT) { this._firstPT = pt._next; } if (pt._next) { this._linkCSSP(pt._next, pt._next._next, xfirst._prev); } this._classNamePT = null; } pt = this._firstPT; while (pt) { if (pt.plugin && pt.plugin !== p && pt.plugin._kill) { //for plugins that are registered with CSSPlugin, we should notify them of the kill. pt.plugin._kill(lookup); p = pt.plugin; } pt = pt._next; } return TweenPlugin.prototype._kill.call(this, copy); }; //used by cascadeTo() for gathering all the style properties of each child element into an array for comparison. var _getChildStyles = function(e, props, targets) { var children, i, child, type; if (e.slice) { i = e.length; while (--i > -1) { _getChildStyles(e[i], props, targets); } return; } children = e.childNodes; i = children.length; while (--i > -1) { child = children[i]; type = child.type; if (child.style) { props.push(_getAllStyles(child)); if (targets) { targets.push(child); } } if ((type === 1 || type === 9 || type === 11) && child.childNodes.length) { _getChildStyles(child, props, targets); } } }; /** * Typically only useful for className tweens that may affect child elements, this method creates a TweenLite * and then compares the style properties of all the target's child elements at the tween's start and end, and * if any are different, it also creates tweens for those and returns an array containing ALL of the resulting * tweens (so that you can easily add() them to a TimelineLite, for example). The reason this functionality is * wrapped into a separate static method of CSSPlugin instead of being integrated into all regular className tweens * is because it creates entirely new tweens that may have completely different targets than the original tween, * so if they were all lumped into the original tween instance, it would be inconsistent with the rest of the API * and it would create other problems. For example: * - If I create a tween of elementA, that tween instance may suddenly change its target to include 50 other elements (unintuitive if I specifically defined the target I wanted) * - We can't just create new independent tweens because otherwise, what happens if the original/parent tween is reversed or pause or dropped into a TimelineLite for tight control? You'd expect that tween's behavior to affect all the others. * - Analyzing every style property of every child before and after the tween is an expensive operation when there are many children, so this behavior shouldn't be imposed on all className tweens by default, especially since it's probably rare that this extra functionality is needed. * * @param {Object} target object to be tweened * @param {number} Duration in seconds (or frames for frames-based tweens) * @param {Object} Object containing the end values, like {className:"newClass", ease:Linear.easeNone} * @return {Array} An array of TweenLite instances */ CSSPlugin.cascadeTo = function(target, duration, vars) { var tween = TweenLite.to(target, duration, vars), results = [tween], b = [], e = [], targets = [], _reservedProps = TweenLite._internals.reservedProps, i, difs, p, from; target = tween._targets || tween.target; _getChildStyles(target, b, targets); tween.render(duration, true, true); _getChildStyles(target, e); tween.render(0, true, true); tween._enabled(true); i = targets.length; while (--i > -1) { difs = _cssDif(targets[i], b[i], e[i]); if (difs.firstMPT) { difs = difs.difs; for (p in vars) { if (_reservedProps[p]) { difs[p] = vars[p]; } } from = {}; for (p in difs) { from[p] = b[i][p]; } results.push(TweenLite.fromTo(targets[i], duration, from, difs)); } } return results; }; TweenPlugin.activate([CSSPlugin]); return CSSPlugin; }, true); /* * ---------------------------------------------------------------- * RoundPropsPlugin * ---------------------------------------------------------------- */ (function() { var RoundPropsPlugin = _gsScope._gsDefine.plugin({ propName: "roundProps", version: "1.6.0", priority: -1, API: 2, //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. init: function(target, value, tween) { this._tween = tween; return true; } }), _roundLinkedList = function(node) { while (node) { if (!node.f && !node.blob) { node.m = Math.round; } node = node._next; } }, p = RoundPropsPlugin.prototype; p._onInitAllProps = function() { var tween = this._tween, rp = (tween.vars.roundProps.join) ? tween.vars.roundProps : tween.vars.roundProps.split(","), i = rp.length, lookup = {}, rpt = tween._propLookup.roundProps, prop, pt, next; while (--i > -1) { lookup[rp[i]] = Math.round; } i = rp.length; while (--i > -1) { prop = rp[i]; pt = tween._firstPT; while (pt) { next = pt._next; //record here, because it may get removed if (pt.pg) { pt.t._mod(lookup); } else if (pt.n === prop) { if (pt.f === 2 && pt.t) { //a blob (text containing multiple numeric values) _roundLinkedList(pt.t._firstPT); } else { this._add(pt.t, prop, pt.s, pt.c); //remove from linked list if (next) { next._prev = pt._prev; } if (pt._prev) { pt._prev._next = next; } else if (tween._firstPT === pt) { tween._firstPT = next; } pt._next = pt._prev = null; tween._propLookup[prop] = rpt; } } pt = next; } } return false; }; p._add = function(target, p, s, c) { this._addTween(target, p, s, s + c, p, Math.round); this._overwriteProps.push(p); }; }()); /* * ---------------------------------------------------------------- * AttrPlugin * ---------------------------------------------------------------- */ (function() { _gsScope._gsDefine.plugin({ propName: "attr", API: 2, version: "0.6.0", //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. init: function(target, value, tween, index) { var p, end; if (typeof(target.setAttribute) !== "function") { return false; } for (p in value) { end = value[p]; if (typeof(end) === "function") { end = end(index, target); } this._addTween(target, "setAttribute", target.getAttribute(p) + "", end + "", p, false, p); this._overwriteProps.push(p); } return true; } }); }()); /* * ---------------------------------------------------------------- * DirectionalRotationPlugin * ---------------------------------------------------------------- */ _gsScope._gsDefine.plugin({ propName: "directionalRotation", version: "0.3.0", API: 2, //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. init: function(target, value, tween, index) { if (typeof(value) !== "object") { value = {rotation:value}; } this.finals = {}; var cap = (value.useRadians === true) ? Math.PI * 2 : 360, min = 0.000001, p, v, start, end, dif, split; for (p in value) { if (p !== "useRadians") { end = value[p]; if (typeof(end) === "function") { end = end(index, target); } split = (end + "").split("_"); v = split[0]; start = parseFloat( (typeof(target[p]) !== "function") ? target[p] : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ]() ); end = this.finals[p] = (typeof(v) === "string" && v.charAt(1) === "=") ? start + parseInt(v.charAt(0) + "1", 10) * Number(v.substr(2)) : Number(v) || 0; dif = end - start; if (split.length) { v = split.join("_"); if (v.indexOf("short") !== -1) { dif = dif % cap; if (dif !== dif % (cap / 2)) { dif = (dif < 0) ? dif + cap : dif - cap; } } if (v.indexOf("_cw") !== -1 && dif < 0) { dif = ((dif + cap * 9999999999) % cap) - ((dif / cap) | 0) * cap; } else if (v.indexOf("ccw") !== -1 && dif > 0) { dif = ((dif - cap * 9999999999) % cap) - ((dif / cap) | 0) * cap; } } if (dif > min || dif < -min) { this._addTween(target, p, start, start + dif, p); this._overwriteProps.push(p); } } } return true; }, //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.) set: function(ratio) { var pt; if (ratio !== 1) { this._super.setRatio.call(this, ratio); } else { pt = this._firstPT; while (pt) { if (pt.f) { pt.t[pt.p](this.finals[pt.p]); } else { pt.t[pt.p] = this.finals[pt.p]; } pt = pt._next; } } } })._autoCSS = true; /* * ---------------------------------------------------------------- * EasePack * ---------------------------------------------------------------- */ _gsScope._gsDefine("easing.Back", ["easing.Ease"], function(Ease) { var w = (_gsScope.GreenSockGlobals || _gsScope), gs = w.com.greensock, _2PI = Math.PI * 2, _HALF_PI = Math.PI / 2, _class = gs._class, _create = function(n, f) { var C = _class("easing." + n, function(){}, true), p = C.prototype = new Ease(); p.constructor = C; p.getRatio = f; return C; }, _easeReg = Ease.register || function(){}, //put an empty function in place just as a safety measure in case someone loads an OLD version of TweenLite.js where Ease.register doesn't exist. _wrap = function(name, EaseOut, EaseIn, EaseInOut, aliases) { var C = _class("easing."+name, { easeOut:new EaseOut(), easeIn:new EaseIn(), easeInOut:new EaseInOut() }, true); _easeReg(C, name); return C; }, EasePoint = function(time, value, next) { this.t = time; this.v = value; if (next) { this.next = next; next.prev = this; this.c = next.v - value; this.gap = next.t - time; } }, //Back _createBack = function(n, f) { var C = _class("easing." + n, function(overshoot) { this._p1 = (overshoot || overshoot === 0) ? overshoot : 1.70158; this._p2 = this._p1 * 1.525; }, true), p = C.prototype = new Ease(); p.constructor = C; p.getRatio = f; p.config = function(overshoot) { return new C(overshoot); }; return C; }, Back = _wrap("Back", _createBack("BackOut", function(p) { return ((p = p - 1) * p * ((this._p1 + 1) * p + this._p1) + 1); }), _createBack("BackIn", function(p) { return p * p * ((this._p1 + 1) * p - this._p1); }), _createBack("BackInOut", function(p) { return ((p *= 2) < 1) ? 0.5 * p * p * ((this._p2 + 1) * p - this._p2) : 0.5 * ((p -= 2) * p * ((this._p2 + 1) * p + this._p2) + 2); }) ), //SlowMo SlowMo = _class("easing.SlowMo", function(linearRatio, power, yoyoMode) { power = (power || power === 0) ? power : 0.7; if (linearRatio == null) { linearRatio = 0.7; } else if (linearRatio > 1) { linearRatio = 1; } this._p = (linearRatio !== 1) ? power : 0; this._p1 = (1 - linearRatio) / 2; this._p2 = linearRatio; this._p3 = this._p1 + this._p2; this._calcEnd = (yoyoMode === true); }, true), p = SlowMo.prototype = new Ease(), SteppedEase, RoughEase, _createElastic; p.constructor = SlowMo; p.getRatio = function(p) { var r = p + (0.5 - p) * this._p; if (p < this._p1) { return this._calcEnd ? 1 - ((p = 1 - (p / this._p1)) * p) : r - ((p = 1 - (p / this._p1)) * p * p * p * r); } else if (p > this._p3) { return this._calcEnd ? 1 - (p = (p - this._p3) / this._p1) * p : r + ((p - r) * (p = (p - this._p3) / this._p1) * p * p * p); } return this._calcEnd ? 1 : r; }; SlowMo.ease = new SlowMo(0.7, 0.7); p.config = SlowMo.config = function(linearRatio, power, yoyoMode) { return new SlowMo(linearRatio, power, yoyoMode); }; //SteppedEase SteppedEase = _class("easing.SteppedEase", function(steps) { steps = steps || 1; this._p1 = 1 / steps; this._p2 = steps + 1; }, true); p = SteppedEase.prototype = new Ease(); p.constructor = SteppedEase; p.getRatio = function(p) { if (p < 0) { p = 0; } else if (p >= 1) { p = 0.999999999; } return ((this._p2 * p) >> 0) * this._p1; }; p.config = SteppedEase.config = function(steps) { return new SteppedEase(steps); }; //RoughEase RoughEase = _class("easing.RoughEase", function(vars) { vars = vars || {}; var taper = vars.taper || "none", a = [], cnt = 0, points = (vars.points || 20) | 0, i = points, randomize = (vars.randomize !== false), clamp = (vars.clamp === true), template = (vars.template instanceof Ease) ? vars.template : null, strength = (typeof(vars.strength) === "number") ? vars.strength * 0.4 : 0.4, x, y, bump, invX, obj, pnt; while (--i > -1) { x = randomize ? Math.random() : (1 / points) * i; y = template ? template.getRatio(x) : x; if (taper === "none") { bump = strength; } else if (taper === "out") { invX = 1 - x; bump = invX * invX * strength; } else if (taper === "in") { bump = x * x * strength; } else if (x < 0.5) { //"both" (start) invX = x * 2; bump = invX * invX * 0.5 * strength; } else { //"both" (end) invX = (1 - x) * 2; bump = invX * invX * 0.5 * strength; } if (randomize) { y += (Math.random() * bump) - (bump * 0.5); } else if (i % 2) { y += bump * 0.5; } else { y -= bump * 0.5; } if (clamp) { if (y > 1) { y = 1; } else if (y < 0) { y = 0; } } a[cnt++] = {x:x, y:y}; } a.sort(function(a, b) { return a.x - b.x; }); pnt = new EasePoint(1, 1, null); i = points; while (--i > -1) { obj = a[i]; pnt = new EasePoint(obj.x, obj.y, pnt); } this._prev = new EasePoint(0, 0, (pnt.t !== 0) ? pnt : pnt.next); }, true); p = RoughEase.prototype = new Ease(); p.constructor = RoughEase; p.getRatio = function(p) { var pnt = this._prev; if (p > pnt.t) { while (pnt.next && p >= pnt.t) { pnt = pnt.next; } pnt = pnt.prev; } else { while (pnt.prev && p <= pnt.t) { pnt = pnt.prev; } } this._prev = pnt; return (pnt.v + ((p - pnt.t) / pnt.gap) * pnt.c); }; p.config = function(vars) { return new RoughEase(vars); }; RoughEase.ease = new RoughEase(); //Bounce _wrap("Bounce", _create("BounceOut", function(p) { if (p < 1 / 2.75) { return 7.5625 * p * p; } else if (p < 2 / 2.75) { return 7.5625 * (p -= 1.5 / 2.75) * p + 0.75; } else if (p < 2.5 / 2.75) { return 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375; } return 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375; }), _create("BounceIn", function(p) { if ((p = 1 - p) < 1 / 2.75) { return 1 - (7.5625 * p * p); } else if (p < 2 / 2.75) { return 1 - (7.5625 * (p -= 1.5 / 2.75) * p + 0.75); } else if (p < 2.5 / 2.75) { return 1 - (7.5625 * (p -= 2.25 / 2.75) * p + 0.9375); } return 1 - (7.5625 * (p -= 2.625 / 2.75) * p + 0.984375); }), _create("BounceInOut", function(p) { var invert = (p < 0.5); if (invert) { p = 1 - (p * 2); } else { p = (p * 2) - 1; } if (p < 1 / 2.75) { p = 7.5625 * p * p; } else if (p < 2 / 2.75) { p = 7.5625 * (p -= 1.5 / 2.75) * p + 0.75; } else if (p < 2.5 / 2.75) { p = 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375; } else { p = 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375; } return invert ? (1 - p) * 0.5 : p * 0.5 + 0.5; }) ); //CIRC _wrap("Circ", _create("CircOut", function(p) { return Math.sqrt(1 - (p = p - 1) * p); }), _create("CircIn", function(p) { return -(Math.sqrt(1 - (p * p)) - 1); }), _create("CircInOut", function(p) { return ((p*=2) < 1) ? -0.5 * (Math.sqrt(1 - p * p) - 1) : 0.5 * (Math.sqrt(1 - (p -= 2) * p) + 1); }) ); //Elastic _createElastic = function(n, f, def) { var C = _class("easing." + n, function(amplitude, period) { this._p1 = (amplitude >= 1) ? amplitude : 1; //note: if amplitude is < 1, we simply adjust the period for a more natural feel. Otherwise the math doesn't work right and the curve starts at 1. this._p2 = (period || def) / (amplitude < 1 ? amplitude : 1); this._p3 = this._p2 / _2PI * (Math.asin(1 / this._p1) || 0); this._p2 = _2PI / this._p2; //precalculate to optimize }, true), p = C.prototype = new Ease(); p.constructor = C; p.getRatio = f; p.config = function(amplitude, period) { return new C(amplitude, period); }; return C; }; _wrap("Elastic", _createElastic("ElasticOut", function(p) { return this._p1 * Math.pow(2, -10 * p) * Math.sin( (p - this._p3) * this._p2 ) + 1; }, 0.3), _createElastic("ElasticIn", function(p) { return -(this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * this._p2 )); }, 0.3), _createElastic("ElasticInOut", function(p) { return ((p *= 2) < 1) ? -0.5 * (this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * this._p2)) : this._p1 * Math.pow(2, -10 *(p -= 1)) * Math.sin( (p - this._p3) * this._p2 ) * 0.5 + 1; }, 0.45) ); //Expo _wrap("Expo", _create("ExpoOut", function(p) { return 1 - Math.pow(2, -10 * p); }), _create("ExpoIn", function(p) { return Math.pow(2, 10 * (p - 1)) - 0.001; }), _create("ExpoInOut", function(p) { return ((p *= 2) < 1) ? 0.5 * Math.pow(2, 10 * (p - 1)) : 0.5 * (2 - Math.pow(2, -10 * (p - 1))); }) ); //Sine _wrap("Sine", _create("SineOut", function(p) { return Math.sin(p * _HALF_PI); }), _create("SineIn", function(p) { return -Math.cos(p * _HALF_PI) + 1; }), _create("SineInOut", function(p) { return -0.5 * (Math.cos(Math.PI * p) - 1); }) ); _class("easing.EaseLookup", { find:function(s) { return Ease.map[s]; } }, true); //register the non-standard eases _easeReg(w.SlowMo, "SlowMo", "ease,"); _easeReg(RoughEase, "RoughEase", "ease,"); _easeReg(SteppedEase, "SteppedEase", "ease,"); return Back; }, true); }); if (_gsScope._gsDefine) { _gsScope._gsQueue.pop()(); } //necessary in case TweenLite was already loaded separately. /* * ---------------------------------------------------------------- * Base classes like TweenLite, SimpleTimeline, Ease, Ticker, etc. * ---------------------------------------------------------------- */ (function(window, moduleName) { "use strict"; var _exports = {}, _doc = window.document, _globals = window.GreenSockGlobals = window.GreenSockGlobals || window; if (_globals.TweenLite) { return; //in case the core set of classes is already loaded, don't instantiate twice. } var _namespace = function(ns) { var a = ns.split("."), p = _globals, i; for (i = 0; i < a.length; i++) { p[a[i]] = p = p[a[i]] || {}; } return p; }, gs = _namespace("com.greensock"), _tinyNum = 0.0000000001, _slice = function(a) { //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll() var b = [], l = a.length, i; for (i = 0; i !== l; b.push(a[i++])) {} return b; }, _emptyFunc = function() {}, _isArray = (function() { //works around issues in iframe environments where the Array global isn't shared, thus if the object originates in a different window/iframe, "(obj instanceof Array)" will evaluate false. We added some speed optimizations to avoid Object.prototype.toString.call() unless it's absolutely necessary because it's VERY slow (like 20x slower) var toString = Object.prototype.toString, array = toString.call([]); return function(obj) { return obj != null && (obj instanceof Array || (typeof(obj) === "object" && !!obj.push && toString.call(obj) === array)); }; }()), a, i, p, _ticker, _tickerActive, _defLookup = {}, /** * @constructor * Defines a GreenSock class, optionally with an array of dependencies that must be instantiated first and passed into the definition. * This allows users to load GreenSock JS files in any order even if they have interdependencies (like CSSPlugin extends TweenPlugin which is * inside TweenLite.js, but if CSSPlugin is loaded first, it should wait to run its code until TweenLite.js loads and instantiates TweenPlugin * and then pass TweenPlugin to CSSPlugin's definition). This is all done automatically and internally. * * Every definition will be added to a "com.greensock" global object (typically window, but if a window.GreenSockGlobals object is found, * it will go there as of v1.7). For example, TweenLite will be found at window.com.greensock.TweenLite and since it's a global class that should be available anywhere, * it is ALSO referenced at window.TweenLite. However some classes aren't considered global, like the base com.greensock.core.Animation class, so * those will only be at the package like window.com.greensock.core.Animation. Again, if you define a GreenSockGlobals object on the window, everything * gets tucked neatly inside there instead of on the window directly. This allows you to do advanced things like load multiple versions of GreenSock * files and put them into distinct objects (imagine a banner ad uses a newer version but the main site uses an older one). In that case, you could * sandbox the banner one like: * * * * * * * * @param {!string} ns The namespace of the class definition, leaving off "com.greensock." as that's assumed. For example, "TweenLite" or "plugins.CSSPlugin" or "easing.Back". * @param {!Array.} dependencies An array of dependencies (described as their namespaces minus "com.greensock." prefix). For example ["TweenLite","plugins.TweenPlugin","core.Animation"] * @param {!function():Object} func The function that should be called and passed the resolved dependencies which will return the actual class for this definition. * @param {boolean=} global If true, the class will be added to the global scope (typically window unless you define a window.GreenSockGlobals object) */ Definition = function(ns, dependencies, func, global) { this.sc = (_defLookup[ns]) ? _defLookup[ns].sc : []; //subclasses _defLookup[ns] = this; this.gsClass = null; this.func = func; var _classes = []; this.check = function(init) { var i = dependencies.length, missing = i, cur, a, n, cl, hasModule; while (--i > -1) { if ((cur = _defLookup[dependencies[i]] || new Definition(dependencies[i], [])).gsClass) { _classes[i] = cur.gsClass; missing--; } else if (init) { cur.sc.push(this); } } if (missing === 0 && func) { a = ("com.greensock." + ns).split("."); n = a.pop(); cl = _namespace(a.join("."))[n] = this.gsClass = func.apply(func, _classes); //exports to multiple environments if (global) { _globals[n] = _exports[n] = cl; //provides a way to avoid global namespace pollution. By default, the main classes like TweenLite, Power1, Strong, etc. are added to window unless a GreenSockGlobals is defined. So if you want to have things added to a custom object instead, just do something like window.GreenSockGlobals = {} before loading any GreenSock files. You can even set up an alias like window.GreenSockGlobals = windows.gs = {} so that you can access everything like gs.TweenLite. Also remember that ALL classes are added to the window.com.greensock object (in their respective packages, like com.greensock.easing.Power1, com.greensock.TweenLite, etc.) hasModule = (typeof(module) !== "undefined" && module.exports); if (!hasModule && typeof(define) === "function" && define.amd){ //AMD define((window.GreenSockAMDPath ? window.GreenSockAMDPath + "/" : "") + ns.split(".").pop(), [], function() { return cl; }); } else if (hasModule){ //node if (ns === moduleName) { module.exports = _exports[moduleName] = cl; for (i in _exports) { cl[i] = _exports[i]; } } else if (_exports[moduleName]) { _exports[moduleName][n] = cl; } } } for (i = 0; i < this.sc.length; i++) { this.sc[i].check(); } } }; this.check(true); }, //used to create Definition instances (which basically registers a class that has dependencies). _gsDefine = window._gsDefine = function(ns, dependencies, func, global) { return new Definition(ns, dependencies, func, global); }, //a quick way to create a class that doesn't have any dependencies. Returns the class, but first registers it in the GreenSock namespace so that other classes can grab it (other classes might be dependent on the class). _class = gs._class = function(ns, func, global) { func = func || function() {}; _gsDefine(ns, [], function(){ return func; }, global); return func; }; _gsDefine.globals = _globals; /* * ---------------------------------------------------------------- * Ease * ---------------------------------------------------------------- */ var _baseParams = [0, 0, 1, 1], _blankArray = [], Ease = _class("easing.Ease", function(func, extraParams, type, power) { this._func = func; this._type = type || 0; this._power = power || 0; this._params = extraParams ? _baseParams.concat(extraParams) : _baseParams; }, true), _easeMap = Ease.map = {}, _easeReg = Ease.register = function(ease, names, types, create) { var na = names.split(","), i = na.length, ta = (types || "easeIn,easeOut,easeInOut").split(","), e, name, j, type; while (--i > -1) { name = na[i]; e = create ? _class("easing."+name, null, true) : gs.easing[name] || {}; j = ta.length; while (--j > -1) { type = ta[j]; _easeMap[name + "." + type] = _easeMap[type + name] = e[type] = ease.getRatio ? ease : ease[type] || new ease(); } } }; p = Ease.prototype; p._calcEnd = false; p.getRatio = function(p) { if (this._func) { this._params[0] = p; return this._func.apply(null, this._params); } var t = this._type, pw = this._power, r = (t === 1) ? 1 - p : (t === 2) ? p : (p < 0.5) ? p * 2 : (1 - p) * 2; if (pw === 1) { r *= r; } else if (pw === 2) { r *= r * r; } else if (pw === 3) { r *= r * r * r; } else if (pw === 4) { r *= r * r * r * r; } return (t === 1) ? 1 - r : (t === 2) ? r : (p < 0.5) ? r / 2 : 1 - (r / 2); }; //create all the standard eases like Linear, Quad, Cubic, Quart, Quint, Strong, Power0, Power1, Power2, Power3, and Power4 (each with easeIn, easeOut, and easeInOut) a = ["Linear","Quad","Cubic","Quart","Quint,Strong"]; i = a.length; while (--i > -1) { p = a[i]+",Power"+i; _easeReg(new Ease(null,null,1,i), p, "easeOut", true); _easeReg(new Ease(null,null,2,i), p, "easeIn" + ((i === 0) ? ",easeNone" : "")); _easeReg(new Ease(null,null,3,i), p, "easeInOut"); } _easeMap.linear = gs.easing.Linear.easeIn; _easeMap.swing = gs.easing.Quad.easeInOut; //for jQuery folks /* * ---------------------------------------------------------------- * EventDispatcher * ---------------------------------------------------------------- */ var EventDispatcher = _class("events.EventDispatcher", function(target) { this._listeners = {}; this._eventTarget = target || this; }); p = EventDispatcher.prototype; p.addEventListener = function(type, callback, scope, useParam, priority) { priority = priority || 0; var list = this._listeners[type], index = 0, listener, i; if (this === _ticker && !_tickerActive) { _ticker.wake(); } if (list == null) { this._listeners[type] = list = []; } i = list.length; while (--i > -1) { listener = list[i]; if (listener.c === callback && listener.s === scope) { list.splice(i, 1); } else if (index === 0 && listener.pr < priority) { index = i + 1; } } list.splice(index, 0, {c:callback, s:scope, up:useParam, pr:priority}); }; p.removeEventListener = function(type, callback) { var list = this._listeners[type], i; if (list) { i = list.length; while (--i > -1) { if (list[i].c === callback) { list.splice(i, 1); return; } } } }; p.dispatchEvent = function(type) { var list = this._listeners[type], i, t, listener; if (list) { i = list.length; if (i > 1) { list = list.slice(0); //in case addEventListener() is called from within a listener/callback (otherwise the index could change, resulting in a skip) } t = this._eventTarget; while (--i > -1) { listener = list[i]; if (listener) { if (listener.up) { listener.c.call(listener.s || t, {type:type, target:t}); } else { listener.c.call(listener.s || t); } } } } }; /* * ---------------------------------------------------------------- * Ticker * ---------------------------------------------------------------- */ var _reqAnimFrame = window.requestAnimationFrame, _cancelAnimFrame = window.cancelAnimationFrame, _getTime = Date.now || function() {return new Date().getTime();}, _lastUpdate = _getTime(); //now try to determine the requestAnimationFrame and cancelAnimationFrame functions and if none are found, we'll use a setTimeout()/clearTimeout() polyfill. a = ["ms","moz","webkit","o"]; i = a.length; while (--i > -1 && !_reqAnimFrame) { _reqAnimFrame = window[a[i] + "RequestAnimationFrame"]; _cancelAnimFrame = window[a[i] + "CancelAnimationFrame"] || window[a[i] + "CancelRequestAnimationFrame"]; } _class("Ticker", function(fps, useRAF) { var _self = this, _startTime = _getTime(), _useRAF = (useRAF !== false && _reqAnimFrame) ? "auto" : false, _lagThreshold = 500, _adjustedLag = 33, _tickWord = "tick", //helps reduce gc burden _fps, _req, _id, _gap, _nextTime, _tick = function(manual) { var elapsed = _getTime() - _lastUpdate, overlap, dispatch; if (elapsed > _lagThreshold) { _startTime += elapsed - _adjustedLag; } _lastUpdate += elapsed; _self.time = (_lastUpdate - _startTime) / 1000; overlap = _self.time - _nextTime; if (!_fps || overlap > 0 || manual === true) { _self.frame++; _nextTime += overlap + (overlap >= _gap ? 0.004 : _gap - overlap); dispatch = true; } if (manual !== true) { //make sure the request is made before we dispatch the "tick" event so that timing is maintained. Otherwise, if processing the "tick" requires a bunch of time (like 15ms) and we're using a setTimeout() that's based on 16.7ms, it'd technically take 31.7ms between frames otherwise. _id = _req(_tick); } if (dispatch) { _self.dispatchEvent(_tickWord); } }; EventDispatcher.call(_self); _self.time = _self.frame = 0; _self.tick = function() { _tick(true); }; _self.lagSmoothing = function(threshold, adjustedLag) { _lagThreshold = threshold || (1 / _tinyNum); //zero should be interpreted as basically unlimited _adjustedLag = Math.min(adjustedLag, _lagThreshold, 0); }; _self.sleep = function() { if (_id == null) { return; } if (!_useRAF || !_cancelAnimFrame) { clearTimeout(_id); } else { _cancelAnimFrame(_id); } _req = _emptyFunc; _id = null; if (_self === _ticker) { _tickerActive = false; } }; _self.wake = function(seamless) { if (_id !== null) { _self.sleep(); } else if (seamless) { _startTime += -_lastUpdate + (_lastUpdate = _getTime()); } else if (_self.frame > 10) { //don't trigger lagSmoothing if we're just waking up, and make sure that at least 10 frames have elapsed because of the iOS bug that we work around below with the 1.5-second setTimout(). _lastUpdate = _getTime() - _lagThreshold + 5; } _req = (_fps === 0) ? _emptyFunc : (!_useRAF || !_reqAnimFrame) ? function(f) { return setTimeout(f, ((_nextTime - _self.time) * 1000 + 1) | 0); } : _reqAnimFrame; if (_self === _ticker) { _tickerActive = true; } _tick(2); }; _self.fps = function(value) { if (!arguments.length) { return _fps; } _fps = value; _gap = 1 / (_fps || 60); _nextTime = this.time + _gap; _self.wake(); }; _self.useRAF = function(value) { if (!arguments.length) { return _useRAF; } _self.sleep(); _useRAF = value; _self.fps(_fps); }; _self.fps(fps); //a bug in iOS 6 Safari occasionally prevents the requestAnimationFrame from working initially, so we use a 1.5-second timeout that automatically falls back to setTimeout() if it senses this condition. setTimeout(function() { if (_useRAF === "auto" && _self.frame < 5 && _doc.visibilityState !== "hidden") { _self.useRAF(false); } }, 1500); }); p = gs.Ticker.prototype = new gs.events.EventDispatcher(); p.constructor = gs.Ticker; /* * ---------------------------------------------------------------- * Animation * ---------------------------------------------------------------- */ var Animation = _class("core.Animation", function(duration, vars) { this.vars = vars = vars || {}; this._duration = this._totalDuration = duration || 0; this._delay = Number(vars.delay) || 0; this._timeScale = 1; this._active = (vars.immediateRender === true); this.data = vars.data; this._reversed = (vars.reversed === true); if (!_rootTimeline) { return; } if (!_tickerActive) { //some browsers (like iOS 6 Safari) shut down JavaScript execution when the tab is disabled and they [occasionally] neglect to start up requestAnimationFrame again when returning - this code ensures that the engine starts up again properly. _ticker.wake(); } var tl = this.vars.useFrames ? _rootFramesTimeline : _rootTimeline; tl.add(this, tl._time); if (this.vars.paused) { this.paused(true); } }); _ticker = Animation.ticker = new gs.Ticker(); p = Animation.prototype; p._dirty = p._gc = p._initted = p._paused = false; p._totalTime = p._time = 0; p._rawPrevTime = -1; p._next = p._last = p._onUpdate = p._timeline = p.timeline = null; p._paused = false; //some browsers (like iOS) occasionally drop the requestAnimationFrame event when the user switches to a different tab and then comes back again, so we use a 2-second setTimeout() to sense if/when that condition occurs and then wake() the ticker. var _checkTimeout = function() { if (_tickerActive && _getTime() - _lastUpdate > 2000) { _ticker.wake(); } setTimeout(_checkTimeout, 2000); }; _checkTimeout(); p.play = function(from, suppressEvents) { if (from != null) { this.seek(from, suppressEvents); } return this.reversed(false).paused(false); }; p.pause = function(atTime, suppressEvents) { if (atTime != null) { this.seek(atTime, suppressEvents); } return this.paused(true); }; p.resume = function(from, suppressEvents) { if (from != null) { this.seek(from, suppressEvents); } return this.paused(false); }; p.seek = function(time, suppressEvents) { return this.totalTime(Number(time), suppressEvents !== false); }; p.restart = function(includeDelay, suppressEvents) { return this.reversed(false).paused(false).totalTime(includeDelay ? -this._delay : 0, (suppressEvents !== false), true); }; p.reverse = function(from, suppressEvents) { if (from != null) { this.seek((from || this.totalDuration()), suppressEvents); } return this.reversed(true).paused(false); }; p.render = function(time, suppressEvents, force) { //stub - we override this method in subclasses. }; p.invalidate = function() { this._time = this._totalTime = 0; this._initted = this._gc = false; this._rawPrevTime = -1; if (this._gc || !this.timeline) { this._enabled(true); } return this; }; p.isActive = function() { var tl = this._timeline, //the 2 root timelines won't have a _timeline; they're always active. startTime = this._startTime, rawTime; return (!tl || (!this._gc && !this._paused && tl.isActive() && (rawTime = tl.rawTime(true)) >= startTime && rawTime < startTime + this.totalDuration() / this._timeScale)); }; p._enabled = function (enabled, ignoreTimeline) { if (!_tickerActive) { _ticker.wake(); } this._gc = !enabled; this._active = this.isActive(); if (ignoreTimeline !== true) { if (enabled && !this.timeline) { this._timeline.add(this, this._startTime - this._delay); } else if (!enabled && this.timeline) { this._timeline._remove(this, true); } } return false; }; p._kill = function(vars, target) { return this._enabled(false, false); }; p.kill = function(vars, target) { this._kill(vars, target); return this; }; p._uncache = function(includeSelf) { var tween = includeSelf ? this : this.timeline; while (tween) { tween._dirty = true; tween = tween.timeline; } return this; }; p._swapSelfInParams = function(params) { var i = params.length, copy = params.concat(); while (--i > -1) { if (params[i] === "{self}") { copy[i] = this; } } return copy; }; p._callback = function(type) { var v = this.vars, callback = v[type], params = v[type + "Params"], scope = v[type + "Scope"] || v.callbackScope || this, l = params ? params.length : 0; switch (l) { //speed optimization; call() is faster than apply() so use it when there are only a few parameters (which is by far most common). Previously we simply did var v = this.vars; v[type].apply(v[type + "Scope"] || v.callbackScope || this, v[type + "Params"] || _blankArray); case 0: callback.call(scope); break; case 1: callback.call(scope, params[0]); break; case 2: callback.call(scope, params[0], params[1]); break; default: callback.apply(scope, params); } }; //----Animation getters/setters -------------------------------------------------------- p.eventCallback = function(type, callback, params, scope) { if ((type || "").substr(0,2) === "on") { var v = this.vars; if (arguments.length === 1) { return v[type]; } if (callback == null) { delete v[type]; } else { v[type] = callback; v[type + "Params"] = (_isArray(params) && params.join("").indexOf("{self}") !== -1) ? this._swapSelfInParams(params) : params; v[type + "Scope"] = scope; } if (type === "onUpdate") { this._onUpdate = callback; } } return this; }; p.delay = function(value) { if (!arguments.length) { return this._delay; } if (this._timeline.smoothChildTiming) { this.startTime( this._startTime + value - this._delay ); } this._delay = value; return this; }; p.duration = function(value) { if (!arguments.length) { this._dirty = false; return this._duration; } this._duration = this._totalDuration = value; this._uncache(true); //true in case it's a TweenMax or TimelineMax that has a repeat - we'll need to refresh the totalDuration. if (this._timeline.smoothChildTiming) if (this._time > 0) if (this._time < this._duration) if (value !== 0) { this.totalTime(this._totalTime * (value / this._duration), true); } return this; }; p.totalDuration = function(value) { this._dirty = false; return (!arguments.length) ? this._totalDuration : this.duration(value); }; p.time = function(value, suppressEvents) { if (!arguments.length) { return this._time; } if (this._dirty) { this.totalDuration(); } return this.totalTime((value > this._duration) ? this._duration : value, suppressEvents); }; p.totalTime = function(time, suppressEvents, uncapped) { if (!_tickerActive) { _ticker.wake(); } if (!arguments.length) { return this._totalTime; } if (this._timeline) { if (time < 0 && !uncapped) { time += this.totalDuration(); } if (this._timeline.smoothChildTiming) { if (this._dirty) { this.totalDuration(); } var totalDuration = this._totalDuration, tl = this._timeline; if (time > totalDuration && !uncapped) { time = totalDuration; } this._startTime = (this._paused ? this._pauseTime : tl._time) - ((!this._reversed ? time : totalDuration - time) / this._timeScale); if (!tl._dirty) { //for performance improvement. If the parent's cache is already dirty, it already took care of marking the ancestors as dirty too, so skip the function call here. this._uncache(false); } //in case any of the ancestor timelines had completed but should now be enabled, we should reset their totalTime() which will also ensure that they're lined up properly and enabled. Skip for animations that are on the root (wasteful). Example: a TimelineLite.exportRoot() is performed when there's a paused tween on the root, the export will not complete until that tween is unpaused, but imagine a child gets restarted later, after all [unpaused] tweens have completed. The startTime of that child would get pushed out, but one of the ancestors may have completed. if (tl._timeline) { while (tl._timeline) { if (tl._timeline._time !== (tl._startTime + tl._totalTime) / tl._timeScale) { tl.totalTime(tl._totalTime, true); } tl = tl._timeline; } } } if (this._gc) { this._enabled(true, false); } if (this._totalTime !== time || this._duration === 0) { if (_lazyTweens.length) { _lazyRender(); } this.render(time, suppressEvents, false); if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when someone calls seek() or time() or progress(), they expect an immediate render. _lazyRender(); } } } return this; }; p.progress = p.totalProgress = function(value, suppressEvents) { var duration = this.duration(); return (!arguments.length) ? (duration ? this._time / duration : this.ratio) : this.totalTime(duration * value, suppressEvents); }; p.startTime = function(value) { if (!arguments.length) { return this._startTime; } if (value !== this._startTime) { this._startTime = value; if (this.timeline) if (this.timeline._sortChildren) { this.timeline.add(this, value - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct. } } return this; }; p.endTime = function(includeRepeats) { return this._startTime + ((includeRepeats != false) ? this.totalDuration() : this.duration()) / this._timeScale; }; p.timeScale = function(value) { if (!arguments.length) { return this._timeScale; } value = value || _tinyNum; //can't allow zero because it'll throw the math off if (this._timeline && this._timeline.smoothChildTiming) { var pauseTime = this._pauseTime, t = (pauseTime || pauseTime === 0) ? pauseTime : this._timeline.totalTime(); this._startTime = t - ((t - this._startTime) * this._timeScale / value); } this._timeScale = value; return this._uncache(false); }; p.reversed = function(value) { if (!arguments.length) { return this._reversed; } if (value != this._reversed) { this._reversed = value; this.totalTime(((this._timeline && !this._timeline.smoothChildTiming) ? this.totalDuration() - this._totalTime : this._totalTime), true); } return this; }; p.paused = function(value) { if (!arguments.length) { return this._paused; } var tl = this._timeline, raw, elapsed; if (value != this._paused) if (tl) { if (!_tickerActive && !value) { _ticker.wake(); } raw = tl.rawTime(); elapsed = raw - this._pauseTime; if (!value && tl.smoothChildTiming) { this._startTime += elapsed; this._uncache(false); } this._pauseTime = value ? raw : null; this._paused = value; this._active = this.isActive(); if (!value && elapsed !== 0 && this._initted && this.duration()) { raw = tl.smoothChildTiming ? this._totalTime : (raw - this._startTime) / this._timeScale; this.render(raw, (raw === this._totalTime), true); //in case the target's properties changed via some other tween or manual update by the user, we should force a render. } } if (this._gc && !value) { this._enabled(true, false); } return this; }; /* * ---------------------------------------------------------------- * SimpleTimeline * ---------------------------------------------------------------- */ var SimpleTimeline = _class("core.SimpleTimeline", function(vars) { Animation.call(this, 0, vars); this.autoRemoveChildren = this.smoothChildTiming = true; }); p = SimpleTimeline.prototype = new Animation(); p.constructor = SimpleTimeline; p.kill()._gc = false; p._first = p._last = p._recent = null; p._sortChildren = false; p.add = p.insert = function(child, position, align, stagger) { var prevTween, st; child._startTime = Number(position || 0) + child._delay; if (child._paused) if (this !== child._timeline) { //we only adjust the _pauseTime if it wasn't in this timeline already. Remember, sometimes a tween will be inserted again into the same timeline when its startTime is changed so that the tweens in the TimelineLite/Max are re-ordered properly in the linked list (so everything renders in the proper order). child._pauseTime = child._startTime + ((this.rawTime() - child._startTime) / child._timeScale); } if (child.timeline) { child.timeline._remove(child, true); //removes from existing timeline so that it can be properly added to this one. } child.timeline = child._timeline = this; if (child._gc) { child._enabled(true, true); } prevTween = this._last; if (this._sortChildren) { st = child._startTime; while (prevTween && prevTween._startTime > st) { prevTween = prevTween._prev; } } if (prevTween) { child._next = prevTween._next; prevTween._next = child; } else { child._next = this._first; this._first = child; } if (child._next) { child._next._prev = child; } else { this._last = child; } child._prev = prevTween; this._recent = child; if (this._timeline) { this._uncache(true); } return this; }; p._remove = function(tween, skipDisable) { if (tween.timeline === this) { if (!skipDisable) { tween._enabled(false, true); } if (tween._prev) { tween._prev._next = tween._next; } else if (this._first === tween) { this._first = tween._next; } if (tween._next) { tween._next._prev = tween._prev; } else if (this._last === tween) { this._last = tween._prev; } tween._next = tween._prev = tween.timeline = null; if (tween === this._recent) { this._recent = this._last; } if (this._timeline) { this._uncache(true); } } return this; }; p.render = function(time, suppressEvents, force) { var tween = this._first, next; this._totalTime = this._time = this._rawPrevTime = time; while (tween) { next = tween._next; //record it here because the value could change after rendering... if (tween._active || (time >= tween._startTime && !tween._paused)) { if (!tween._reversed) { tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force); } else { tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force); } } tween = next; } }; p.rawTime = function() { if (!_tickerActive) { _ticker.wake(); } return this._totalTime; }; /* * ---------------------------------------------------------------- * TweenLite * ---------------------------------------------------------------- */ var TweenLite = _class("TweenLite", function(target, duration, vars) { Animation.call(this, duration, vars); this.render = TweenLite.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method) if (target == null) { throw "Cannot tween a null target."; } this.target = target = (typeof(target) !== "string") ? target : TweenLite.selector(target) || target; var isSelector = (target.jquery || (target.length && target !== window && target[0] && (target[0] === window || (target[0].nodeType && target[0].style && !target.nodeType)))), overwrite = this.vars.overwrite, i, targ, targets; this._overwrite = overwrite = (overwrite == null) ? _overwriteLookup[TweenLite.defaultOverwrite] : (typeof(overwrite) === "number") ? overwrite >> 0 : _overwriteLookup[overwrite]; if ((isSelector || target instanceof Array || (target.push && _isArray(target))) && typeof(target[0]) !== "number") { this._targets = targets = _slice(target); //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll() this._propLookup = []; this._siblings = []; for (i = 0; i < targets.length; i++) { targ = targets[i]; if (!targ) { targets.splice(i--, 1); continue; } else if (typeof(targ) === "string") { targ = targets[i--] = TweenLite.selector(targ); //in case it's an array of strings if (typeof(targ) === "string") { targets.splice(i+1, 1); //to avoid an endless loop (can't imagine why the selector would return a string, but just in case) } continue; } else if (targ.length && targ !== window && targ[0] && (targ[0] === window || (targ[0].nodeType && targ[0].style && !targ.nodeType))) { //in case the user is passing in an array of selector objects (like jQuery objects), we need to check one more level and pull things out if necessary. Also note that *
* before * * ``` */ EHDI.CameraManager = function ( canvas ){ var _videoSetup = false; var _canvas = canvas; var _streamCanvas = null; var _loop, _stopLoop = false; var _orientImage = function( orientation, img ){ switch( orientation ){ //case 2: img.position.set(img.width, 0); img.scale.set(-1, 1); break; case 3: img.rotation = Math.PI; img.position.set( img.width, img.height ); break; //case 4: img.position.set(0, img.height); img.scale.set(1, -1); break; //case 5: img.rotation = (0.5 * Math.PI); img.scale.set(1, -1); break; case 6: img.rotation = (0.5 * Math.PI); img.position.set( img.height, 0 ); break; //case 7: img.rotation = (0.5 * Math.PI); img.position.set(img.width, -img.height); img.scale.set(-1, 1); break; case 8: img.rotation = (-0.5 * Math.PI); img.position.set( 0, img.width ); break; } } var _mobilePhoto = function( callback ){ var inputElement = document.getElementById("photo"); inputElement.click(); inputElement.onchange = function (event) { var files = event.target.files, file; if (files && files.length > 0) { file = files[0]; var base64ToArrayBuffer = function(base64) { base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, ''); var binaryString = atob(base64); var len = binaryString.length; var bytes = new Uint8Array(len); for (var i = 0; i < len; i++) { bytes[i] = binaryString.charCodeAt(i); } return bytes.buffer; } var fileReader = new FileReader(); fileReader.onload = function (event) { var img = new Image(); var exif = EXIF.readFromBinaryFile( base64ToArrayBuffer( this.result ) ); var orientation = exif.Orientation; img.src = event.target.result; img.onload = function(e){ var basetx = new PIXI.BaseTexture( img ); basetx.imageUrl = img.src; var texture = new PIXI.Texture( basetx ); callback.apply( null, [ texture, orientation ] ); } }; fileReader.readAsDataURL( file ); } inputElement.value = ""; } } var _takeDesktopPhoto = function( callback ){ var tempCanvas = document.createElement('canvas'); var video = document.body.querySelector('video'); var sCanvas = document.getElementById("stream"); tempCanvas.width = video.videoWidth; tempCanvas.height = video.videoHeight; tempCanvas.getContext('2d').drawImage( video, 0, 0, video.videoWidth, video.videoHeight ); video.pause(); video.src = ""; window.stream.getTracks()[0].stop(); document.getElementById( "vidiv" ).removeChild( video ); _stopUpdate(); document.getElementById( "vidiv" ).removeChild( sCanvas ); var img = new Image(); img.src = tempCanvas.toDataURL(); img.onload = function(){ var basetx = new PIXI.BaseTexture( img ); var texture = new PIXI.Texture( basetx ); callback.apply( null, [ texture ] ); }; } var _update = function( x, y, width, height ){ var sCanvas = document.getElementById("stream"); var sCtx = sCanvas.getContext('2d'); var video = document.body.querySelector('video'); var ratio = 1; if( width !== -1 ) ratio = width / video.videoWidth; if( height !== -1 ) ratio = height / video.videoHeight; var newWidth = video.videoWidth * ratio; var newHeight = video.videoHeight * ratio; var posX = x - ( newWidth * 0.5 ); var posY = y - ( newHeight * 0.5 ); _stopLoop = false; var loop = function() { if( _stopLoop === false ){ sCtx.drawImage( video, posX, posY, newWidth, newHeight ); requestAnimationFrame( loop ); } } _loop = requestAnimationFrame( loop ); } var _stopUpdate = function(){ if ( _loop ) { cancelAnimationFrame( _loop ); } _stopLoop = true; } /********* * PUBLIC **********/ return { /** * @param (STRING) callback - where the resulting contianer will be returned to * @param (BOOL) isMobile * @param (NUMBER) maxWidth * @param (NUMBER) maxHeight * @desc creates image from upload or camera use */ getVideoSetup: function(){ return _videoSetup; }, setupVideo: function( onsuccess, onfail, posX, posY, width, height ){ if( _videoSetup === true ) return; var constraints = { audio: false, video: true }; if (navigator.mediaDevices === undefined) { navigator.mediaDevices = {}; } // Some browsers partially implement mediaDevices. We can't just assign an object // with getUserMedia as it would overwrite existing properties. // Here, we will just add the getUserMedia property if it's missing. if (navigator.mediaDevices.getUserMedia === undefined) { navigator.mediaDevices.getUserMedia = function( constraints ) { // First get ahold of the legacy getUserMedia, if present var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; // Some browsers just don't implement it - return a rejected promise with an error // to keep a consistent interface if (!getUserMedia) { return Promise.reject(new Error('getUserMedia is not implemented in this browser')); } // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise return new Promise(function(resolve, reject) { getUserMedia.call(navigator, constraints, resolve, reject); }); } } navigator.mediaDevices.getUserMedia( constraints ) .then(function(stream) { var vidTest = document.createElement( 'video' ); vidTest.autoplay = true; _canvas.style.position = 'absolute'; vidTest.style.position = 'absolute'; vidTest.style.display = 'none'; document.getElementById( "vidiv" ).appendChild( vidTest ); _streamCanvas = null; _streamCanvas = document.createElement( 'canvas' ); _streamCanvas.id = 'stream'; _streamCanvas.style.position = 'absolute'; _streamCanvas.width = _canvas.width; _streamCanvas.height = _canvas.height; _streamCanvas.style.width = _canvas.style.width; _streamCanvas.style.height = _canvas.style.height; _streamCanvas.style.display = "block"; _streamCanvas.style.marginTop = _canvas.style.marginTop; _streamCanvas.style.marginBottom = _canvas.style.marginBottom; _streamCanvas.style.marginLeft = _canvas.style.marginLeft; _streamCanvas.style.marginRight = _canvas.style.marginRight; _streamCanvas.style.paddingLeft = _canvas.style.paddingLeft; _streamCanvas.style.paddingRight = _canvas.style.paddingRight; _streamCanvas.style.paddingTop = _canvas.style.paddingTop; _streamCanvas.style.paddingBottom = _canvas.style.paddingBottom; document.getElementById( "vidiv" ).appendChild( _streamCanvas ); var video = document.querySelector('video'); window.stream = stream; video.src = URL.createObjectURL(stream); video.play(); video.onloadeddata = function(){ _videoSetup = true; onsuccess(); _update( posX, posY, width, height ); } }) .catch( function(err) { alert( err.name + ": " + err.message ); onfail(); }); }, takePhoto: function( callback, isMobile ){ if( isMobile ){ var callTex = function( texture, orientation ){ var imgContainer = new EHDI.aka.Container(); var imgSprite = new EHDI.aka.Sprite( texture ); _orientImage( orientation, imgSprite ); imgContainer.addChild( imgSprite ); callback.apply( null, [imgContainer] ); } _mobilePhoto( callTex ); } else{ var video = document.body.querySelector( 'video' ); if( typeof video !== 'undefined' && video !== null ){ var callTex = function( texture ){ _videoSetup = false; var imgContainer = new EHDI.aka.Container(); var imgSprite = new EHDI.aka.Sprite( texture ); imgContainer.addChild( imgSprite ); callback.apply( null, [imgContainer] ); }; _takeDesktopPhoto( callTex ); } } } } }; //GET OR INITIALIZE EHDI var EHDI = EHDI || Object.create(null); /** * @param (STRING) name * @desc Custom Event for Ehdi */ EHDI.Event = function(name){ this.name = name; this.callbacks = []; } /** * @param (FUNCTION) callback */ EHDI.Event.prototype.registerCallback = function(callback){ this.callbacks.push(callback); } EHDI.Event.prototype.unregisterCallback = function(callback){ var index = this.callbacks.indexOf(callback); if(index > -1) this.callbacks.splice(index, 1); } EHDI.Event.prototype.clearCallbacks = function(){ this.callbacks.length = 0; } /** * @desc EventManager for custom events in javascript */ EHDI.EventManager = function(){ "use strict"; "use restrict"; var _eventController = Object.create(null); var _events = Object.create(null); var _maxListeners = 10; //PUBLIC /** * @desc sets the maximum number of listeners * @default 10 */ Object.defineProperty(_eventController, "maxListeners",{ set: function(val){ if(typeof val !== "number") return; _maxListeners = val; }, get: function(){ return _maxListeners; } }) /** * @param (STRING) name */ _eventController.register = function(name){ var e = new EHDI.Event(name); _events[name] = e; } /** * @param (STRING) name * @desc unregisters the event and removes all of its listeners */ _eventController.unregister = function(name){ if(!(name in _events)) throw new Error("event not found"); _events[name].clearCallbacks(); delete _events[name]; } /** * @param (STRING) name * @param (OBJECT) data */ _eventController.dispatch = function(name, data){ if(!(name in _events)) throw new Error("event is unregistered"); var callbacks = _events[name].callbacks; for(var i = 0, len = callbacks.length; i < len; i++){ if(typeof data !== "undefined"){ callbacks[i](data); }else callbacks[i](); }; } /** * @param (STRING) name * @param (FUNCTION) callback - note avoid using anonymous function for callback */ _eventController.addListener = function(name, callback){ if(!(name in _events)) throw new Error("event is unregistered"); if(_events[name].callbacks.length >= _maxListeners) throw new Error("max amount of listeners limit reached, maxListener: " + _maxListeners); _events[name].registerCallback(callback); } /** * @param (STRING) name * @param (FUNCTION) callback */ _eventController.removeListener = function(name, callback){ if(!(name in _events)) throw new Error("event is unregistered"); if(_events[name].callbacks.indexOf(callback) <= -1) console.log("callback listener not found"); _events[name].unregisterCallback(callback); } return _eventController; }; //GET OR INITIALIZE EHDI var EHDI = EHDI || Object.create(null); /** * @param (JSON) configData * @param (JSON) localeData * @desc sets a JSONManager to handle localization and/or configuration */ EHDI.JSONManager = function(configData, localeData){ "use strict"; "use restrict"; /********* * PRIVATES **********/ var _configData = configData; var _localeData = localeData; /********* * PUBLIC **********/ return{ /** * @param (JSON) data * @desc sets config data. will not overwrite when config data exist. */ setConfigData: function(data){ if(typeof _configData === "undefined") _configData = data; }, /** * @param (JSON) data * @desc sets locale data. will not overwrite when locale data exist. */ setLocaleData: function(data){ if(typeof _localeData === "undefined") _localeData = data; }, /** * @param (STRING) id; * @return (OBJECT) returns _localeData.data[id] or _localeData.data; */ getLocale: function(id){ if(arguments.length < 1) { return _localeData.data; }else{ return _localeData.data[id]; } }, /** * @return (OBJECT) returns config data. */ getConfig: function(){ return _configData; } }; }; (function(){ "use strict"; "use restrict"; //GET OR INITIALIZE EHDI EHDI = EHDI || Object.create(null); /** * @desc Asset Storage * @member images - Pixi Textures * @member cjAssets - String and Sound Files */ EHDI.Assets = { images: EHDI.aka.TextureCache, fonts: [] }; /** * @class * @desc LoadManager for managing fonts, strings, images and audio * images and fonts are handled by PixiJS while * strings and audio are handled by CreateJS * Loading Priority - createJS loads first then pixiJS. * Load starts by using EHDI.LoadManager.start(); */ EHDI.LoadManager = (function(){ /*************** * PRIVATES ***************/ //const var _STRINGEXTENSION = ["json", "js", "xml", "txt"]; var _AUDIOEXTENSION = ["ogg", "mp3", "wav"]; var _FONTEXTENSION = ["ttf", "woff", "woff2", "otf"]; //module var _public = Object.create(null); var _cjAssets, _pixiLoader; //manifest for createJS, sounds and strings; var _createJSManifest = []; var _pixiAssetToBeLoaded = []; var _fontToBeParsed = []; var _functionOnComplete = null; var _onCompleteParam = []; var _isLoading = false; var _loadProgress = 0; var _soundProgress = 0; var _totalObjectsToLoad = 0; var _createJSManifestToUnload = []; var _pixiAssetToBeUnload = []; var _totalObjectsToUnload = 0; /** * loader initalization */ var init = function(){ _pixiLoader = EHDI.aka.Loader; _cjAssets = new createjs.LoadQueue(); createjs.Sound.alternateExtensions = _AUDIOEXTENSION; Object.defineProperty(EHDI.Assets, "cjAssets",{value: _cjAssets, enumerable: false }); _cjAssets.installPlugin(createjs.Sound); _cjAssets.addEventListener("progress", cjProgressHandler); _cjAssets.addEventListener("complete", cjCompleteHandler); _cjAssets.addEventListener("error", cjErrorHandler); _pixiLoader.on("progress", pixiProgressHandler); _pixiLoader.on("error", pixiErrorHandler); } /** * @param (STRING) id * @return the asset from createJS.Loader or pixi.loader * returns null if no object is found */ EHDI.Assets.fetch = function(id){ var result = _cjAssets.getResult(id); if(!result){ result = EHDI.aka.Loader.resources[id] || null; } return result; } /** * @desc clears the manifest file */ var clearManifest = function(){ _pixiAssetToBeLoaded.length = 0; _createJSManifest.length = 0; _createJSManifestToUnload.length = 0; _pixiAssetToBeUnload.length = 0; } /** * @param (Array) urls * @param (Array) exts */ var getUrlsBaseOnExtension = function(urls, exts){ var fileSourcePaths = urls.filter(function (source) { if(typeof source !== "string") source = source.url; var extension = source.split('.').pop(); return (exts.indexOf(extension) !== -1); }); return fileSourcePaths; } var fontParser = function(source){ var fontData = source.split("/").pop().split("."); var fontFamily = fontData[0]; var fontExt = fontData[1]; if(fontExt === "ttf") fontExt = "truetype"; if(fontExt === "otf") fontExt = "opentype"; if(fontExt === "eot") fontExt = "embedded-opentype"; var newStyle = document.createElement("style"); var fontFace = "@font-face {font-family: '" + fontFamily + "'; src: url('" + source + "') format('" + fontExt + "');"; newStyle.appendChild(document.createTextNode(fontFace)); document.body.appendChild(newStyle); EHDI.Assets.fonts.push(fontFamily); } var pixiProgressHandler = function (loader,resource) { _loadProgress = _soundProgress + (loader.progress * (_pixiAssetToBeLoaded.length) / _totalObjectsToLoad); }; var pixiErrorHandler = function(error, loader,resource){ console.log("PixiJS Loading Error!"); console.log(error); } var pixiCompleteHandler = function(loader,resources){ clearManifest(); _isLoading = false; if(_fontToBeParsed.length > 0) { _fontToBeParsed.length = 0; } if(typeof _functionOnComplete === "function") _functionOnComplete.apply(null, _onCompleteParam); } var cjProgressHandler = function(e){ var progress = (e.progress > 1) ? 1 : e.progress; _loadProgress = (progress * (_createJSManifest.length) / _totalObjectsToLoad) * 100; _soundProgress = _loadProgress; } var cjCompleteHandler = function(e){ if(_pixiAssetToBeLoaded.length <= 0){ pixiCompleteHandler(); return; } _pixiLoader.add(_pixiAssetToBeLoaded).load(pixiCompleteHandler); } var cjErrorHandler = function(e){ console.log("CreateJS Loading Error"); console.log(e); } /** * @param (jsonmanager) -jsonmanager component * @param (id) - config file id */ var configHandler = function(jsonmanager, id, callback){ var configJSON, localeConfig, locid, localeUrl, lang, onDone; var ext = ".json"; var _loader; var _fontsToLoad, _stringToLoad; configJSON = _cjAssets.getResult(id); localeConfig = configJSON.locale; localeUrl = localeConfig.url; lang = (typeof localeConfig.lang !== "undefined") ? localeConfig.lang : "en"; locid = localeConfig.id + lang; if(typeof localeConfig.font[lang] === "undefined"){ _fontsToLoad = localeConfig.font["default"]; }else{ _fontsToLoad = localeConfig.font[lang]; } _stringToLoad = [localeUrl+locid+ext]; onDone = function(){ jsonmanager.setConfigData(configJSON); jsonmanager.setLocaleData(_cjAssets.getResult(locid)); if(typeof callback === "function") callback(); } _public.queueStrings(_stringToLoad); _public.queueFonts(_fontsToLoad); _public.start(onDone); } var startUnload = function(){ var asset, item; while(_createJSManifestToUnload.length > 0){ item = _createJSManifestToUnload.pop(); asset = _cjAssets.getItem(item); _cjAssets.remove(asset.id); if(asset.type === "sound"){ createjs.Sound.removeSound(asset.id); } } while(_pixiAssetToBeUnload.length > 0){ item = _pixiAssetToBeUnload.pop(); asset = EHDI.Assets.images[item]; asset.destroy(true); } if(_createJSManifest.length > 0){ _cjAssets.loadManifest(_createJSManifest); }else{ cjCompleteHandler(); } } init(); /************** * PUBLIC *************/ /** * @param (ARRAY) url paths of the strings to be loaded * @desc add string url to queue */ _public.queueStrings = function(urls){ var manifest = []; var url, id; while(urls.length > 0){ url = urls.pop(); //id = url.split("/").pop(); //has .fileType id = url.split("/").pop().split(".")[0]; manifest.push({ id: id, src: url }) }; _createJSManifest = _createJSManifest.concat(manifest); } /** * @param (ARRAY) url paths of the fonts to be loaded * @desc add font url to queue */ _public.queueFonts = function(urls){ //var fontsToLoad = [] var url, id; while(urls.length > 0){ url = urls.pop(); id = url.split("/").pop().split(".")[0]; _fontToBeParsed.push(fontParser(url)); /*fontsToLoad.push({ name: id, url: url })*/ }; //_pixiAssetToBeLoaded = _pixiAssetToBeLoaded.concat(fontsToLoad); } /** * @param (ARRAY) url paths of the fonts to be loaded * @desc add audio url to queue */ _public.queueAudios = function(urls){ var manifest = [] var url, id; while(urls.length > 0){ url = urls.pop(); if(typeof url !== "string") { id = url.id; url = url.url; } else { id = url.split("/").pop().split(".")[0]; } manifest.push({ id: id, src: url }) }; _createJSManifest = _createJSManifest.concat(manifest); } /** * @param (ARRAY) url paths of the images to be loaded * @desc add image url to queue, can also use to parse atlas */ _public.queueImages = function(urls){ var imagesToBeLoaded = []; var url, id; while(urls.length > 0){ url = urls.pop(); if(typeof url !== "string") { id = url.id; url = url.url; } else { id = url.split("/").pop().split(".")[0]; } imagesToBeLoaded.push({ name: id, url: url }) }; _pixiAssetToBeLoaded = _pixiAssetToBeLoaded.concat(imagesToBeLoaded); } /** * @param (ARRAY) url paths of the assets to be loaded * @desc loads all assets. */ _public.queueAssets = function(urls){ var filterUrls = function(main, filt){ main = main.filter(function (source) { return filt.indexOf(source) < 0; }); return main; } var fontsToLoad = getUrlsBaseOnExtension(urls, _FONTEXTENSION); var audiosToLoad = getUrlsBaseOnExtension(urls, _AUDIOEXTENSION); var stringsToLoad = getUrlsBaseOnExtension(urls, _STRINGEXTENSION); var imgFileToLoad = filterUrls(urls, fontsToLoad); imgFileToLoad = filterUrls(imgFileToLoad, stringsToLoad); imgFileToLoad = filterUrls(imgFileToLoad, audiosToLoad); _public.queueFonts(fontsToLoad); _public.queueAudios(audiosToLoad); _public.queueStrings(stringsToLoad); _public.queueImages(imgFileToLoad); } /** * @param (STRING) url path of the config file * @param (OBJECT) JSONManager component * @param (FUNCTION) callback * @desc loads config file and its dependencies */ _public.loadConfig = function(url, jsonmanager, callback){ if(typeof url !== "string") throw new Error("Invalid URL"); if(typeof jsonmanager === "undefined") throw new Error("needs JSONManager component"); if(_isLoading) throw new Error("Load manager is currently running"); var id = url.split("/").pop().split(".")[0]; clearManifest(); _public.queueStrings([url]); _public.start(configHandler, [jsonmanager, id, callback]); } /** * @return gets the progress of the load manager. */ _public.getProgress = function(){ return _loadProgress; } /** * @param (function) callback - the callback function when loading ends * @param (ARRAY) params - the callback parameters * @desc starts loading and storing files */ _public.start = function(callback, params){ if(_isLoading) throw new Error("EHDI Load manager is currently running"); _functionOnComplete = callback; _onCompleteParam = params; _isLoading = true; _loadProgress = 0; _soundProgress = 0; _totalObjectsToLoad = _createJSManifest.length + _pixiAssetToBeLoaded.length; _totalObjectsToUnload = _createJSManifestToUnload.length + _pixiAssetToBeUnload.length; _pixiLoader.reset(); startUnload(); } /** * @param (ARRAY) url paths of the images to be loaded * @desc add urls to unload queue */ _public.unloadAssets = function(urls){ var filterUrls = function(main, filt){ main = main.filter(function (source) { return filt.indexOf(source) < 0; }); return main; } var fontsToUnload = getUrlsBaseOnExtension(urls, _FONTEXTENSION); var audiosToUnload = getUrlsBaseOnExtension(urls, _AUDIOEXTENSION); var stringsToUnload = getUrlsBaseOnExtension(urls, _STRINGEXTENSION); var imgFileToUnload = filterUrls(urls, audiosToUnload); imgFileToUnload = filterUrls(imgFileToUnload, stringsToUnload); imgFileToUnload = filterUrls(imgFileToUnload, fontsToUnload); _createJSManifestToUnload = _createJSManifestToUnload.concat(audiosToUnload); _createJSManifestToUnload = _createJSManifestToUnload.concat(stringsToUnload); _pixiAssetToBeUnload = _pixiAssetToBeUnload.concat(imgFileToUnload); } return _public; }()); }()); var EHDI = EHDI || Object.create(null); EHDI.ScaleManager = function(renderer, stage, type, defaultWidth, defaultHeight) { var resizeCallback = arguments.length <= 5 || typeof arguments[5] === "undefined" ? null : arguments[5]; var scaleX, scaleY, orientation, isAutoScale, center, margin, resizeClock; var newStyle = document.createElement("style"); var style = "html, body {padding : 0; margin : 0; overflow : hidden; width: 100%; height: 100%, position : fixed}"; newStyle.appendChild(document.createTextNode(style)); document.head.appendChild(newStyle); var ratio = 1; var width = defaultWidth; var height = defaultHeight; EHDI.screen = EHDI.screen || Object.create(null); updateDeviceOrientation(); scaleToWindow(); function scaleToWindow() { scaleX = window.innerWidth / defaultWidth; scaleY = window.innerHeight / defaultHeight; if(type === EHDI.ScaleManager.DOCKING.WIDTH) { ratio = scaleX; } else if(type === EHDI.ScaleManager.DOCKING.HEIGHT) { ratio = scaleY; } else if(type === EHDI.ScaleManager.DOCKING.AUTO) { ratio = Math.min(scaleX, scaleY); } else if(type === EHDI.ScaleManager.DOCKING.FULLSCREEN) { ratio = Math.max(scaleX, scaleY); } var canvas = renderer.view; canvas.style.paddingLeft = 0; canvas.style.paddingRight = 0; canvas.style.paddingTop = 0; canvas.style.paddingBottom = 0; canvas.style.display = "block"; width = Math.floor(defaultWidth * ratio); height = Math.floor(defaultHeight * ratio); stage.scale.x = stage.scale.y = ratio; if(width > window.innerWidth) { EHDI.screen.xOffset = (window.innerWidth - width) * 0.5; width = window.innerWidth; EHDI.screen.viewWidth = width / ratio; } else { EHDI.screen.viewWidth = window.innerWidth / ratio; if(EHDI.screen.viewWidth > defaultWidth) { EHDI.screen.viewWidth = defaultWidth; } EHDI.screen.xOffset = 0; } if(height > window.innerHeight) { EHDI.screen.yOffset = (window.innerHeight - height) * 0.5; height = window.innerHeight; EHDI.screen.viewHeight = height / ratio; } else { EHDI.screen.viewHeight = window.innerHeight / ratio; if(EHDI.screen.viewHeight > defaultHeight) { EHDI.screen.viewHeight = defaultHeight; } EHDI.screen.yOffset = 0; } if(EHDI.screen.centerOrigin) { stage.children.forEach(function(element) { element.position.set(EHDI.screen.viewWidth * 0.5, EHDI.screen.viewHeight * 0.5); }); } // EHDI.screen.xOffset = EHDI.screen.stageWidth - EHDI.screen.viewWidth; // EHDI.screen.yOffset = EHDI.screen.stageHeight - EHDI.screen.viewHeight; renderer.resize(width, height); centerCanvas(); window.scrollTo(0, 0); updateDeviceOrientation(); if(resizeCallback) { resizeCallback(); } }; function updateDeviceOrientation() { if(window.innerHeight > window.innerWidth){ orientation = EHDI.ScaleManager.SCREEN_ORIENTATION.PORTRAIT; } else { orientation = EHDI.ScaleManager.SCREEN_ORIENTATION.LANDSCAPE; } return orientation; }; function centerCanvas() { var canvas = renderer.view; canvas.style.marginTop = 0; canvas.style.marginBottom = 0; canvas.style.marginLeft = 0; canvas.style.marginRight = 0; if (type == EHDI.ScaleManager.DOCKING.HEIGHT || type == EHDI.ScaleManager.DOCKING.FULLSCREEN || (type == EHDI.ScaleManager.DOCKING.AUTO && width < window.innerWidth)) { margin = (window.innerWidth - width) / 2; canvas.style.marginLeft = margin + "px"; canvas.style.marginRight = margin + "px"; } //Center vertically (for wide canvases) if (type == EHDI.ScaleManager.DOCKING.WIDTH || type == EHDI.ScaleManager.DOCKING.FULLSCREEN || (type == EHDI.ScaleManager.DOCKING.AUTO && height < window.innerHeight)) { margin = (window.innerHeight - height) / 2; canvas.style.marginTop = margin + "px"; canvas.style.marginBottom = margin + "px"; } }; /** * @param (NUMBER) timeout - the scale timeout */ function addAutomaticScaling(timeout) { if(!isAutoScale) window.addEventListener("resize", function() { clearTimeout(resizeClock); timeout = timeout || 500; resizeClock = setTimeout(scaleToWindow, timeout); isAutoScale = true; }); } function getScale() { return ratio; } function getOrientation() { return orientation; } return { getScale : getScale, getOrientation : getOrientation, scaleToWindow : scaleToWindow, setResizeCallback : function(callback){ if(typeof callback !== "function") throw new Error("insert function as parameter") resizeCallback = callback; }, addAutomaticScaling : addAutomaticScaling } }; EHDI.ScaleManager.SCREEN_ORIENTATION = { LANDSCAPE : 0, PORTRAIT : 1 } EHDI.ScaleManager.DOCKING = { WIDTH: 0, HEIGHT: 1, AUTO: 2, FULLSCREEN : 3 } var EHDI = EHDI || Object.create(null); EHDI.scene = EHDI.scene || Object.create(null); EHDI.SceneManager = function(width, height, nogl, centerOrigin) { var rendererView = arguments.length <= 4 || typeof arguments[4] === "undefined" ? document.getElementById("game-canvas") : arguments[4]; var _stage = new EHDI.aka.Container(); var rendererOptions = { view: rendererView, antialiasing: false, transparent: true, resolution: window.devicePixelRatio, autoResize: true, } var _renderer; if(!!nogl){ _renderer = new EHDI.aka.CanvasRenderer(width, height, rendererOptions); }else{ _renderer = new EHDI.aka.AutoDetectRenderer(width, height, rendererOptions); } var _stageWidth = width; var _stageHeight = height; var _sceneList = []; var _popUpList = []; var _currentScene = null; var _sceneLayer = new EHDI.aka.Container(); var _popupLayer = new EHDI.aka.Container(); var _notificationLayer = new EHDI.aka.Container(); EHDI.screen = EHDI.screen || Object.create(null); EHDI.screen.stageWidth = width; EHDI.screen.stageHeight = height; EHDI.screen.centerOrigin = centerOrigin; if(centerOrigin) { _sceneLayer.position.set(width * 0.5, height * 0.5); _popupLayer.position.set(width * 0.5, height * 0.5); _notificationLayer.position.set(width * 0.5, height * 0.5); } _stage.addChild(_sceneLayer); _stage.addChild(_popupLayer); _stage.addChild(_notificationLayer); return { //GETTERS getStage : function () { return _stage; }, getRenderer : function () { return _renderer; }, getStageWidth : function () { return _stageWidth; }, getStageHeight : function () { return _stageHeight; }, defaultWidth : width, defaultHeight : height, renderScreen : function(){ _renderer.render(_stage); }, changeScene : function(scene, transition, destroyPrevious) { if(typeof scene.screenWillAppear === 'function') scene.screenWillAppear(); if(_currentScene) if(typeof _currentScene.screenWillDisappear === 'function') _currentScene.screenWillDisappear(); if(transition) { var values = Object.create(null); EHDI.config.isTransition = true; var keys = Object.keys(transition) for(var i = 0; i< keys.length; i++){ if(transition[keys[i]].hasOwnProperty('from') && transition[keys[i]].hasOwnProperty('to')){ scene[keys[i]] = transition[keys[i]].from; values[keys[i]] = transition[keys[i]].to; }else if(!transition[keys[i]].hasOwnProperty('duration')){ values[keys[i]] = transition[keys[i]]; } } _sceneLayer.addChild(scene); values.onComplete = function() { EHDI.config.isTransition = false; if(_currentScene) { if(typeof _currentScene.screenDidDisappear === 'function') _currentScene.screenDidDisappear(); _sceneLayer.removeChild(_currentScene); } if(typeof scene.screenDidAppear === 'function') scene.screenDidAppear(); if(destroyPrevious) _currentScene.destroy({children : true}); _currentScene = scene; } TweenLite.to(scene, transition.duration, values); } else { _sceneLayer.addChild(scene); if(_currentScene) { _sceneLayer.removeChild(_currentScene); if(typeof _currentScene.screenDidDisappear === 'function') _currentScene.screenDidDisappear(); } if(typeof scene.screenDidAppear === 'function') scene.screenDidAppear(); if(destroyPrevious) _currentScene.destroy({children : true}); _currentScene = scene; } }, /** * @desc CurrentScene popup functions will work when first popup is added, succeeding popup won't call the function. */ pushPopUp : function(popup, transition) { if(typeof popup.popUpWillAppear === 'function') popup.popUpWillAppear(); if(typeof _currentScene.popUpWillAppear === 'function' && _popUpList.length === 0) _currentScene.popUpWillAppear(); if(transition) { var values = Object.create(null); EHDI.config.isTransition = true; var keys = Object.keys(transition) for(var i = 0; i< keys.length; i++){ if(transition[keys[i]].hasOwnProperty('from') && transition[keys[i]].hasOwnProperty('to')){ popup[keys[i]] = transition[keys[i]].from; values[keys[i]] = transition[keys[i]].to; }else if(!transition[keys[i]].hasOwnProperty('duration')){ values[keys[i]] = transition[keys[i]]; } } _popupLayer.addChild(popup); values.onComplete = function() { EHDI.config.isTransition = false; if(typeof popup.popUpDidAppear === 'function') popup.popUpDidAppear(); if(typeof _currentScene.popUpDidAppear === 'function' && _popUpList.length === 0) _currentScene.popUpDidAppear(); _popUpList.push(popup); } TweenLite.to(popup, transition.duration, values); } else { _popUpList.push(popup); _popupLayer.addChild(popup); if(typeof popup.popUpDidAppear === 'function') popup.popUpDidAppear(); } }, /** * @desc CurrentScene popPopUp function will be called when last popup is removed. */ popPopUp : function(transition, destroyPrevious) { if(_popUpList.length <= 0) throw "Pop Up list is empty!"; var popUpToRemove = _popUpList.pop(); if(typeof popUpToRemove.popUpWillDisappear === 'function') popUpToRemove.popUpWillDisappear(); if(typeof _currentScene.popUpWillDisappear === 'function' && _popUpList.length === 0) _currentScene.popUpWillDisappear(); if(transition) { var values = Object.create(null); EHDI.config.isTransition = true; var keys = Object.keys(transition) for(var i = 0; i< keys.length; i++){ if(transition[keys[i]].hasOwnProperty('from') && transition[keys[i]].hasOwnProperty('to')){ popUpToRemove[keys[i]] = transition[keys[i]].from; values[keys[i]] = transition[keys[i]].to; }else if(!transition[keys[i]].hasOwnProperty('duration')){ values[keys[i]] = transition[keys[i]]; } } values.onComplete = function() { EHDI.config.isTransition = false; if(typeof popUpToRemove.popUpDidDisappear === 'function') popUpToRemove.popUpDidDisappear(); if(typeof _currentScene.popUpDidDisappear === 'function' && _popUpList.length === 0) _currentScene.popUpDidDisappear(); _popupLayer.removeChild(popUpToRemove); if(destroyPrevious) popUpToRemove.destroy({children : true}); } TweenLite.to(popUpToRemove, transition.duration, values); }else { _popupLayer.removeChild(popUpToRemove); if(typeof popUpToRemove.popUpDidDisappear === 'function') popUpToRemove.popUpDidDisappear(); if(typeof _currentScene.popUpDidDisappear === 'function' && _popUpList.length === 0) _currentScene.popUpDidDisappear(); if(destroyPrevious) popUpToRemove.destroy({children : true}); } }, popAllPopUps: function(destroyPrevious){ while(_popUpList.length > 0){ var popup = _popUpList.pop(); if(typeof popup.popUpWillDisappear === 'function') popup.popUpWillDisappear(); if(typeof _currentScene.popUpWillDisappear === 'function' && _popUpList.length === 0) _currentScene.popUpWillDisappear(); _popupLayer.removeChild(popup); if(typeof popup.popUpDidDisappear === 'function') popup.popUpDidDisappear(); if(typeof _currentScene.popUpDidDisappear === 'function' && _popUpList.length === 0) _currentScene.popUpDidDisappear(); if(destroyPrevious) popup.destroy({children : true}); } }, addNotification: function(notif){ _notificationLayer.addChild(notif); }, /** * @param (OBJECT) notif - notification object * @param (BOOLEAN) destroy - set to true to destroy object */ removeNotification: function(notif, destroy){ var obj, index = _notificationLayer.children.indexOf(notif); if(index > -1){ obj = _notificationLayer.removeChild(notif); } if(destroy) obj.destroy({children : true}); obj = null; }, /** * @desc returns the topmost object from the notification layer * @return (DisplayObject) */ popNofication: function(){ return _notificationLayer.children.pop() }, screenResize: function() { if(_currentScene && typeof _currentScene.onScreenResize === 'function') _currentScene.onScreenResize(); _popUpList.forEach(function(element) { if(typeof element.onScreenResize === 'function') element.onScreenResize(); }); _notificationLayer.children.forEach(function(element) { if(typeof element.onScreenResize === 'function') element.onScreenResize(); }); } } }; EHDI.scene.TransitionParameter = function (from, to) { this.from = from; this.to = to; } EHDI.scene.TransitionParameter.constructor = EHDI.scene.TransitionParameter; var EHDI = EHDI || Object.create(null); EHDI.SoundManager = function (isAddInterrupt) { var _bgm = null; var _sfx = []; var _vo = null; var _muted = false; var _isActive = true; var _isAutoResume = true; var _volume = { bgm: 1, sfx: 1, vo: 1 }; var _hasInterrupt = isAddInterrupt || true; var pauseAll = function() { if(_bgm) { _bgm.paused = true; } _sfx.forEach(function (sfxElement) { sfxElement.paused = true; }); if(_vo) { _vo.paused = true; } } var resumeAll = function() { if(!_isAutoResume) return; if(_bgm) { _bgm.paused = false; } _sfx.forEach(function (sfxElement) { sfxElement.paused = false; }); if(_vo) { _vo.paused = false; } } var checkInterrupt = function() { if (window.document.webkitHidden || window.document.hidden) { pauseAll(); } else { resumeAll(); } } var addInterruptListener = function(){ window.addEventListener("blur", pauseAll); window.addEventListener("focus", resumeAll); window.addEventListener("pagehide", pauseAll); window.addEventListener("pageshow", resumeAll); window.addEventListener("webkitvisibilitychange", checkInterrupt); window.addEventListener("webkitvisibilitychange", checkInterrupt); } var removeInterruptListener = function(){ window.removeEventListener("blur", pauseAll); window.removeEventListener("focus", resumeAll); window.removeEventListener("pagehide", pauseAll); window.removeEventListener("pageshow", resumeAll); window.removeEventListener("webkitvisibilitychange", checkInterrupt); window.removeEventListener("webkitvisibilitychange", checkInterrupt); } if(_hasInterrupt) { addInterruptListener(); } return { set enableInterrupt(v){ if(typeof v !== "boolean" || _hasInterrupt === v) return; _hasInterrupt = v; if(_hasInterrupt){ addInterruptListener(); }else{ removeInterruptListener(); } }, get enableInterrupt(){ return _hasInterrupt; }, set sfxVolume(v){ if(typeof v !== "number") return; _volume.sfx = v; if(_sfx){ _sfx.forEach( function(sfxElement) { sfxElement.volume = sfxElement.volume * _volume.sfx; } ); } }, get sfxVolume(){ return _volume.sfx; }, set bgmVolume(v){ if(typeof v !== "number") return; _volume.bgm = v; if(_bgm) _bgm.volume = _bgm.volume * _volume.bgm; }, get bgmVolume(){ return _volume.bgm; }, set voVolume(v){ if(typeof v !== "number") return; _volume.vo = v; if(_vo) _vo.volume = _vo.volume * _volume.vo; }, get voVolume(){ return _volume.vo; }, playBGM : function(bgmToPlay, volume) { volume = ( volume * _volume.bgm ) || _volume.bgm; if(typeof bgmToPlay === 'string') { if(_bgm instanceof createjs.AbstractSoundInstance) { _bgm.stop(); _bgm.destroy(); } _bgm = createjs.Sound.play(bgmToPlay, {loop : -1}); _bgm.volume = volume; _bgm.muted = _muted; return _bgm; } else { throw("pass string id of BGM to be played"); } }, stopBGM : function () { if(_bgm) { _bgm.stop(); _bgm.destroy(); _bgm = null; } }, pauseBGM : function () { if(_bgm) { _bgm.paused = true; } }, resumeBGM : function () { if(_bgm) { _bgm.paused = false; } }, playSFX : function(sfxToPlay, volume) { volume = ( volume * _volume.sfx ) || _volume.sfx; if(typeof sfxToPlay === 'string') { var playingSFX = createjs.Sound.play(sfxToPlay); playingSFX.volume = volume; playingSFX.muted = _muted; _sfx.push(playingSFX); var sfxListener = playingSFX.on("complete", function(sfxToStop) { var index = _sfx.indexOf(sfxToStop.currentTarget); if(index > -1) { var forDisposal = _sfx.splice(index, 1)[0]; playingSFX.off("complete", sfxListener); forDisposal.destroy(); } }); return playingSFX; } else { throw("pass string id of SFX to be played"); } }, stopSFX : function (sfxToStop) { var index = _sfx.indexOf(sfxToStop); if(index > -1) { var forDisposal = _sfx.splice(index, 1)[0]; forDisposal.stop(); forDisposal.destroy(); } }, stopAllSFX : function () { _sfx.forEach(function (sfxElement) { sfxElement.stop(); sfxElement.destroy(); }); _sfx = []; }, pauseAllSFX : function() { _sfx.forEach(function (sfxElement) { sfxElement.paused = true; }); }, resumeAllSFX : function() { _sfx.forEach(function (sfxElement) { sfxElement.paused = false; }); }, playVO : function(VOToPlay, volume) { volume = ( volume * _volume.vo ) || _volume.vo; if(typeof VOToPlay === 'string') { _vo = createjs.Sound.play(VOToPlay); _vo.volume = volume; _vo.muted = _muted; return _vo; } else { throw("pass string ID of VO to be played"); } }, stopVO : function() { if(_vo) { _vo.stop(); _vo.destroy(); } }, pauseVO : function() { if(_vo) { _vo.paused = true; } }, resumeVO : function() { if(_vo) { _vo.paused = false; } }, setMute : function() { var isMute = arguments.length <= 0 || typeof arguments[0] === "undefined" ? !_muted : arguments[0];; _muted = isMute; if(_bgm) _bgm.muted = _muted; _sfx.forEach(function(sfxElement) { sfxElement.muted = _muted; }); if(_vo) _vo.muted = _muted; }, getMuted : function() { return _muted; }, setDeactivate : function() { var isDeactivate = arguments.length <= 0 || typeof arguments[0] === "undefined" ? !_isActive : arguments[0];; _isActive = isDeactivate; if(_bgm) _bgm.paused = !_isActive; _sfx.forEach(function(sfxElement) { sfxElement.paused = !_isActive; }); if(_vo) _vo.muted = !_isActive; }, autoResumeToggle : function(isAutoResume) { _isAutoResume = isAutoResume; } }; }; var EHDI = EHDI || Object.create(null); /** * @desc creates and manages local storage. * handles one shared object at a time per ID. uses "game_data" for default storage * * ```js * var storageManager = EHDI.StorageManager(); * storageManager.setLocalInfo("HighScoreData", hsObj) * storageManager.setDataID("another_data") will use "another_data" for default storage * storageManager.setDataID() reverts back to "game_data" as default storage * storageManager.clearLocalData() clears data on the dataID specified. * ``` */ EHDI.StorageManager = function (){ 'use strict'; 'use restrict'; /********* * PRIVATE **********/ var _dataID = "game_data"; var _isSupported = true; var _sharedObject = JSON.parse(localStorage.getItem(_dataID)); var _isLocalStorageNameSupported = function(){ try{ localStorage.setItem('t3st', '1'); localStorage.removeItem('t3st'); return true; }catch(error){ return false; } } var _checkLocalData = function(){ if(!_isSupported) return false; var obj; if(_sharedObject === null && _dataID !== null){ _sharedObject = Object.create(null); obj = JSON.stringify(_sharedObject); localStorage.setItem(_dataID, obj); return true; }else if(_sharedObject !== null){ return true; } return false; } _isSupported = _isLocalStorageNameSupported(); if(!_isSupported){ _sharedObject = Object.create(null); console.log("Local storage is not supported. Current session will not be saved offline"); }else{ _checkLocalData(); } /********* * PUBLIC **********/ return { /** * @desc it checks the local data. * @return (BOOL) true if data already exists */ checkLocalData : _checkLocalData, /** * @param (STRING) id * @desc creates new dataID to be manage and used */ setDataID: function(id){ if(arguments.length < 0 || typeof id !== "string") id = "game_data"; _dataID = id; _checkLocalData(); }, /** * @return (STRING) dataID */ getDataID: function(){ return _dataID; }, /** * @param (STRING) key - get the info of the key * @return (OBJECT) the value of the sharedObject * (null) if the key is not found */ getLocalInfo: function(key){ if(typeof key !== "string") throw "invalid key"; if(typeof _sharedObject[key] === "undefined"){ return null; }else{ return _sharedObject[key]; } }, /** * @param (STRING) key * @param (OBJECT || ARRAY) val * @desc sets or updates the data on the sharedObject */ setLocalInfo: function(key, val){ if(arguments.length < 2) throw "invalid parameters"; if(typeof key !== "string") throw "invalid key"; _sharedObject[key] = val; if(!!_checkLocalData()){ localStorage.setItem(_dataID, JSON.stringify(_sharedObject)); } }, /** * @param (STRING) key * @desc deletes the data on the sharedObject */ deleteLocalInfo: function(key){ if(typeof key !== "string") throw "invalid key"; delete _sharedObject[key]; localStorage.setItem(_dataID, JSON.stringify(_sharedObject)); }, /** * @desc clears the overall local data in stored on dataID */ clearLocalData: function(){ var obj; _sharedObject = Object.create(null); if(_isSupported){ obj = JSON.stringify(_sharedObject); localStorage.setItem(_dataID, obj); } } } }; //GET OR INITIALIZE EHDI var EHDI = EHDI || Object.create(null); /** * @param (PIXI.Renderer) renderer - pass PIXI renderer as param here. * @param (PIXI.Container) stage - pass PIXI container that will be rendered. * @desc use and initialize the UpdateManager, this will handle the update utility and auto rendering * if renderer and stage are added in the parameters */ EHDI.UpdateManager = function(renderer, stage){ "use strict"; // PRIVATES // Properties var _autoRender = false; var _updateList = []; var _prevTime; var _frameNumber = 0; var _fpsStartTime; var _fps; var _renderer, _stage; /** * @desc frameLoop - updates every frame and returns dt in milliseconds */ var _frameLoop = function(){ window.requestAnimationFrame(_frameLoop); var curTime = new Date(); if(!_fpsStartTime) _fpsStartTime = new Date().getTime(); var dt = (curTime - _prevTime); var fpsCountTime = (curTime.getTime() - _fpsStartTime) / 1000; _frameNumber++; _fps = Math.floor(_frameNumber / fpsCountTime); if(fpsCountTime > 1) { _fpsStartTime = new Date().getTime(); _frameNumber = 0; } if(_updateList.length > 0){ for(var i = 0;i < _updateList.length;i++){ _updateList[i](dt); } } _prevTime = curTime; //Render the graphics if(!!_autoRender) _renderer.render(_stage); } //check if renderer and stage is passed as parameters if(arguments.length > 0){ if(!(renderer instanceof PIXI.CanvasRenderer) && !(renderer instanceof PIXI.WebGLRenderer)) throw new Error("Please pass renderer as parameter") if(!(stage instanceof PIXI.DisplayObject)) throw new Error("Stage is not a display object") _autoRender = true; _renderer = renderer; _stage = stage; } //start the update _frameLoop(); // PUBLICS return{ /** * @param (BOOL) val */ getFPS : function() { return _fps; }, /** * @param (BOOL) val */ setAutoRender: function(val){ _autoRender = val; }, /** * @return (BOOL) returns true if manager auto renders gfx */ isAutoRendering: function(){ return _autoRender; }, /** * @param (Function) callback - the callback function to be added */ addFrameListener: function(callback){ if(typeof callback !== 'function') throw new Error("Callback must be a function"); _updateList.push(callback); }, /** * @param (Function) callback - check if the callback exist * @return (BOOL) */ hasFrameListener: function(callback){ if(typeof callback !== 'function') throw new Error("Callback must be a function"); var index = _updateList.indexOf(callback); if(index > -1) return true; return false; }, /** * @param (Function) callback - the callback function that needs to be removed */ removeFrameListener: function(callback){ if(typeof callback !== 'function') throw "Callback must be a function"; var index = _updateList.indexOf(callback); if(index > -1) _updateList.splice(index, 1); }, /** * @desc removes all callback listeners */ removeAllFrameListeners: function(){ _updateList.length = 0; } }; }; /** *@TODO add detection for MS EDGE * add detection for cocoon wrapper */ (function(ehdi){ 'use strict'; ehdi.BrowserInfo = ehdi.BrowserInfo || Object.create(null); var navigator = window.navigator; var info = ehdi.BrowserInfo; var userAgent = navigator.userAgent; var regex, ver; var getiPhoneVersion = function(){ var iHeight = window.screen.height; var iWidth = window.screen.width; if (iWidth === 320 && iHeight === 480) { return "4"; } else if (iWidth === 375 && iHeight === 667) { return "6"; } else if (iWidth === 414 && iHeight === 736) { return "6+"; } else if (iWidth === 320 && iHeight === 568) { return "5"; } else if (iHeight <= 480) { return "1-3"; } return ' '; } info.platformType = navigator.platform; info.platformVersion = ""; info.browserName = navigator.appName; info.browserVersion = navigator.appVersion; info.isMobileDevice = false; info.isIOS = false; info.deviceType = "desktop"; //Platform if(navigator.platform.indexOf('iPhone') !== -1){ info.isMobileDevice = true; info.platformType = "iPhone " + getiPhoneVersion(); info.deviceType = "phone"; info.isIOS = true; regex = /OS (\d+_\d+)/g; if(userAgent.search(regex) !== -1){ ver = String(userAgent.match(regex)); info.platformVersion = ver.replace("_","."); } }else if(navigator.platform.indexOf('iPod') != -1){ info.isMobileDevice = true; info.platformType = "iPod"; info.deviceType = "tablet"; info.isIOS = true; regex = /OS (\d+_\d+)/g; if(userAgent.search(regex) !== -1){ ver = String(userAgent.match(regex)); info.platformVersion = ver.replace("_","."); } }else if(navigator.platform.indexOf('iPad') != -1){ info.isMobileDevice = true; info.platformType = "iPad"; info.deviceType = "tablet"; info.isIOS = true; regex = /OS (\d+_\d+)/g; if(userAgent.search(regex) !== -1){ ver = String(userAgent.match(regex)); info.platformVersion = ver.replace("_","."); } }else if(userAgent.indexOf('Android') != -1){ info.isMobileDevice = true; info.platformType = "Android"; info.deviceType = "tablet"; regex = /OS (\d+_\d+)/g; if(userAgent.search(regex) !== -1){ ver = String(userAgent.match(regex)); info.platformVersion = ver.replace("_","."); } }else if(userAgent.indexOf('Kindle') != -1 || userAgent.indexOf('Silk') != -1){ info.isMobileDevice = true; info.platformType = "Android"; info.deviceType = "tablet"; }else if(userAgent.indexOf('IEMobile') != -1){ info.isMobileDevice = true; info.platformType = "IEMobile"; info.deviceType = "phone"; regex = /IEMobile\/(\d+\.\d+)/g; if(userAgent.search(regex) !== -1) info.platformVersion = String(userAgent.match(regex)); }else if(navigator.platform.indexOf('Win') != -1){ info.platformType = 'Windows'; info.deviceType = "desktop"; }else if(navigator.platform.indexOf('Mac') != -1){ info.platformType = 'MAC'; info.deviceType = "desktop"; regex = /OS (\d+_\d+)/g; if(userAgent.search(regex) !== -1){ ver = String(userAgent.match(regex)); info.platformVersion = ver.replace("_","."); } }else if(navigator.platform.indexOf('Linux') != -1){ info.platformType = 'Linux'; info.deviceType = "desktop"; } var _browser = (function(){ var ua= navigator.userAgent, tem, M= ua.match(/(crios|samsungbrowser|opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if(/trident/i.test(M[1])){ tem= /\brv[ :]+(\d+)/g.exec(ua) || []; return 'IE '+(tem[1] || ''); } if(M[1]=== 'Chrome'){ tem= ua.match(/\b(OPR|Edge)\/(\d+)/); if(tem != null){ if(tem.indexOf('OPR') != -1) return tem.slice(1).join(' ').replace('OPR', 'Opera'); if(tem.indexOf('Edge') != -1) return tem.slice(1).join(' ').replace('Edge', 'Edge'); } } M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?']; if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]); return M.join(' '); })(); info.browserName = _browser.split(" ")[0]; if(info.browserName.toUpperCase() === "CRIOS") info.browserName = "Chrome"; info.browserVersion = _browser.split(" ")[1]; ehdi.checkGLQuality = function(renderer){ if(!renderer) throw new Error("pass renderer as parameters"); var max = 0; var gl = renderer.view.getContext("webgl") || renderer.view.getContext("experimental-webgl"); if(!gl) return "canvas"; var ext = ( gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') ) if(ext) max = gl.getParameter(ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT); if(max > 4) return "gl-high" return "gl-normal"; } return ehdi; }(EHDI || Object.create(null))) //GET OR INITIALIZE EHDI var EHDI = EHDI || Object.create(null); EHDI.CollisionUtil = function(){}; //METHODS /** * @param (Object) rect1 - 1st rectangle that contains: {x, y, width, height} * @param (Object) rect2 - 2nd rectangle that contains: {x, y, width, height} * @return (Bool) true or false if there was collision */ EHDI.CollisionUtil.rectToRect = function( rect1, rect2 ){ if( rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x && rect1.y < rect2.y + rect2.height && rect1.height + rect1.y > rect2.y ){ return true; } return false; } /** * @param (Object) cir - circle that contains: {x, y, r} * @param (Object) rect - rectangle that contains: {x, y, width, height} * @return (Bool) true or false if there was collision */ EHDI.CollisionUtil.circleToRect = function( cir, rect ){ var distX = Math.abs( cir.x - rect.x - ( rect.width * 0.5 ) ); var distY = Math.abs( cir.y - rect.y - ( rect.height * 0.5 ) ); if( distX > ( ( rect.width * 0.5 ) + cir.r ) ) return false; if( distY > ( ( rect.height * 0.5 ) + cir.r ) ) return false; if( distX <= ( rect.width * 0.5 ) ) return true; if( distY <= ( rect.height * 0.5 ) ) return true; var dx = distX - ( rect.width * 0.5 ); var dy = distY - ( rect.height * 0.5 ); return ( dx * dx + dy * dy <= ( cir.r * cir.r ) ); } /** * @param (Object) cir1 - 1st circle that contains: {x, y, r} * @param (Object) cir2 - 2nd circle that contains: {x, y, r} * @return (Bool) true or false if there was collision */ EHDI.CollisionUtil.circleToCircle = function( cir1, cir2 ){ var dx = cir1.x - cir2.x; var dy = cir1.y - cir2.y; var distance = Math.sqrt(dx * dx + dy * dy); if (distance < cir1.r + cir2.r) { return true; } return false; } //GET OR INITIALIZE EHDI var EHDI = EHDI || Object.create(null); EHDI.NumberUtil = EHDI.NumberUtil || Object.create(null); //PROPERTIES EHDI.NumberUtil.GOLDEN_RATIO = 1.61803398875; //METHODS /** * @param (Number) val - the value in degrees * @return (Number) val - the value in radians */ EHDI.NumberUtil.degreeToRadian = function(val){ return (val * (Math.PI / 180)); } /** * @param (Number) val - the value in radians * @return (Number) val - the value in degrees */ EHDI.NumberUtil.radianToDegree = function(val){ return (val * (180/ Math.PI)); } /** * @param (Number) val - interpolation value * @param (Number) min * @param (Number) max * @return interpolate the val */ EHDI.NumberUtil.lerp = function(val, min, max){ return (1 - val) * min + val * max; } /** * @param (Number) val - the value that needs to be normalize * @param (Number) min * @param (Number) max * @return normalize the val */ EHDI.NumberUtil.normalize = function(val, min, max){ return (val - min) / (max - min); } /** * @param (Number) val - the value that needs to be map * @param (Number) minX - val min * @param (Number) maxX - val max * @param (Number) minY - result min * @param (Number) maxY - result max * @param (Boolean) strict - set to true to lock val to minY and maxY * @return returns map val */ EHDI.NumberUtil.map = function(val, minX, maxX, minY, maxY, strict){ var strict = (typeof strict !== 'undefined') ? strict : false; if(!!strict){ if(val > minX) return minY; if(val < maxX) return maxY; } return NumberUtil.lerp( NumberUtil.normalize(val, minX, maxX), minY, maxY ); } /** * @param (Number) val - the value that needs to be clamp * @param (Number) min * @param (Number) max * @return lock the val on min/max */ EHDI.NumberUtil.clamp = function(val, min, max) { return Math.max(min, Math.min(max, val)); } /** * @param (Number) min * @param (Number) max * @return generate a random number from min to max */ EHDI.NumberUtil.randomRange = function(min, max){ if(min > max){ return (Math.random() * (min - max) + max); }else{ return (Math.random() * (max - min) + min); } } /** * @param (Number) num * @return get number of digit of a non-floating number */ EHDI.NumberUtil.getDigit = function(num){ return num.toString().length; } /** * @param (ARRAY) myArray * @return a shuffled array */ EHDI.NumberUtil.shuffleArray = function(myArray) { var swap = function(arr, i, j) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }; var randInt = function(max) { return Math.floor(Math.random() * max); }; for(var slot = myArray.length - 1; slot > 0; slot--) { var element = randInt(slot + 1); swap(myArray, element, slot); } } /* Based on Stress Test function by Mat Groves*/ EHDI = EHDI || Object.create(null); EHDI.StressTest = function(callback) { var _callback = callback; var _stage = new PIXI.Container(); var _stressCanvas = document.createElement('canvas'); _stressCanvas.width = _stressCanvas.height = "500px"; document.body.appendChild(_stressCanvas); var rendererOptions = { view: _stressCanvas, antialiasing: false, transparent: true, resolution: window.devicePixelRatio, autoResize: true }; var _renderer = new EHDI.aka.AutoDetectRenderer(500, 500, rendererOptions); _renderer.view.style.position = "absolute"; var _cover = document.createElement("div"); _cover.style.width = _cover.style.height = "500px"; _cover.style.background = "#FFFFFF"; document.body.appendChild(_cover); _cover.style.position = "absolute"; _cover.style.zIndex = 2; var _this = this; var _frameRate = []; var _testSprites = []; var _startTime, _lastTime, _texture; this.update = function() { var curTime = Date.now(); for(var i=0; i < _testSprites.length; i++) { _testSprites[i].rotation += 0.3; } _renderer.render(_stage); var diff = curTime - _lastTime; diff *= 0.6; _frameRate.push(diff); _lastTime = curTime; var elapsedTime = curTime - _startTime; if(elapsedTime < 1500) { window.requestAnimationFrame(function() { _this.update(); }) } else { document.body.removeChild(_renderer.view); document.body.removeChild(_cover); var result = _frameRate.length / 1.5; EHDI.BrowserInfo = EHDI.BrowserInfo || Object.create(null); EHDI.BrowserInfo.isLowEndDevice = result < 30; if(_callback) _callback(); } } this.begin = function() { _texture = EHDI.displays.TextureRectangle(0xFFFFFF, 52, 74); for(var i = 0; i < 300; i++) { var sprite = new PIXI.Sprite(_texture); sprite.anchor.set(0.5, 0.5); _stage.addChild(sprite); sprite.position.set(50, + Math.random() * 400, 50 + Math.random() * 400); _testSprites.push(sprite); }; _startTime = Date.now(); _lastTime = Date.now(); _renderer.render(_stage); _this.update(); } _this.begin(); return _this; } var AssetDirectory = { "load": [ "assets/bgm/bgm.ogg", "assets/fonts/airbagfree-regular.woff", "assets/fonts/londonbetween.woff", "assets/htp/htp_eden1.png", "assets/htp/htp_eden2.png", "assets/htp/htp_eden3.png", "assets/htp/htp_eden4.png", "assets/htp/htp_eden5.png", "assets/htp/htp_eden6.png", "assets/ingame/beartigerlion_anim_ske.json", "assets/ingame/beartigerlion_anim_tex.json", "assets/ingame/beartigerlion_anim_tex.png", "assets/ingame/bg_eden.png", "assets/ingame/deer_anim_ske.json", "assets/ingame/deer_anim_tex.json", "assets/ingame/deer_anim_tex.png", "assets/ingame/donkey_anim_ske.json", "assets/ingame/donkey_anim_tex.json", "assets/ingame/donkey_anim_tex.png", "assets/ingame/eden_prop1.png", "assets/ingame/eden_prop2.png", "assets/ingame/eden_prop3.png", "assets/ingame/eden_prop4.png", "assets/ingame/eden_prop5.png", "assets/ingame/eden_prop6.png", "assets/ingame/elephant_anim_ske.json", "assets/ingame/elephant_anim_tex.json", "assets/ingame/elephant_anim_tex.png", "assets/ingame/fx_firsttimeplay_glow.png", "assets/ingame/fx_glow_red.png", "assets/ingame/fx_glow_red2.png", "assets/ingame/fx_glow_white.png", "assets/ingame/fx_glow_white2.png", "assets/ingame/fx_glow_yellow.png", "assets/ingame/fx_glow_yellow2.png", "assets/ingame/fx_sparkle_ske.json", "assets/ingame/fx_sparkle_tex.json", "assets/ingame/fx_sparkle_tex.png", "assets/ingame/gazelle_anim_ske.json", "assets/ingame/gazelle_anim_tex.json", "assets/ingame/gazelle_anim_tex.png", "assets/ingame/giraffe_anim_ske.json", "assets/ingame/giraffe_anim_tex.json", "assets/ingame/giraffe_anim_tex.png", "assets/ingame/goat_anim_ske.json", "assets/ingame/goat_anim_tex.json", "assets/ingame/goat_anim_tex.png", "assets/ingame/goat_anim_ver2_ske.json", "assets/ingame/goat_anim_ver2_tex.json", "assets/ingame/goat_anim_ver2_tex.png", "assets/ingame/horse_anim_ske.json", "assets/ingame/horse_anim_tex.json", "assets/ingame/horse_anim_tex.png", "assets/ingame/monkeyslothlamb_anim_ske.json", "assets/ingame/monkeyslothlamb_anim_tex.json", "assets/ingame/monkeyslothlamb_anim_tex.png", "assets/ingame/pomegranate.png", "assets/ingame/pomegranate_expired.png", "assets/ingame/ram_anim_ske.json", "assets/ingame/ram_anim_tex.json", "assets/ingame/ram_anim_tex.png", "assets/ingame/rhino_anim_ske.json", "assets/ingame/rhino_anim_tex.json", "assets/ingame/rhino_anim_tex.png", "assets/sfx/animal_collect.ogg", "assets/sfx/bear.ogg", "assets/sfx/button_sfx.ogg", "assets/sfx/deer.ogg", "assets/sfx/donkey.ogg", "assets/sfx/elephant.ogg", "assets/sfx/gazelle.ogg", "assets/sfx/giraffe.ogg", "assets/sfx/goat.ogg", "assets/sfx/horse.ogg", "assets/sfx/lamb.ogg", "assets/sfx/lion.ogg", "assets/sfx/monkey.ogg", "assets/sfx/pick_fruit.ogg", "assets/sfx/ram.ogg", "assets/sfx/rhino.ogg", "assets/sfx/score_points.ogg", "assets/sfx/sloth.ogg", "assets/sfx/star_gain.ogg", "assets/sfx/success.ogg", "assets/sfx/tiger.ogg", "assets/titlescreen/bg_logo_eden.png", "assets/titlescreen/gizmo_eden.png", "assets/titlescreen/logo_eden1.png", "assets/titlescreen/logo_eden2.png", "assets/ui/btn_audio1.png", "assets/ui/btn_audio2.png", "assets/ui/btn_audio3.png", "assets/ui/btn_audio4.png", "assets/ui/btn_exit.png", "assets/ui/btn_exit2.png", "assets/ui/btn_pause.png", "assets/ui/btn_pause2.png", "assets/ui/btn_play.png", "assets/ui/btn_play2.png", "assets/ui/btn_prevnext.png", "assets/ui/btn_prevnext2.png", "assets/ui/btn_return.png", "assets/ui/btn_return2.png", "assets/ui/check-button1.png", "assets/ui/check-button2.png", "assets/ui/gfx_container.png", "assets/ui/gfx_container_white.png", "assets/ui/gfx_explode.png", "assets/ui/gfx_flare_long.png", "assets/ui/gfx_flare_star.png", "assets/ui/gfx_loading_bar_con.png", "assets/ui/gfx_pop.png", "assets/ui/gfx_pop2.png", "assets/ui/gfx_star0.png", "assets/ui/gfx_star1.png", "assets/ui/gfx_starbg.png", "assets/ui/x-button1.png", "assets/ui/x-button2.png" ], "preload": [ "assets/preload/fonts/Exo-Bold.otf", "assets/preload/fonts/Exo-Medium.ttf", "assets/preload/fonts/proximanova-black.otf", "assets/preload/strings/gizmoloading_ske.json", "assets/preload/strings/gizmoloading_tex.json", "assets/preload/strings/strings.json", "assets/preload/ui/gfx_bg.png", "assets/preload/ui/gfx_loading.png", "assets/preload/ui/gizmoloading_tex.png" ], "preloadstring": [] }; var EHDI = EHDI || Object.create(null); EHDI.displays = EHDI.displays || Object.create(null); EHDI.displays.FillRectangle = function(color, x, y, width, height) { var alpha = arguments.length <= 4 || typeof arguments[5] == "undefined" ? 1 : arguments[5]; var graphics = new PIXI.Graphics(); graphics._sprite = null; graphics._width = width; graphics._height = height; graphics._color = color; var draw = function(width, height, fillStyle) { graphics.clear(); graphics.beginFill(fillStyle); graphics.drawRect(0,0,width, height); graphics.endFill(); }; draw(graphics._width, graphics._height, graphics._color); var texture = graphics.generateCanvasTexture(1); var sprite = new EHDI.aka.Sprite(texture); sprite.position.set(x,y); sprite.alpha = alpha; graphics.sprite = sprite; return sprite; }; EHDI.displays.changeRectangleColor = function(color, width, height) { var alpha = arguments.length <= 4 || typeof arguments[5] == "undefined" ? 1 : arguments[5]; var graphics = new PIXI.Graphics(); graphics._sprite = null; graphics._width = width; graphics._height = height; graphics._color = color; var draw = function(width, height, fillStyle) { graphics.clear(); graphics.beginFill(fillStyle); graphics.drawRect(0,0,width, height); graphics.endFill(); }; draw(graphics._width, graphics._height, graphics._color); var texture = graphics.generateCanvasTexture(1); return texture; } var EHDI = EHDI || Object.create(null); var UTILS = UTILS || Object.create(null); var POOLS = POOLS || Object.create(null); EHDI.components = EHDI.components || Object.create(null); EHDI.components.GlowEffect = function(size) { EHDI.aka.Container.call(this); this.active = false; this.visual = new EHDI.aka.Sprite(EHDI.Assets.images["fx_firsttimeplay_glow"]); this.visual.anchor.set(0.5, 0.5); this.scale.x = size / this.visual.width; this.scale.y = size / this.visual.height; this.addChild(this.visual); this.speed = (360 *(Math.PI / 180 )) / 10000; this.appear = function(score) { if(this.active) return; this.active = true; } this.disappear = function() { if(!this.active) return; this.active = false; } this.update = function (delta) { if(!this.active) return false; this.rotation += delta * this.speed; return false; } } EHDI.components.GlowEffect.prototype = Object.create(EHDI.aka.Container.prototype); var EHDI = EHDI || Object.create(null); EHDI.components = EHDI.components || Object.create(null); EHDI.components.HighScoreHolder = function(stage, highscore) { var score = 0; var scoreContainer = new EHDI.aka.Container(); stage.addChild(scoreContainer); var containerSprite = new EHDI.aka.Sprite(EHDI.Assets.images["gfx_container"]); scoreContainer.addChild(containerSprite); var scoreHeader = new EHDI.displays.TextSprite(EHDI.GAME.jsonManager.getLocale("STR_CONT_BEST")); scoreHeader.anchor.x = 0.5; scoreHeader.anchor.y = 0.5; scoreHeader.position.set(containerSprite.width * 0.169, containerSprite.height * 0.4); scoreContainer.addChild(scoreHeader); var scoreTxt = new EHDI.displays.TextSprite(EHDI.GAME.jsonManager.getLocale("STR_CONT_BESTSCORE")); scoreTxt.text = "" + highscore; scoreTxt.anchor.x = 0.5; scoreTxt.anchor.y = 0.5; scoreTxt.position.set(containerSprite.width * 0.675, containerSprite.height * 0.45); scoreContainer.addChild(scoreTxt); var setDisplayPosition = function(x,y) { scoreContainer.position.set(x,y); } var dispose = function() { onScoreTimeline.kill(); }; return { setXY : setDisplayPosition, dispose : dispose }; }; var EHDI = EHDI || Object.create(null); EHDI.components = EHDI.components || Object.create(null); EHDI.components.pauseButton = function() { EHDI.displays.Button.call(this, EHDI.Assets.images["btn_pause"], EHDI.Assets.images["btn_pause2"], null, null); this.isPaused = false; this.isEndGame = false; // EHDI.GAME.soundManager.autoResumeToggle(false); this.setOnClickFunction(this.sfxThenPause.bind(this)); this.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.95, EHDI.GAME.sceneManager.getStageHeight() * 0.075); EHDI.GAME.pauseButton = this; this.pauseTheGame = EHDI.GAME.pauseButton.pauseGame.bind(EHDI.GAME.pauseButton).bind(EHDI.GAME.pauseButton); this.checkIfInterrupt = EHDI.GAME.pauseButton.checkInterrupt.bind(EHDI.GAME.pauseButton); window.addEventListener("blur", this.pauseTheGame); window.addEventListener("pagehide", this.pauseTheGame); window.addEventListener("webkitvisibilitychange", this.checkIfInterrupt); window.addEventListener("visibilitychange", this.checkIfInterrupt); }; EHDI.components.pauseButton.prototype = Object.create(EHDI.displays.Button.prototype); EHDI.components.pauseButton.prototype.sfxThenPause = function() { EHDI.GAME.soundManager.playSFX("button_sfx"); this.pauseGame(); } EHDI.components.pauseButton.prototype.checkInterrupt = function() { if (window.document.webkitHidden || window.document.hidden) { this.pauseGame(); } }; EHDI.components.pauseButton.prototype.pauseGame = function() { if(this.isPaused || this.isEndGame) return; this.isPaused = true; EHDI.GAME.sceneManager.pushPopUp(new EHDI.popup.PausePopUp(true), {y : new EHDI.scene.TransitionParameter(-EHDI.GAME.sceneManager.getStageHeight(), EHDI.GAME.sceneManager.getStageHeight() * 0.5), duration : 0.25}); }; EHDI.components.pauseButton.prototype.resumeGame = function() { this.isPaused = false; }; EHDI.components.pauseButton.prototype.endGame = function() { this.isEndGame = true; // this.hidePauseButton(); window.removeEventListener("blur", this.pauseTheGame); window.removeEventListener("pagehide", this.pauseTheGame); window.removeEventListener("webkitvisibilitychange", this.checkIfInterrupt); window.removeEventListener("visibilitychange", this.checkIfInterrupt); }; EHDI.components.pauseButton.prototype.destroy = function() { // EHDI.GAME.soundManager.autoResumeToggle(true); console.log("hello world"); EHDI.aka.Sprite.prototype.destroy.apply(this, arguments); } EHDI.components.pauseButton.prototype.hidePauseButton = function() { TweenLite.to(this, 0.25, {y : -this.y}); }; var EHDI = EHDI || Object.create(null); var UTILS = UTILS || Object.create(null); var POOLS = POOLS || Object.create(null); EHDI.components = EHDI.components || Object.create(null); EHDI.components.ScoreEffect = function(stage, highscore) { EHDI.aka.Container.call(this); var DECAY_TIME = 500; var FLOAT_SPEED = 0.25; this.scoreDisplay = new EHDI.displays.TextSprite(EHDI.GAME.jsonManager.getLocale("STR_CONT_SCOREEFFECT")); this.scoreDisplay.anchor.x = 0.5; this.scoreDisplay.anchor.y = 1; this.addChild(this.scoreDisplay); this.timer=0; this.active = false; this.appear = function(score) { if(this.active) return; this.scoreDisplay.y =0; this.scoreDisplay.text = score; this.scoreDisplay.anchor.x = 0.5; this.scoreDisplay.anchor.y = 1; this.timer = DECAY_TIME; this.active = true; } this.disappear = function() { if(!this.active) return; this.active = false; this.alpha =0; } this.update = function (delta) { if(!this.active) return false; this.timer -= delta; this.alpha = this.timer / DECAY_TIME; this.scoreDisplay.y -= delta * FLOAT_SPEED; if (this.timer <= 0) { this.disappear(); return true; } return false; } } EHDI.components.ScoreEffect.prototype = Object.create(EHDI.aka.Container.prototype); EHDI.components.ScoreEffectManager = function() { this.init = function(cont) { this.container = cont; this.scoreEffects = []; this.effectPool = new Pool(EHDI.components.ScoreEffect, 5); this.enabled = true; } this.popScore = function(x,y,score) { if(!this.enabled) return; var effect = this.effectPool.takeFromPool(); effect.appear(score); effect.x = x; effect.y = y; this.scoreEffects.push(effect); this.container.addChild(effect); } this.hideScores = function() { this.enabled = false; for(var i= 0, l = this.scoreEffects.length; i 0) { var toReturn = []; for(var i = 0, l = this.scoreEffects.length; i 10 && this.isRed) { this.isRed = false; this.timerTxt.style = {fontFamily:'proximanova-black', fill: 0xFFFFFF, fontSize: 36}; if(this.shakeTimeline) { this.shakeTimeline.kill(); this.shakeTimeline = null; } } else if(this.timeLeft < 10 && !this.isRed) { this.isRed = true; this.timerTxt.style = {fontFamily:'proximanova-black', fill: 0xED1C24, fontSize: 36}; this.shakeTimeline = new TimelineMax({repeat : -1}); this.shakeTimeline.to(this.timerTxt, 0.05, {x : this.containerSprite.width * 0.69, ease : Power0.easeNone}); this.shakeTimeline.to(this.timerTxt, 0.1, {x : this.containerSprite.width * 0.66, ease : Power0.easeNone}); this.shakeTimeline.to(this.timerTxt, 0.05, {x : this.containerSprite.width * 0.675, ease : Power0.easeNone}); } else if(this.timeLeft <= 1) { // 0) { if(this.shakeTimeline) this.shakeTimeline.kill(); EHDI.GAME.updateManager.removeFrameListener(this.timerUpdate); if(this.onTimerDone != null) this.onTimerDone(); } }; EHDI.components.Timer.prototype.addTime = function(timeToAdd) { this.timeLeft += timeToAdd; this.onTimeTimeline.restart(); this.onTimeTimeline.play(); }; EHDI.components.Timer.prototype.dispose = function() { if(this.shakeTimeline) this.shakeTimeline.kill(); EHDI.GAME.updateManager.removeFrameListener(this.timerUpdate); }; EHDI.components.Timer.prototype.toggleEffects = function(bool) { this.line.visible = bool; this.sparkle.visible = bool; }; EHDI.components.Timer.prototype.toggleFlash = function(bool) { this.flash.visible = bool; }; EHDI.components.Timer.prototype.setTimerDoneCallback = function(cb) { this.onTimerDone = cb; }; var EHDI = EHDI || Object.create(null); var WTE = WTE || Object.create(null); var UTILS = UTILS || Object.create(null); var POOLS = POOLS || Object.create(null); WTE.Animal = function() { EHDI.aka.Container.call(this); var MINIMUM_VISIBLE_TIME = 3500; var ENTRY_TIME = 500; var EXIT_TIME = 500;//250; var EASY_TIME_OFFSET = 3000; this.init = function (type, gameTimeFactor, isEasySpawn) { if(!this.sprite) this.sprite = new EHDI.aka.Sprite(); else this.sprite.removeChildren(); this.sprite.scale.x = 1; this.sprite.y =0; this.sprite.x =0; if(!this.glowContainer) { this.glowContainer = new EHDI.aka.Sprite(); this.glowContainer.y = 35; } this.glowContainer.visible = false; this.sprite.addChild(this.glowContainer); this.type =type; //int value var animalData = WTE.AnimalMap[type] this.validCage = animalData.validCage; this.spriteXOffset = animalData.xOffset; this.spriteYOffset = animalData.yOffset; this.entryAnimIndex = animalData.entryIndex; this.idleAnimIndex = animalData.idleIndex; this.exitAnimIndex = animalData.exitIndex; this.selectedAnimIndex = animalData.selectedIndex; this.classification = animalData.classification; var minimumTime = MINIMUM_VISIBLE_TIME - gameTimeFactor; this.activeTime = minimumTime + (Math.random() * minimumTime); if(isEasySpawn) this.activeTime += EASY_TIME_OFFSET; this.timer =0; this.isOut = false; this.hasFled = false; this.isChosen = false; this.cageNumber= -1; this.isToDisappear = false; this.isExiting = false; this.speed = 0; this.eventTimer = 0; this.isMatched = false; this.isMismatched = false; this.onEventTimerComplete = null; this.setVisual(); } this.dispose = function() { this.sprite.removeChildren(); this.sprite.scale.x = 1; this.sprite.y =0; this.sprite.x =0; this.sprite.rotation = 0; this.glowContainer.visible = false; } var sparkleAnimationName = "fx_sparkle"; this.setVisual = function() { if(this.children.indexOf(this.sprite) == -1) this.addChild(this.sprite); this.armature = EHDI.DBoneFactory.createArmature(this.type+"_armature"); this.animationSprite = this.armature.getDisplay(); this.animList = this.armature.animation.animationList; var animLoopCount =0; if((this.classification == 'prowl') || (this.classification == 'bush')) animLoopCount =1; this.armature.animation.gotoAndPlay(this.animList[this.entryAnimIndex], -1, -1, animLoopCount); this.sparkleArmature = EHDI.DBoneFactory.createArmature("sparkle_armature"); this.sparkleAnimationSprite = this.sparkleArmature.getDisplay(); // this.animDataList = this.armature.animation.animationDataList; // this.armature.animation.gotoAndStop(this.animList[0], this.animDataList[0].duration * 0.001 - 0.001); // this.animationSprite.position.set(this.animationSprite.width * 0.5, this.animationSprite.height * 0.5); } this.removeVisuals = function() { this.sprite.removeChildren(); EHDI.DBoneFactory.destroyArmature(this.armature); } this.spawn = function() { } this.setGlow = function(type) { var color= 'white'; if (type == null) color= 'white'; else if(type == 0) color= 'red'; else color= 'yellow'; var glowId = 'fx_glow_'+color; if((this.classification == 'prowl') || (this.classification == 'bush')) glowId = glowId+"2"; this.glowContainer.texture =EHDI.Assets.images[glowId]; this.glowContainer.anchor.set(0.5, 1); this.glowContainer.visible = true; } this.fadeGlow = function() { this.glowContainer.visible = false; } this.toIdle = function() { } this.exit = function() { if(this.isExiting) return; this.sprite.scale.x = -1; this.isExiting = true; if((this.classification != 'prowl') && (this.classification != 'bush')) this.speed = exitSpeed; else this.speed = 0; this.eventTimer = EXIT_TIME; this.onEventTimerComplete = this.run; var animLoopCount =0; if((this.classification == 'prowl') || (this.classification == 'bush')) animLoopCount =1; this.armature.animation.gotoAndPlay(this.animList[this.exitAnimIndex], -1, -1, animLoopCount); } this.run = function() { if(!this.isOut) return; this.disappear(); this.hasFled = true; this.isChosen = false; this.onEventTimerComplete = null; } this.update = function(delta) { // if((this.isMismatched) || (this.isMatched)) // { // this.sprite.alpha -= (delta * (1/EXIT_TIME)); // if(this.isMismatched) // { // this.sprite.y -= (delta * (250/EXIT_TIME)); // } // if(this.sprite.alpha < 0) // this.wasMatched(); // return; // } if(this.speed != 0) this.sprite.x += delta * this.speed; this.timer += delta; if(this.eventTimer > 0) { this.eventTimer -= delta; if(this.eventTimer <= 0) { if(this.onEventTimerComplete != null) this.onEventTimerComplete(); } } // var remainingTime = this.activeTime - this.timer; // if(remainingTime <= EXIT_TIME) // { // if(!this.isExiting) // this.exit(); // if(remainingTime <= 0) // { // if(this.isOut) // { // this.run(); // return false; // } // } // } if(this.hasFled) return false; return true; } var entrySpeed = 50/ ENTRY_TIME; var exitSpeed = (50/EXIT_TIME) * -1; this.appear = function() { this.isOut = true; this.sprite.addChild(this.animationSprite); this.addInteraction(); this.entryTimer =0; this.eventTimer = ENTRY_TIME; if((this.classification != 'prowl') && (this.classification != 'bush')) { this.sprite.x = -50+this.spriteXOffset; this.speed = entrySpeed; } else { this.sprite.x = this.spriteXOffset; this.speed = 0; } this.sprite.y = this.spriteYOffset; this.onEventTimerComplete = this.hasAppeared; } this.hasAppeared = function() { this.sprite.x =0 + this.spriteXOffset; this.speed = 0; this.armature.animation.gotoAndPlay(this.animList[this.idleAnimIndex], -1, -1, 0); this.eventTimer = this.activeTime - this.timer - EXIT_TIME; this.onEventTimerComplete = this.exit; } this.disappear = function () { this.isOut = false; this.isToDisappear = true; this.removeInteraction(); this.removeVisuals(); } this.match = function(isMatch, willExit) { if(isMatch) { this.isMatched = true; this.setGlow(1); this.armature.animation.gotoAndPlay(this.animList[this.selectedAnimIndex], -1, -1, 1); this.sparkleAnimationSprite.y = -100; this.sprite.addChild(this.sparkleAnimationSprite); this.sparkleArmature.animation.gotoAndPlay(sparkleAnimationName, -1, -1, 1); this.speed = 0; this.eventTimer = EXIT_TIME; this.onEventTimerComplete = this.wasMatched; } else { // this.isMismatched = true; // this.armature.animation.gotoAndPlay(this.animList[1], -1, -1, 0); if(willExit) { this.setGlow(0); this.exit(); } } if(willExit) { this.isChosen = false; this.removeInteraction(); } } this.wasMatched = function () { this.isToDisappear = true; this.disappear(); this.onEventTimerComplete = null; } this.addInteraction = function() { if(EHDI.BrowserInfo.isMobileDevice) this.on('touchstart', this.touched); else this.on('mousedown', this.touched); this.interactive = true; } this.removeInteraction = function() { if(EHDI.BrowserInfo.isMobileDevice) this.off('touchstart', this.touched); else this.off('mousedown', this.touched); this.interactive = false; } this.touched = function() { if(!this.hasFled) this.isChosen = true; this.armature.animation.gotoAndPlay(this.animList[this.selectedAnimIndex], -1, -1, 1); } this.untouch = function() { if((!this.isChosen) || (this.hasFled)) returm; this.armature.animation.gotoAndPlay(this.animList[this.idleAnimIndex], -1, -1, 0); this.isChosen = false; this.fadeGlow(); } this.makeSound = function() { EHDI.GAME.soundManager.playSFX(this.type); } } WTE.Animal.prototype = Object.create(EHDI.aka.Container.prototype); WTE.AnimalKeeper = function () { var ACTIVE_COUNT = 4; var speciesList = WTE.AnimalMap['specieslist']; var bigspeciesList = WTE.AnimalMap['bigspecieslist']; var prowlspeciesList = WTE.AnimalMap['prowlspecieslist']; var bushspeciesList = WTE.AnimalMap['bushspecieslist']; var animalRoster = []; var animalBench =[]; this.init = function() { UTILS.arrayUtils.shuffleArray(speciesList, 30); UTILS.arrayUtils.shuffleArray(bigspeciesList, 10); UTILS.arrayUtils.shuffleArray(prowlspeciesList, 10); UTILS.arrayUtils.shuffleArray(bushspeciesList, 10); for (var i = 0, l= speciesList.length, lim = ACTIVE_COUNT-2; (i 0) this.returnAnimal(animalBench.pop(), true); } else animalBench.push(animal); } } var EHDI = EHDI || Object.create(null); var WTE = WTE || Object.create(null); WTE.AnimalMap = Object.create(null); WTE.AnimalMap.init = Function() { WTE.AnimalMap['specieslist'] = specieslist = ['lamb', 'goat', 'donkey', 'deer', 'ram', 'gazelle']; WTE.AnimalMap['bigspecieslist'] = bigspecieslist = ['elephant', 'rhino', 'horse', 'giraffe']; WTE.AnimalMap['prowlspecieslist'] = prowlspecieslist = ['lion', 'tiger', 'bear']; WTE.AnimalMap['bushspecieslist'] = bushspecieslist = ['sloth', 'monkey']; initializeAnimal = function(species, type) { var cage; var entry; var idle; var exit; var selected; var x = 0; var y = 0; switch(type) { case 'normal': cage=[2,3,4,5]; // cage=[0,1,2,3,4,5]; entry = 1; idle = 0; exit = 1; selected = 2; break; case 'big': cage=[6,7]; entry = 1; idle = 0; exit = 1; selected = 2; break; case 'prowl': cage=[4,5]; entry = 0; idle = 1; exit = 2; selected = 3; break; case 'bush': cage=[8,9]; entry = 0; idle = 1; exit = 2; selected = 3; break; } switch(species) { case 'lamb': x = 35; cage=[2,3,4,5]; break; case 'elephant': x = -100; break; case 'rhino': x = -70; break; case 'giraffe': x = -70; break; case 'horse': x = -20; break; case 'bear': x = -50; y = -100; break; case 'lion': x = -50; y = -100; break; case 'tiger': x = -50; y = -100; break; } return{ classification: type, validCage: cage, entryIndex: entry, idleIndex: idle, exitIndex: exit, selectedIndex:selected, xOffset: x, yOffset: y }; } for(var i = 0, l = specieslist.length; i= EHDI.GAME.constants['fruitDecayTime']) this.rot(); if(this.glow) this.glow.update(delta); if(!this.isRipe) { var scale = this.timer/GROWTH_TIME; if(scale >= 1) { scale = 1; this.spawn(); } this.sprite.scale.x = this.sprite.scale.y =scale; } else if((this.isRotten) && (!this.fallen)) { this.yVel += delta * EHDI.GAME.constants.gravity; this.sprite.y += delta * this.yVel; this.sprite.alpha = (FALL_TIME- this.timer) / FALL_TIME; if(this.timer >= FALL_TIME) this.fallen = true; } } this.addInteraction = function() { if(EHDI.BrowserInfo.isMobileDevice) this.on('touchstart', this.touched); else this.on('mousedown', this.touched); this.interactive = true; } this.removeInteraction = function() { if(EHDI.BrowserInfo.isMobileDevice) this.off('touchstart', this.touched); else this.off('mousedown', this.touched); this.interactive = false; } this.touched = function() { if((!this.isRipe) || (this.isPicked) || (this.isRotten)) return; this.isPicked = true; EHDI.scene.GameScene.scoreHolder.addScore(SCORE_WORTH); EHDI.scene.GameScene.game.adjustTime(TIME_WORTH); EHDI.GAME.soundManager.playSFX("pick_fruit"); this.removeGlow(); // var basketLoc =this.toGlobal(new PIXI.Point(EHDI.scene.GameScene.game.x, EHDI.scene.GameScene.game.y)); // // var globalLoc =this.toGlobal(new PIXI.Point(basketLoc.x, basketLoc.y)); EHDI.scene.GameScene.game.fruitScoreEffects.popScore(this.x, this.y, 5); } } WTE.Fruit.prototype = Object.create(EHDI.aka.Container.prototype); WTE.FruitMap = Object.create(null); WTE.FruitMap['forbidden'] = 0; WTE.FruitMap['pomegranate'] =1; var EHDI = EHDI || Object.create(null); var WTE = WTE || Object.create(null); var UTILS = UTILS || Object.create(null); var POOLS = POOLS || Object.create(null); WTE.GameEngine = function() { var TIME_LIMIT = 90000; var EASY_DURATION = 45000; var SPAWN_DELAY = 400; var MAX_ANIMAL_COUNT = 10;//8;//6; var MAX_ACTIVE_ANIMAL =6; var POMEGRANATE_LIMIT = 3; var PAIR_SCORE = 2; var TUTORIAL_FRUIT_COUNT = 3; EHDI.aka.Container.call(this); var bg; var isOver; this.activeAnimals = []; this.vacantCages = []; this.alphaMale = null; var pauseBtn; this.init = function() { bg = new PIXI.extras.TilingSprite(EHDI.Assets.images["bg_eden"], EHDI.GAME.sceneManager.getStageWidth(), EHDI.GAME.sceneManager.getStageHeight()); this.addChild(bg); this.layers = []; this.cages =[]; this.generateLayers(); this.timer =0; this.spawnTimer = SPAWN_DELAY; this.tamer = new WTE.AnimalKeeper(); this.tamer.init(); this.spawnCounter = 0; this.fruitCounter = 0; this.fruits = []; EHDI.GAME.constants['fruitDecayTime'] = (SPAWN_DELAY * ((MAX_ANIMAL_COUNT * POMEGRANATE_LIMIT)-POMEGRANATE_LIMIT)); this.scoreEffects = new EHDI.components.ScoreEffectManager(); this.scoreEffects.init(this); this.pixiPt = new PIXI.Point(this.x, this.y); } this.generateLayers = function() { var gameWidth =EHDI.GAME.sceneManager.getStageWidth(); var yMarks = [400, 480, 555, 600];//[350, 450, 525, 600]; var cageY = [-50,-50,-50,-30,0,0 ,-25,-25, -50,-50]; var cageX = [400,640, 340,690, 250,825 ,410,650, 94,950 ]; var depth =[0.75,0.75,0.875,0.875,1,1 ,1,1, 1,1 ];// [0.5,0.5,0.75,0.75,1,1 ,1,1 ]; for(var i = 0, l = yMarks.length; i< l; i++) { var layer = new EHDI.aka.Container(); layer.y = yMarks[i]; this.layers.push(layer); this.addChild(layer); } for(var j = 0; j< MAX_ANIMAL_COUNT; j++) { var cage = new WTE.Cage(); cage.init(depth[j]); cage.x = cageX[j]; cage.y = cageY[j]; this.cages.push(cage); this.vacantCages.push(j); } var cageCounter =0; var placeCage = function(cages, flipSide, scale) { if(cageCounter >= MAX_ANIMAL_COUNT) cageCounter = MAX_ANIMAL_COUNT - 1; var cage = cages[cageCounter]; cage.isFlipped = flipSide; cageCounter++; return cage; } var layer0Elem = new EHDI.aka.Sprite(EHDI.Assets.images['eden_prop6']); layer0Elem.x = (gameWidth - layer0Elem.width) * 0.5; layer0Elem.y = layer0Elem.height * -1; this.layers[1].addChild(placeCage(this.cages)); this.layers[1].addChild(placeCage(this.cages, true)); this.layers[1].addChild(layer0Elem); var layer1Elem0 = new EHDI.aka.Sprite(EHDI.Assets.images['eden_prop3']); layer1Elem0.x = -52; layer1Elem0.y = (layer1Elem0.height * -1); var layer1Elem1 = new EHDI.aka.Sprite(EHDI.Assets.images['eden_prop4']); layer1Elem1.x = 180; layer1Elem1.y = (layer1Elem1.height * -1) - 20; var layer1Elem2 = new EHDI.aka.Sprite(EHDI.Assets.images['eden_prop5']); layer1Elem2.x = 550; layer1Elem2.y = (layer1Elem2.height * -1) + 20; var layer1Elem3 = new EHDI.aka.Sprite(EHDI.Assets.images['eden_prop3']); layer1Elem3.x = 724; layer1Elem3.y = (layer1Elem3.height * -1) +10; this.layers[2].addChild(placeCage(this.cages)); this.layers[2].addChild(layer1Elem1); this.layers[2].addChild(layer1Elem0); this.layers[2].addChild(placeCage(this.cages, true)); this.layers[2].addChild(layer1Elem3); this.layers[2].addChild(layer1Elem2); var layer2Elem0 = new EHDI.aka.Sprite(EHDI.Assets.images['eden_prop1']); layer2Elem0.x = -150; layer2Elem0.y = (layer2Elem0.height * -1) + 95; var layer2Elem1 = new EHDI.aka.Sprite(EHDI.Assets.images['eden_prop1']); layer2Elem1.x = 734; layer2Elem1.y = (layer2Elem1.height * -1) + 90; var layer2Elem2 = new EHDI.aka.Sprite(EHDI.Assets.images['eden_prop2']); layer2Elem2.x = 369; layer2Elem2.y = (layer2Elem2.height * -1); this.layers[3].addChild(placeCage(this.cages)); this.layers[3].addChild(layer2Elem0); this.layers[3].addChild(placeCage(this.cages, true)); this.layers[3].addChild(layer2Elem1); this.layers[3].addChild(layer2Elem2); this.layers[0].addChild(placeCage(this.cages)); this.layers[0].addChild(placeCage(this.cages, true)); this.layers[3].addChild(placeCage(this.cages)); this.layers[3].addChild(placeCage(this.cages, true)); this.fruitBasket = new EHDI.aka.Container(); this.fruitBasket.y = -370; this.layers[1].addChild(this.fruitBasket); // var testRect = new PIXI.Graphics(); // testRect.beginFill(0xFF0000); // testRect.drawRect(750,0, 250, 75); // testRect.endFill(); // this.fruitBasket.addChild(testRect); this.fruitScoreEffects = new EHDI.components.ScoreEffectManager(); this.fruitScoreEffects.init( this.fruitBasket); } this.gameStart = function() { scoreHolder = EHDI.scene.GameScene.scoreHolder; pauseBtn =EHDI.GAME.pauseButton; isOver = false; this.bindedLoop = gameUpdate.bind(this); EHDI.GAME.updateManager.addFrameListener(this.bindedLoop); } gameUpdate= function(delta) { if(pauseBtn.isPaused) { return; } this.timer += delta; if((this.timer >= TIME_LIMIT) || (isOver)) { this.gameOver(); return; } dragonBones.WorldClock.clock.advanceTime(delta * 0.001); this.spawnTimer -= delta; if(this.spawnTimer<= 0) this.spawnAnimals(); if(this.fruits.length > 0) { var pickedFruits = []; for(var i = 0, l = this.fruits.length; i 0) { var escapee = []; for(var i = 0, l = this.activeAnimals.length; i EHDI.GAME.saveData.highScore) { EHDI.GAME.saveData.highScore = score; EHDI.sbGame.saveGameData(EHDI.GAME.saveData, "DEFAULT", function(){ console.log("data saved."); }); } EHDI.sbGame.end(score); } this.removeGameLoop = function() { EHDI.GAME.updateManager.removeFrameListener(this.bindedLoop); } checkPair = function(animal1, animal2) { return (animal1.type == animal2.type); } getCageCandidates = function(vacant, valid) { var candidates =[]; for(var i = 0, l = valid.length; i= MAX_ACTIVE_ANIMAL) || (this.vacantCages.length <= 0)) return; this.spawnTimer = SPAWN_DELAY; var timeFactor = this.timer * timeFactorConverter; var animal; var cageCandidates; var easySpawn = (this.timer <= EASY_DURATION); do { animal= POOLS.animPool.takeFromPool(); animal.init(this.tamer.releaseAnimal(), timeFactor, easySpawn); cageCandidates = getCageCandidates(this.vacantCages, animal.validCage); if(cageCandidates.length < 1) { this.tamer.returnAnimal(animal.type, false); POOLS.animPool.returnBatch(null, [animal]); } }while(cageCandidates.length < 1); var cageIndex= UTILS.arrayUtils.getRandom(cageCandidates, true); this.cages[cageIndex].addAnimal(animal); /* if(animal.classification == "bush") { console.log(this.cages[cageIndex].x, this.cages[cageIndex].y) }*/ UTILS.arrayUtils.removeFromArray(this.vacantCages, [cageIndex]); animal.cageNumber = cageIndex; animal.appear(); this.activeAnimals.push(animal); this.spawnCounter++; if(this.spawnCounter >= 6) { this.spawnCounter = 0; this.growFruit(); } } this.releaseAnimal = function (animal, toRoster) { this.tamer.returnAnimal(animal.type, toRoster); this.cages[animal.cageNumber].releaseAnimal(); this.vacantCages.push(animal.cageNumber); } var fruitXSpawn = [50,100, 150, 200, 250, 750, 800, 850, 900, 950, 1000]; var basketHeight= 75; this.growFruit = function() { // var basketWidth= [200]; var fruit = POOLS.fruitPool.takeFromPool(); fruit.init((this.fruitCounter < TUTORIAL_FRUIT_COUNT)); do { fruit.x = fruitXSpawn[Math.floor(Math.random() * fruitXSpawn.length)]; }while(this.checkFruitX(fruit.x)); // fruit.x = fruitXSpawn[Math.floor(Math.random() * fruitXSpawn.length)]; fruit.y = Math.random() * basketHeight; this.fruitBasket.addChild(fruit); this.fruits.push(fruit); this.fruitCounter++; } this.checkFruitX = function(xTemp) { if((this.fruits == null) || (this.fruits.length <1)) return false; for(var i = 0, l = this.fruits.length; i 3) rating =3; return rating; } } WTE.GameEngine.prototype = Object.create(EHDI.aka.Container.prototype); POOLS.animPool = new Pool(WTE.Animal, 5); POOLS.fruitPool = new Pool(WTE.Fruit, 2); var EHDI = EHDI || Object.create(null); EHDI.loadScene = function setupLoader() { var loaderContainer = new PIXI.Container(); EHDI.GAME.jsonManager = EHDI.JSONManager(null, EHDI.Assets.fetch("assets/preload/strings/strings.json")); var proximanova = new EHDI.aka.PixiText("hello world", {fontFamily: 'proximanova-black'}); var exo = new EHDI.aka.PixiText("hello world", {fontFamily: 'Exo-Bold'}); loaderContainer.addChild(proximanova); loaderContainer.addChild(exo); /* window.addEventListener('screenDidAppear', function() { console.log("screen is now visible"); }); window.addEventListener('screenDidDisappear', destroy);*/ //load config //initialize the json files to be managed // console.log(EHDI.Assets.images["gfx_bg"]); var bg = new PIXI.extras.TilingSprite(EHDI.Assets.images["gfx_bg"], EHDI.GAME.sceneManager.getStageWidth(), EHDI.GAME.sceneManager.getStageHeight()); //var bg = new EHDI.displays.FillRectangle(0xFF7874, 0, 0, EHDI.GAME.sceneManager.getStageWidth(), EHDI.GAME.sceneManager.getStageHeight()); loaderContainer.addChild(bg); var loadingBorder = new EHDI.aka.Sprite(EHDI.Assets.images["gfx_loading"]); loadingBorder.anchor.x = 0.5; loadingBorder.anchor.y = 0.5; loadingBorder.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.5, EHDI.GAME.sceneManager.getStageHeight() * 0.5); loaderContainer.addChild(loadingBorder); var loadingBarBorder = new EHDI.aka.Sprite(EHDI.Assets.images["gfx_loading_bar_con"]); loadingBarBorder.anchor.set(0.5, 0.5); loadingBarBorder.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.5, EHDI.GAME.sceneManager.getStageHeight() * 0.64); loaderContainer.addChild(loadingBarBorder); var loadingStyle = EHDI.GAME.jsonManager.getLocale("STR_LOADING"); var loadingText = new EHDI.displays.TextSprite(loadingStyle); loadingText.style = loadingStyle.STYLE; loadingText.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.316, EHDI.GAME.sceneManager.getStageHeight() * 0.595); loaderContainer.addChild(loadingText); var loadingContainer = new EHDI.displays.FillRectangle(0x000000, 0, 0, 380, 27); loadingContainer.anchor.x = 0.5; loadingContainer.anchor.y = 0.5; loadingContainer.position.x = EHDI.GAME.sceneManager.getStageWidth() * 0.5; loadingContainer.position.y = EHDI.GAME.sceneManager.getStageHeight() * 0.65; loaderContainer.addChild(loadingContainer); var loadingBar = new EHDI.displays.FillRectangle(0x1999F1, 0, 0, 380, 27); loadingContainer.addChild(loadingBar); loadingBar.x = -loadingContainer.width * 0.5; loadingBar.y = -loadingContainer.height * 0.5; var loadingWidth = loadingBar.width; var tapAnywhere = null; var tapAnywhereTimeline = null; // EHDI.LoadManager.queueStrings(AssetDirectory.string); EHDI.LoadManager.queueAssets(AssetDirectory.load); EHDI.LoadManager.start(startGame); EHDI.GAME.updateManager.addFrameListener(update); var dbFactory = new dragonBones.PixiFactory(); // var textureImage = EHDI.Assets.images["gizmoloading_tex"].baseTexture.source; // var textureData = EHDI.Assets.fetch("gizmoloading_tex"); // dbFactory.addTextureAtlas(new dragonBones.TextureAtlas(textureImage, textureData)); // var skeleton = EHDI.Assets.fetch("gizmoloading_ske"); // dbFactory.addDragonBonesData(dragonBones.DataParser.parseDragonBonesData(skeleton)); // var armature = dbFactory.buildArmature(skeleton.armature[0].name); // dragonBones.WorldClock.clock.add(armature); // armature.animation.gotoAndPlay(armature.animation.animationList[0], -1, -1, 0); // armature.animation.play(); // var animationSprite = armature.getDisplay();; // animationSprite.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.5, EHDI.GAME.sceneManager.getStageHeight() * 0.55); EHDI.DBoneFactory.start("gizmoloading_tex","gizmoloading_tex","gizmoloading_ske"); var armature = EHDI.DBoneFactory.createArmature("Gizmo"); dragonBones.WorldClock.clock.add(armature); armature.animation.gotoAndPlay(armature.animation.animationList[0], -1, -1, 0); armature.animation.play(); var animationSprite = armature.getDisplay();; animationSprite.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.5, EHDI.GAME.sceneManager.getStageHeight() * 0.55); loaderContainer.addChild(animationSprite); // EHDI.GAME.updateManager.addFrameListener(updateAnimationClock); // function updateAnimationClock(dt) { // dragonBones.WorldClock.clock.advanceTime(dt * 0.001); // } function update() { //console.log(EHDI.GAME.loader.getProgress()); loadingBar.scale.x = EHDI.LoadManager.getProgress() / 100; }; function startGame() { loadingBar.scale.x = EHDI.LoadManager.getProgress() / 100; EHDI.GAME.updateManager.removeFrameListener(update); var speciesList = ['goat','donkey', 'deer','ram','horse','gazelle', 'elephant','rhino','giraffe', 'monkeyslothlamb', 'beartigerlion']; for (var i = 0, l= speciesList.length; i this.maxPages) this.pageNumber = 1; var htpImg = new EHDI.aka.Sprite(EHDI.Assets.images[this.filePaths[this.pageNumber - 1]]); htpImg.anchor.set(0.5, 0.5); htpImg.position.set(0, -this.bg.height * 0.15); this.upcomingPage.addChild(htpImg); var myText = this.messages[this.pageNumber -1]; var htpTxt = new EHDI.displays.TextSprite(this.messages[this.pageNumber -1]); htpTxt.style.wordWrap = true; htpTxt.style.wordWrapWidth = htpImg.width * 0.9; htpTxt.anchor.set(0.5, 0); htpTxt.position.set(0, this.bg.height * 0.05); this.upcomingPage.addChild(htpTxt); this.transitionTimeline = new TimelineMax(); this.transitionTimeline.to(this.upcomingPage, 0.5, {alpha : 1}); this.transitionTimeline.to(this.page, 0.5, {alpha : 0}, 0); this.transitionTimeline.add(this.endTransition.bind(this)); this.bg.addChild(this.upcomingPage); } EHDI.popup.PausePopUp.prototype.endTransition = function() { this.page.destroy({children: true}); this.page = this.upcomingPage; this.upcomingPage = null; this.page.alpa = 1; }; var EHDI = EHDI || Object.create(null); var WTE = WTE || Object.create(null); EHDI.scene.GameScene = function() { EHDI.aka.Container.call(this); EHDI.scene.GameScene.game = new WTE.GameEngine(); EHDI.scene.GameScene.timer = new EHDI.components.Timer(); EHDI.scene.GameScene.timer.timeLeft =EHDI.GAME.constants.gametimelimit / 1000; EHDI.scene.GameScene.timer.x = 280; EHDI.scene.GameScene.timer.y = 5; EHDI.GAME.pauseButton = new EHDI.components.pauseButton(); } EHDI.scene.GameScene.prototype = Object.create(EHDI.aka.Container.prototype); EHDI.scene.GameScene.prototype.screenWillAppear = function() { EHDI.scene.GameScene.game.init(); this.addChild(EHDI.scene.GameScene.game); EHDI.scene.GameScene.scoreHolder = EHDI.components.ScoreManager(this); EHDI.scene.GameScene.scoreHolder.setXY(10,5); this.addChild( EHDI.scene.GameScene.timer); this.addChild(EHDI.GAME.pauseButton); }; EHDI.scene.GameScene.prototype.screenDidAppear = function() { EHDI.DBoneFactory.enableClock = false; EHDI.scene.GameScene.game.gameStart(); var cache = EHDI.GAME.saveData; if(cache.isFirstTimePlay) { cache.isFirstTimePlay = false; EHDI.sbGame.saveGameData(EHDI.GAME.saveData, "DEFAULT", function(){ console.log("data saved."); }); EHDI.GAME.pauseButton.isPaused = true; EHDI.GAME.sceneManager.pushPopUp(new EHDI.popup.PausePopUp(), {y : new EHDI.scene.TransitionParameter(-EHDI.GAME.sceneManager.getStageHeight(), EHDI.GAME.sceneManager.getStageHeight() * 0.5), duration : 0.25}); } }; EHDI.scene.GameScene.prototype.screenDidDisappear = function() { //this.destroy({children: true}); EHDI.scene.GameScene.game.removeGameLoop(); EHDI.scene.GameScene.timer.dispose(); EHDI.scene.GameScene.timer = null; delete this; EHDI.DBoneFactory.enableClock = true; } var EHDI = EHDI || Object.create(null); EHDI.scene = EHDI.scene || Object.create(null); EHDI.scene.TitleScene = function() { EHDI.aka.Container.call(this); } EHDI.scene.TitleScene.prototype = Object.create(EHDI.aka.Container.prototype); EHDI.scene.TitleScene.prototype.screenWillAppear = function() { var bg = new PIXI.extras.TilingSprite(EHDI.Assets.images["bg_logo_eden"], EHDI.GAME.sceneManager.getStageWidth(), EHDI.GAME.sceneManager.getStageHeight()); this.addChild(bg); }; EHDI.scene.TitleScene.prototype.screenDidAppear = function() { // this.title = new EHDI.aka.PixiText("The Weeds Among The Grass", {fontFamily: 'Exo-Bold', fill: 0xFFFFFF, fontSize : 50}); this.title = new EHDI.aka.Sprite(EHDI.Assets.images['logo_eden1']); this.title.anchor.set(0.5, 0.5); this.title.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.5, EHDI.GAME.sceneManager.getStageHeight() * 0.5); this.spark = new EHDI.aka.Sprite(EHDI.Assets.images['logo_eden2']); this.spark.anchor.set(0.5, 0.5); this.spark.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.5, EHDI.GAME.sceneManager.getStageHeight() * 0.5); this.spark.alpha =0; this.gizmo =new EHDI.aka.Sprite(EHDI.Assets.images['gizmo_eden']); this.gizmo.anchor.set(0.5, 0.75); this.gizmo.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.5, EHDI.GAME.sceneManager.getStageHeight() * 0.45); this.addChild(this.spark); this.addChild(this.gizmo); this.addChild(this.title); this.sound = new EHDI.displays.ToggleButton(EHDI.Assets.images["btn_audio1"], EHDI.Assets.images["btn_audio3"], EHDI.Assets.images["btn_audio2"], EHDI.Assets.images["btn_audio4"], EHDI.GAME.soundManager.getMuted()); this.sound.setOnClickFunction(this.toggleAudio); this.sound.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.1, EHDI.GAME.sceneManager.getStageHeight() * 0.09); this.addChild(this.sound); this.highScoreHolder = new EHDI.components.HighScoreHolder(this, EHDI.GAME.saveData.highScore); this.highScoreHolder.setXY(EHDI.GAME.sceneManager.getStageWidth() * 0.723, EHDI.GAME.sceneManager.getStageHeight() * 0.0417); this.playBtn = new EHDI.displays.Button(EHDI.Assets.images["btn_play"], EHDI.Assets.images["btn_play2"], null, null); this.playBtn.position.set(EHDI.GAME.sceneManager.getStageWidth() * 0.5, EHDI.GAME.sceneManager.getStageHeight() * 0.85); this.addChild(this.playBtn); this.playBtn.setOnClickFunction(this.startGame); this.playTxt = new EHDI.displays.TextSprite(EHDI.GAME.jsonManager.getLocale("BTN_PLAY")); this.playTxt.anchor.set(0.75, 0.5); this.playBtn.addChild(this.playTxt); var tlPhase2 = function() { this.tl.kill(); this.tl = null; this.tl2 = new TimelineMax({repeat: -1, yoyo:true}); this.tl2.from(this.spark, 2, {scaleX:0.5, scaleY:0.5,}); this.spark.alpha =1; } this.tl = new TimelineMax({repeat: 0}); this.tl.from(this.title, 1, {scaleX:0, scaleY:0, ease: Elastic.easeOut}); this.tl.from(this.gizmo, 0.5, {scaleX:0, scaleY:0, ease: Back.easeOut}); this.tl.from(this.playBtn, 0.25, {scaleX:0, scaleY:0, ease: Back.easeOut}); this.tl.add(tlPhase2.bind(this)); /* if(!EHDI.GAME.debugUtils) { EHDI.GAME.debugUtils = new EHDI.debugUtils.debugUtilsContainer("v0.3.6"); // EHDI.GAME.sceneManager.addNotification(EHDI.GAME.debugUtils); }*/ if(!EHDI.GAME.bgm) { EHDI.GAME.soundManager.autoResumeToggle(true); EHDI.GAME.bgm = EHDI.GAME.soundManager.playBGM("bgm", 0.75); } }; EHDI.scene.TitleScene.prototype.toggleAudio = function(enable) { EHDI.GAME.soundManager.setMute(enable); EHDI.GAME.soundManager.playSFX("button_sfx"); var cache = EHDI.GAME.storageManager.getLocalInfo(EHDI.GAME.id); cache.isMuted = enable; EHDI.GAME.storageManager.setLocalInfo(EHDI.GAME.id, cache); } EHDI.scene.TitleScene.prototype.startGame = function() { if(this.tl) { this.tl.kill(); this.tl = null; } if(this.tl2) { this.tl2.kill(); this.tl2 = null; } EHDI.GAME.soundManager.playSFX("button_sfx"); EHDI.GAME.sceneManager.changeScene(new EHDI.scene.GameScene(), {x : new EHDI.scene.TransitionParameter(-EHDI.GAME.sceneManager.getStageWidth(), 0), duration : 0.25}); }; EHDI.scene.TitleScene.prototype.screenDidDisappear = function() { this.tl2.kill(); this.tl2 = null; if(this.tl) { this.tl.kill(); this.tl = null; } this.destroy({children: true}); // delete this; } EHDI.onWindowLoad = function() { //This will hold all global variables for the game as property EHDI.GAME = Object.create(null); EHDI.GAME.id = gameId;//'13062766'; EHDI.GAME.language = "en"; EHDI.GAME.constants = EHDI.GAME.constants || Object.create(null); Object.defineProperties(EHDI.GAME.constants, { 'boundHeight': {value: 600}, 'boundWidth': {value: 1024}, 'gametimelimit': {value: 90000}, 'gravity': {value:0.00098} } ); EHDI.GAME.constants['fruitDecayTime'] = 0; EHDI.sbGame = new SuperbookGame(EHDI.GAME.id, 'state', EHDI.init); EHDI.sbGame.renderGameArea(); var vendorGameElement = EHDI.sbGame.getVendorGameElement(); EHDI.canvas = document.createElement('canvas'); EHDI.canvas.id = "game-canvas"; EHDI.canvas.width = vendorGameElement.style.width; EHDI.canvas.height = vendorGameElement.style.height; vendorGameElement.appendChild(EHDI.canvas); EHDI.sbGame.start(); } EHDI.init = function init() { EHDI.GAME.sceneManager = EHDI.SceneManager(1024, 600); //EHDI.GAME.scaleManager = EHDI.ScaleManager(EHDI.GAME.sceneManager.getRenderer(), EHDI.GAME.sceneManager.getStage(), EHDI.ScaleManager.DOCKING.AUTO, EHDI.GAME.sceneManager.defaultWidth, EHDI.GAME.sceneManager.defaultHeight); //EHDI.GAME.scaleManager.addAutomaticScaling(); var sbResize = function() { var vendorGameElement = EHDI.sbGame.getVendorGameElement(); var width = EHDI.GAME.sceneManager.defaultWidth, height = EHDI.GAME.sceneManager.defaultHeight; var scaleX = vendorGameElement.offsetWidth / EHDI.GAME.sceneManager.defaultWidth, scaleY = vendorGameElement.offsetHeight / EHDI.GAME.sceneManager.defaultHeight, ratio = Math.min(scaleX, scaleY); width = Math.ceil(width * ratio); height = Math.ceil(height * ratio); var stage = EHDI.GAME.sceneManager.getStage(); stage.scale.x = stage.scale.y = ratio; EHDI.GAME.sceneManager.getRenderer().resize(width, height); var canvas = EHDI.GAME.sceneManager.getRenderer().view; canvas.style.paddingLeft = 0; canvas.style.paddingRight = 0; canvas.style.paddingTop = 0; canvas.style.paddingBottom = 0; canvas.style.display = "block"; canvas.style.position = "absolute"; canvas.style.top = 0; canvas.style.left = 0; canvas.style.right = 0; canvas.style.bottom = 0; if(width < vendorGameElement.offsetWidth) { var margin = (vendorGameElement.offsetWidth - width) / 2; canvas.style.left = margin + "px"; canvas.style.right = margin + "px"; } if(height < vendorGameElement.offsetHeight) { var margin = (vendorGameElement.offsetHeight - height) / 2; canvas.style.top = margin + "px"; canvas.style.bottom = margin + "px"; } window.scrollTo(0, 0); }; EHDI.sbGame.resizeCallback = sbResize; sbResize(); EHDI.GAME.storageManager = EHDI.StorageManager(); EHDI.GAME.updateManager = EHDI.UpdateManager(EHDI.GAME.sceneManager.getRenderer(), EHDI.GAME.sceneManager.getStage()); EHDI.GAME.soundManager = EHDI.SoundManager(true); var cache = EHDI.GAME.storageManager.getLocalInfo(EHDI.GAME.id) || {isMuted : false}; EHDI.GAME.storageManager.setLocalInfo(EHDI.GAME.id, cache); EHDI.GAME.soundManager.setMute(cache.isMuted); // console.log(AssetDirectory.preload); // EHDI.LoadManager.queueStrings(AssetDirectory.preloadString) var showLoadScene = function(){ EHDI.LoadManager.queueAssets(AssetDirectory.preload); var promises = []; this.fontObserve = []; for(var i = 0; i < EHDI.Assets.fonts.length;i++){ this.fontObserve[i] = new FontFaceObserver(EHDI.Assets.fonts[i]); promises.push(this.fontObserve[i].load(null,8000)); } Promise.all(promises) .then(function(){ EHDI.LoadManager.start(EHDI.loadScene); }); } EHDI.sbGame.loadGameData(undefined, //LOAD DATA SUCCESS function(data){ EHDI.GAME.saveData = (typeof data === 'object') ? data : {highScore: 0, isFirstTimePlay: true}; showLoadScene(); }, //LOAD DATA FAILED function(){ EHDI.GAME.saveData = {highScore: 0, isFirstTimePlay: true}; showLoadScene(); } ) } window.onload = EHDI.onWindowLoad; document.ontouchmove = function (e) { if(e !== undefined && e !== null) e.preventDefault(); window.scrollTo(0, 0); } /* Font Face Observer v2.0.13 - © Bram Stein. License: BSD-3-Clause */(function(){'use strict';var f,g=[];function l(a){g.push(a);1==g.length&&f()}function m(){for(;g.length;)g[0](),g.shift()}f=function(){setTimeout(m)};function n(a){this.a=p;this.b=void 0;this.f=[];var b=this;try{a(function(a){q(b,a)},function(a){r(b,a)})}catch(c){r(b,c)}}var p=2;function t(a){return new n(function(b,c){c(a)})}function u(a){return new n(function(b){b(a)})}function q(a,b){if(a.a==p){if(b==a)throw new TypeError;var c=!1;try{var d=b&&b.then;if(null!=b&&"object"==typeof b&&"function"==typeof d){d.call(b,function(b){c||q(a,b);c=!0},function(b){c||r(a,b);c=!0});return}}catch(e){c||r(a,e);return}a.a=0;a.b=b;v(a)}} function r(a,b){if(a.a==p){if(b==a)throw new TypeError;a.a=1;a.b=b;v(a)}}function v(a){l(function(){if(a.a!=p)for(;a.f.length;){var b=a.f.shift(),c=b[0],d=b[1],e=b[2],b=b[3];try{0==a.a?"function"==typeof c?e(c.call(void 0,a.b)):e(a.b):1==a.a&&("function"==typeof d?e(d.call(void 0,a.b)):b(a.b))}catch(h){b(h)}}})}n.prototype.g=function(a){return this.c(void 0,a)};n.prototype.c=function(a,b){var c=this;return new n(function(d,e){c.f.push([a,b,d,e]);v(c)})}; function w(a){return new n(function(b,c){function d(c){return function(d){h[c]=d;e+=1;e==a.length&&b(h)}}var e=0,h=[];0==a.length&&b(h);for(var k=0;kparseInt(a[1],10)}else C=!1;return C}function J(){null===F&&(F=!!document.fonts);return F} function K(){if(null===E){var a=document.createElement("div");try{a.style.font="condensed 100px sans-serif"}catch(b){}E=""!==a.style.font}return E}function L(a,b){return[a.style,a.weight,K()?a.stretch:"","100px",b].join(" ")} A.prototype.load=function(a,b){var c=this,k=a||"BESbswy",q=0,D=b||3E3,H=(new Date).getTime();return new Promise(function(a,b){if(J()&&!G()){var M=new Promise(function(a,b){function e(){(new Date).getTime()-H>=D?b():document.fonts.load(L(c,'"'+c.family+'"'),k).then(function(c){1<=c.length?a():setTimeout(e,25)},function(){b()})}e()}),N=new Promise(function(a,c){q=setTimeout(c,D)});Promise.race([N,M]).then(function(){clearTimeout(q);a(c)},function(){b(c)})}else m(function(){function u(){var b;if(b=-1!= f&&-1!=g||-1!=f&&-1!=h||-1!=g&&-1!=h)(b=f!=g&&f!=h&&g!=h)||(null===B&&(b=/AppleWebKit\/([0-9]+)(?:\.([0-9]+))/.exec(window.navigator.userAgent),B=!!b&&(536>parseInt(b[1],10)||536===parseInt(b[1],10)&&11>=parseInt(b[2],10))),b=B&&(f==v&&g==v&&h==v||f==w&&g==w&&h==w||f==x&&g==x&&h==x)),b=!b;b&&(d.parentNode&&d.parentNode.removeChild(d),clearTimeout(q),a(c))}function I(){if((new Date).getTime()-H>=D)d.parentNode&&d.parentNode.removeChild(d),b(c);else{var a=document.hidden;if(!0===a||void 0===a)f=e.a.offsetWidth, g=n.a.offsetWidth,h=p.a.offsetWidth,u();q=setTimeout(I,50)}}var e=new r(k),n=new r(k),p=new r(k),f=-1,g=-1,h=-1,v=-1,w=-1,x=-1,d=document.createElement("div");d.dir="ltr";t(e,L(c,"sans-serif"));t(n,L(c,"serif"));t(p,L(c,"monospace"));d.appendChild(e.a);d.appendChild(n.a);d.appendChild(p.a);document.body.appendChild(d);v=e.a.offsetWidth;w=n.a.offsetWidth;x=p.a.offsetWidth;I();z(e,function(a){f=a;u()});t(e,L(c,'"'+c.family+'",sans-serif'));z(n,function(a){g=a;u()});t(n,L(c,'"'+c.family+'",serif')); z(p,function(a){h=a;u()});t(p,L(c,'"'+c.family+'",monospace'))})})};"object"===typeof module?module.exports=A:(window.FontFaceObserver=A,window.FontFaceObserver.prototype.load=A.prototype.load);}()); var EHDI = (function(ehdi){ ehdi.DBoneFactory = (function(){ var _public = Object.create(null); var enableClock = true; var armatures = []; var skelData = Object.create(null); var loop = function(dt){ dragonBones.WorldClock.clock.advanceTime(dt * _public.dtMultiplier); } _public.dtMultiplier = 0.001; Object.defineProperty(_public, "enableClock", { set: function(val){ enableClock = val; if(enableClock && !EHDI.GAME.updateManager.hasFrameListener(loop)){ EHDI.GAME.updateManager.addFrameListener(loop); } if(!enableClock && EHDI.GAME.updateManager.hasFrameListener(loop)){ EHDI.GAME.updateManager.removeFrameListener(loop); } }, get: function(){ return enableClock; } }); _public.createArmature = function(name){ var newArmature = _public.PixiFactory.buildArmature(name); dragonBones.WorldClock.clock.add(newArmature); armatures.push(newArmature); return newArmature; } _public.destroyArmature = function(armature){ var index = armatures.indexOf(armature); if(index > -1){ var arm = armatures.splice(index, 1)[0]; dragonBones.WorldClock.clock.remove(arm); arm.dispose(); } } _public.destroyAllArmature = function(){ while(armatures.length > 0){ var arm = armatures.pop(); dragonBones.WorldClock.clock.remove(arm); arm.dispose(); } } /** * @param (STRING) imgID texture file(png) * @param (STRING) dataID string file(json) * @param (STRING) SkelID string file(json) */ _public.start = function(imgID, dataID, skelID){ _public.PixiFactory = new dragonBones.PixiFactory(); _public.addToFactory(imgID, dataID, skelID); _public.enableClock = true; } _public.addToFactory = function(imgID, dataID, skelID){ var textureImg = EHDI.Assets.images[imgID].baseTexture.source; var textureData = EHDI.Assets.fetch(dataID); var skel = EHDI.Assets.fetch(skelID); _public.PixiFactory.addTextureAtlas(new dragonBones.TextureAtlas(textureImg, textureData)); _public.PixiFactory.addDragonBonesData(dragonBones.DataParser.parseDragonBonesData(skel)); } return _public; }()); return ehdi; }(EHDI || Object.create(null))); var EHDI = EHDI || Object.create(null); EHDI.debugUtils = EHDI.debugUtils || Object.create(null); EHDI.debugUtils.debugUtilsContainer = function(version) { EHDI.aka.Container.call(this); var fpsDisplay = new EHDI.debugUtils.FPSDisplay(); fpsDisplay.anchor.y = 1; fpsDisplay.position.set(0, EHDI.GAME.sceneManager.getStageHeight()); this.addChild(fpsDisplay); var versionDisplay = new EHDI.aka.PixiText(version, {fontFamily: 'sans-serif', fill: 0xFFFFFF, dropShadow : true, fontSize: 32}); versionDisplay.anchor.x = 1; versionDisplay.anchor.y = 1; versionDisplay.position.set(EHDI.GAME.sceneManager.getStageWidth(), EHDI.GAME.sceneManager.getStageHeight()); this.addChild(versionDisplay); }; EHDI.debugUtils.debugUtilsContainer.prototype = Object.create(EHDI.aka.Container.prototype); EHDI.debugUtils.FPSDisplay = function() { this.fps = EHDI.GAME.updateManager.getFPS(); EHDI.aka.PixiText.call(this, "FPS : " + this.fps, {fontFamily: 'sans-serif', fill: 0xFFFFFF, dropShadow : true, fontSize: 32}); EHDI.GAME.updateManager.addFrameListener(this.updateMe.bind(this)); }; EHDI.debugUtils.FPSDisplay.prototype = Object.create(EHDI.aka.PixiText.prototype); EHDI.debugUtils.FPSDisplay.prototype.updateMe = function() { if(this.fps !== EHDI.GAME.updateManager.getFPS()) this.text = "FPS :" + EHDI.GAME.updateManager.getFPS(); }; var EHDI = EHDI || Object.create(null); EHDI.interactions = EHDI.interactions || Object.create(null); EHDI.interactions.Keyboard = function (keyCode) { var key = {}; key.code = keyCode; key.isDown = false; key.isUp = true; key.press = null; key.release = null; key.downHandler = function(event) { if(event.keyCode === key.code) { if (key.isUp && key.press) key.press(); key.isDown = true; key.isUp = false; } }; key.upHandler = function(event) { if(event.keyCode === key.code) { if(key.isDown && key.release) key.release(); key.isUp = true; key.isDown = false; } }; var downHandle = key.downHandler.bind(key), upHandle = key.upHandler.bind(key); window.addEventListener("keydown", downHandle, false); window.addEventListener("keyup", upHandle, false); key.dispose = function() { window.removeEventListener("keydown", downHandle); window.removeEventListener("keyup", upHandle); } return key; } EHDI.interactions.ArrowControl = function (sprite, speed) { if(typeof speed === undefined) throw new Error("Indicate speed in which you whant the sprite to move"); var upArrow = EHDI.interactions.Keyboard(38), rightArrow = EHDI.interactions.Keyboard(39), downArrow = EHDI.interactions.Keyboard(40), leftArrow = EHDI.interactions.Keyboard(37); leftArrow.press = function() { sprite.vx = -speed; } leftArrow.release = function() { if(!rightArrow.isDown) sprite.vx = 0; } rightArrow.press = function() { sprite.vx = speed; } rightArrow.release = function() { if(!leftArrow.isDown) sprite.vx = 0; } upArrow.press = function() { sprite.vy = -speed; } upArrow.release = function() { if(!downArrow.isDown) sprite.vy = 0; } downArrow.press = function() { sprite.vy = speed; } downArrow.release = function() { if(!upArrow.isDown) sprite.vy = 0; } }; var UTILS = UTILS || Object.create(null); UTILS.arrayUtils = UTILS.arrayUtils || Object.create(null); UTILS.arrayUtils.removeFromArray =function(source, toRemove) { if((source == null) || (toRemove == null)) return; while(toRemove.length > 0) { var item= toRemove.pop(); var itemIndex =source.indexOf(item); if(itemIndex != -1) source = source.splice(itemIndex, 1); } toRemove = null; } UTILS.arrayUtils.clearArray = function(source) { if(source == null) return; while(source.lenghth > 0) { source.pop(); } } UTILS.arrayUtils.destroyArray = function(source) { if(source == null) return; while(source.lenghth > 0) { var item = source.pop(); if(item.dispose != null) item.dispose(); if(item.destroy != null) item.destroy(); } source = null; } UTILS.arrayUtils.shuffleArray = function(source, complexityFactor) { if(source == null) return; if(typeof complexityFactor === 'number') complexityFactor = 100; for(var i = 0; i< complexityFactor; i++) { var item= UTILS.arrayUtils.getRandom(source, true); source.push(item); } } UTILS.arrayUtils.getRandom = function(source, remove) { if((source == null) || (source.lenghth <= 0)) return null; var item = source[Math.floor(Math.random() * source.length)]; if(remove) UTILS.arrayUtils.removeFromArray(source, [item]); return item; } UTILS.depthSwap = function(visualList) { visualList.sort(function(a,b) { a.y = a.y || 0; b.y = b.y || 0; return a.y - b.y; }); } UTILS.objectPools = UTILS.objectPools || Object.create(null); function Pool(obj, initialCount) { var objPool = []; var type = obj; while(objPool.length < initialCount) { var item = new type(); objPool.push(item); } this.takeFromPool = function() { if(objPool.length <= 0) { return new type(); } else { return objPool.pop(); } } this.returnBatch = function(source, toReturn) { if(toReturn == null) return; while(toReturn.length > 0) { var item= toReturn.pop(); if(source != null) { var itemIndex =source.indexOf(item); if(itemIndex != -1) source.splice(itemIndex, 1); } objPool.push(item); } toReturn = null; } this.returnToPool = function(item) { objPool.push(item); } this.clearPool = function() { UTILS.arrayUtils.clearArray(objPool); } this.destroyPool = function() { UTILS.arrayUtils.clearArray(destroyArray); objPool = null; type = null; } } //# sourceMappingURL=game.js.map