diff --git a/p5play.d.ts b/p5play.d.ts index d89dcd97..b9ef3a28 100644 --- a/p5play.d.ts +++ b/p5play.d.ts @@ -76,8 +76,20 @@ class Sprite { * * * The Sprite constructor can be used in many different ways. + * + * In fact it's so flexible that I've only listed out some of the + * most common ways it can be used in the examples section below. + * Try experimenting with it! It's likely to work the way you + * expect it to, if not you'll just get an error. + * + * Special feature! If the first parameter to this constructor is a + * loaded p5.Image, SpriteAnimation, or name of a SpriteAnimation, + * then the Sprite will be created with that animation. If the + * dimensions of the sprite are not given, then the Sprite will be + * created using the dimensions of the animation. + * * Every sprite you create is added to the `allSprites` - * group and put on the top layer, in front of all + * group and put on the top draw order layer, in front of all * previously created sprites. * * @param {Number} [x] - horizontal position of the sprite @@ -91,12 +103,14 @@ class Sprite { * 'static', 'kinematic', or 'none' * @example * - * let sprite = new Sprite(); + * let spr = new Sprite(); * * let rectangle = new Sprite(x, y, width, height); * * let circle = new Sprite(x, y, diameter); * + * let spr = new Sprite(aniName, x, y); + * * let line = new Sprite(x, y, [length, angle]); */ constructor(x?: number, y?: number, w?: number, h?: number, collider?: string, ...args: any[]); @@ -201,6 +215,12 @@ class Sprite { * @type {Number} */ get w(): number; + set h(arg: number); + /** + * The height of the sprite. + * @type {Number} + */ + get h(): number; /** * The sprite's position on the previous frame. * @type {object} @@ -757,12 +777,6 @@ class Sprite { * @type {Number} */ get halfWidth(): number; - set h(arg: number); - /** - * The height of the sprite. - * @type {Number} - */ - get h(): number; set hh(arg: number); /** * Half the height of the sprite. @@ -881,14 +895,22 @@ class Sprite { */ applyTorque(val: any): void; /** - * Moves a sprite towards a position. + * Moves a sprite towards a position at a percentage of the distance + * between itself and the destination. * - * @param {Number|Object} x|position destination x or any object with x and y properties - * @param {Number} y destination y - * @param {Number} tracking [optional] 1 represents 1:1 tracking, the mouse moves to the destination immediately, 0 represents no tracking. Default is 0.1 (10% tracking). + * @param {Number|Object} x destination x or any object with x and y properties + * @param {Number} [y] destination y + * @param {Number} [tracking] 1 represents 1:1 tracking, the mouse moves to the destination immediately, 0 represents no tracking. Default is 0.1 (10% tracking). */ - moveTowards(x: number | any, y: number, tracking: number): void; - moveAway(x: any, y: any, repel: any, ...args: any[]): void; + moveTowards(x: number | any, y?: number, tracking?: number): void; + /** + * Moves the sprite away from a position, the opposite of moveTowards, + * at a percentage of the distance between itself and the position. + * @param {Number} x + * @param {Number} [y] + * @param {Number} [repel] range from 0-1 + */ + moveAway(x: number, y?: number, repel?: number, ...args: any[]): void; /** * Move the sprite a certain distance from its current position. * @@ -1746,7 +1768,9 @@ class Group extends Array { /** */ moveTowards(x: any, y: any, tracking: any): void; - moveAway(x: any, y: any, tracking: any): void; + /** + */ + moveAway(x: any, y: any, repel: any): void; /** * Alias for group.length * @deprecated diff --git a/p5play.js b/p5play.js index 02434fbd..d037627f 100644 --- a/p5play.js +++ b/p5play.js @@ -179,8 +179,20 @@ p5.prototype.registerMethod('init', function p5playInit() { * * * The Sprite constructor can be used in many different ways. + * + * In fact it's so flexible that I've only listed out some of the + * most common ways it can be used in the examples section below. + * Try experimenting with it! It's likely to work the way you + * expect it to, if not you'll just get an error. + * + * Special feature! If the first parameter to this constructor is a + * loaded p5.Image, SpriteAnimation, or name of a SpriteAnimation, + * then the Sprite will be created with that animation. If the + * dimensions of the sprite are not given, then the Sprite will be + * created using the dimensions of the animation. + * * Every sprite you create is added to the `allSprites` - * group and put on the top layer, in front of all + * group and put on the top draw order layer, in front of all * previously created sprites. * * @param {Number} [x] - horizontal position of the sprite @@ -194,12 +206,14 @@ p5.prototype.registerMethod('init', function p5playInit() { * 'static', 'kinematic', or 'none' * @example * - * let sprite = new Sprite(); + * let spr = new Sprite(); * * let rectangle = new Sprite(x, y, width, height); * * let circle = new Sprite(x, y, diameter); * + * let spr = new Sprite(aniName, x, y); + * * let line = new Sprite(x, y, [length, angle]); */ constructor(x, y, w, h, collider) { @@ -244,30 +258,45 @@ p5.prototype.registerMethod('init', function p5playInit() { throw new FriendlyError('Sprite', 0, [args[0]]); } - x = args[0]; - y = args[1]; - w = args[2]; - h = args[3]; - collider = args[4]; - - if (Array.isArray(x)) { + if (!Array.isArray(args[0])) { + // valid use for creating a box collider: + // new Sprite(x, y, w, h, colliderType) + x = args[0]; + y = args[1]; + w = args[2]; + h = args[3]; + collider = args[4]; + } else { + // valid use for creating chain/polygon using vertex mode: + // new Sprite([[x1, y1], [x2, y2], ...], colliderType) x = undefined; y = undefined; w = args[0]; - h = args[1]; - collider = args[2]; + h = undefined; + collider = args[1]; + if (Array.isArray(collider)) { + throw new FriendlyError('Sprite', 1, [`[[${w}], [${h}]]`]); + } + } + + // valid use without setting size: + // new Sprite(x, y, colliderType) + if (typeof w == 'string') { + collider = w; + w = undefined; } - // valid use to create a circle: new Sprite(x, y, d, colliderType) if (typeof h == 'string') { if (isColliderType(h)) { + // valid use to create a circle: + // new Sprite(x, y, d, colliderType) collider = h; } else { + // valid use to create a regular polygon: + // new Sprite(x, y, sideLength, polygonName) w = getRegularPolygon(w, h); } h = undefined; - } else if (Array.isArray(h)) { - throw new FriendlyError('Sprite', 1, [`[[${w}], [${h}]]`]); } this.idNum = this.p.p5play.spritesCreated; diff --git a/p5play.min.js b/p5play.min.js index 0a228a3e..557e8020 100644 --- a/p5play.min.js +++ b/p5play.min.js @@ -4,4 +4,4 @@ * @author quinton-ashley * @license gpl-v3-only */ -p5.prototype.registerMethod("init",(function(){if(void 0===window.planck)throw"planck.js must be loaded before p5play";const t=this,e=planck,i=60;if(void 0===window._p5play_gtagged&&"undefined"==typeof process){let F=document.createElement("script");F.src="https://www.googletagmanager.com/gtag/js?id=G-EHXNCTSYLK",F.async=!0,document.head.append(F),window._p5play_gtagged=!0,F.onload=()=>{window.dataLayer??=[],window.gtag=function(){dataLayer.push(arguments)},gtag("js",new Date),gtag("config","G-EHXNCTSYLK"),gtag("event","p5play_v3_14")}}this.angleMode("degrees");const s=(t,s,r)=>new e.Vec2(t*r/i,s*r/i),r=(t,s,r)=>new e.Vec2(t/r*i,s/r*i),o=t=>Math.abs(t)<=e.Settings.linearSlop,h=t=>Math.abs(t-Math.round(t))<=e.Settings.linearSlop?Math.round(t):t,n={_collisions:["_collides","_colliding","_collided"],_overlappers:["_overlaps","_overlapping","_overlapped"]};this.P5Play=class{constructor(){this.sprites={},this.groups={},this.groupsCreated=0,this.spritesCreated=0,this.spritesDrawn=0,this.disableImages=!1,this.palettes=[],this.targetVersion=0,this.os={},this.context="web",window.matchMedia?this.hasMouse=!window.matchMedia("(any-hover: none)").matches:this.hasMouse=!0,this.standardizeKeyboard=!1,this._renderStats={},this._collides={},this._colliding={},this._collided={},this._overlaps={},this._overlapping={},this._overlapped={}}},this.p5play=new this.P5Play,delete this.P5Play;const a=console.log;this.log=console.log,this.Sprite=class{constructor(s,r,o,n,a){this.p=t,this._isSprite=!0,this.idNum;let u,_,c=[...arguments];if(void 0!==c[0]&&c[0]._isGroup&&(u=c[0],c=c.slice(1)),void 0!==c[0]&&isNaN(c[0])&&("string"==typeof c[0]||c[0]instanceof this.p.SpriteAnimation||c[0]instanceof p5.Image)&&(_=c[0],c=c.slice(1)),1==c.length&&"number"==typeof c[0])throw new b("Sprite",0,[c[0]]);if(s=c[0],r=c[1],o=c[2],n=c[3],a=c[4],Array.isArray(s)&&(s=void 0,r=void 0,o=c[0],n=c[1],a=c[2]),"string"==typeof n)!function(t){if("d"==t||"s"==t||"k"==t||"n"==t)return!0;let e=t.slice(0,2);return"dy"==e||"st"==e||"ki"==e||"no"==e}(n)?o=d(o,n):a=n,n=void 0;else if(Array.isArray(n))throw new b("Sprite",1,[`[[${o}], [${n}]]`]);this.idNum=this.p.p5play.spritesCreated,this._uid=1e3+this.idNum,this.p.p5play.sprites[this._uid]=this,this.p.p5play.spritesCreated++,this.groups=[],this.animations=new this.p.SpriteAnimations,this.joints=[],this.joints.removeAll=()=>{for(let t of this.joints)t.remove()},this.watch,this.mod={},this._removed=!1,this._life=2147483647,this._visible=!0,this._pixelPerfect=!1,this._aniChangeCount=0,this._hasOverlap={},this._collisions={},this._overlappers={},u??=this.p.allSprites,this.tileSize=u.tileSize||1;let f=this;this._position={x:0,y:0},this._pos=t.createVector.call(t),Object.defineProperty(this._pos,"x",{get(){if(!f.body)return f._position.x;let t=f.body.getPosition().x/f.tileSize*i;return h(t)},set(t){if(f.body){let s=new e.Vec2(t*f.tileSize/i,f.body.getPosition().y);f.body.setPosition(s)}f._position.x=t}}),Object.defineProperty(this._pos,"y",{get(){if(!f.body)return f._position.y;let t=f.body.getPosition().y/f.tileSize*i;return h(t)},set(t){if(f.body){let s=new e.Vec2(f.body.getPosition().x,t*f.tileSize/i);f.body.setPosition(s)}f._position.y=t}}),this._velocity={x:0,y:0},this._vel=t.createVector.call(t),Object.defineProperties(this._vel,{x:{get(){let t;return t=f.body?f.body.getLinearVelocity().x:f._velocity.x,h(t/f.tileSize)},set(t){t*=f.tileSize,f.body?f.body.setLinearVelocity(new e.Vec2(t,f.body.getLinearVelocity().y)):f._velocity.x=t}},y:{get(){let t;return t=f.body?f.body.getLinearVelocity().y:f._velocity.y,h(t/f.tileSize)},set(t){t*=f.tileSize,f.body?f.body.setLinearVelocity(new e.Vec2(f.body.getLinearVelocity().x,t)):f._velocity.y=t}}}),this._mirror={_x:1,_y:1,get x(){return this._x<0},set x(t){f.watch&&(f.mod[22]=!0),this._x=t?-1:1},get y(){return this._y<0},set y(t){f.watch&&(f.mod[22]=!0),this._y=t?-1:1}},this._heading="right",this._layer=u._layer,this._layer??=this.p.allSprites._getTopLayer()+1,u.dynamic&&(a??="dynamic"),u.kinematic&&(a??="kinematic"),u.static&&(a??="static"),a??=u.collider,a&&"string"==typeof a||(a="dynamic"),this.collider=a,s??=u.x,void 0===s&&(s=this.p.width/this.tileSize/2,o&&(this._vertexMode=!0)),r??=u.y,void 0===r&&(r=this.p.height/this.tileSize/2);let g=!1;if(void 0===o&&(o=u.w||u.width||u.d||u.diameter||u.v||u.vertices,n||u.d||u.diameter||(n=u.h||u.height,g=!0)),"function"==typeof s&&(s=s(u.length)),"function"==typeof r&&(r=r(u.length)),"function"==typeof o&&(o=o(u.length)),"function"==typeof n&&(n=n(u.length)),this.x=s,this.y=r,!u._isAllSpritesGroup&&!_)for(let t in u.animations){_=t;break}for(let t=u;t;t=this.p.p5play.groups[t.parent])this.groups.push(t);if(this.groups.reverse(),_){_ instanceof p5.Image?this.addAni(_):"string"==typeof _?this._changeAni(_):this._ani=_.clone();let t=this.tileSize;o||1==this._ani.w&&1==this._ani.h||(o=this._ani.w/t,n??=this._ani.h/t)}if(this.groups=[],this.mouse=new this.p._SpriteMouse,this._angle=0,this._rotationSpeed=0,this._bearing=0,this._scale=new l,Object.defineProperty(this._scale,"x",{get(){return this._x},set(t){if(t==this._x)return;f.watch&&(f.mod[28]=!0);let e=t/this._x;f._w*=e,f._hw*=e,f._resizeColliders({x:e,y:1}),this._x=t,this._avg=.5*(this._x+this._y)}}),Object.defineProperty(this._scale,"y",{get(){return this._y},set(t){if(t==this._y)return;f.watch&&(f.mod[28]=!0);let e=t/this._y;f._h&&(this._h*=e,this._hh*=e),f._resizeColliders({x:1,y:e}),this._y=t,this._avg=.5*(this._x+this._y)}}),this._offset={_x:0,_y:0,get x(){return this._x},set x(t){t!=this._x&&(f.watch&&(f.mod[23]=!0),f._offsetCenterBy(t-this._x,0))},get y(){return this._y},set y(t){t!=this._y&&(f.watch&&(f.mod[23]=!0),f._offsetCenterBy(0,t-this._y))}},this._massUndef=!0,void 0===o&&(this._dimensionsUndef=!0,this._widthUndef=!0,o=this.tileSize>1?1:50,void 0===n&&(this._heightUndef=!0)),g&&(n??=this.tileSize>1?1:50),this._shape=u.shape,3!=this.__collider)this._vertexMode?this.addCollider(o):this.addCollider(0,0,o,n),this.shape=this._shape;else{if(this.w=o,Array.isArray(o))throw new Error('Cannot set the collider type of a sprite with a polygon or chain shape to "none". To achieve the same effect, use .overlaps(allSprites) to have your sprite overlap with the allSprites group.');void 0!==o&&void 0===n?this.shape="circle":(this.shape="box",this.h=n)}this.prevPos={x:s,y:r},this.prevRotation=0,this._dest={x:s,y:r},this._destIdx=0,this.drag=0,this.debug=!1,u._isAllSpritesGroup||this.p.allSprites.push(this),u.push(this);let y=u.vel.x||0,m=u.vel.y||0;"function"==typeof y&&(y=y(u.length-1)),"function"==typeof m&&(m=m(u.length-1)),this.vel.x=y,this.vel.y=m;let v=["ani","collider","x","y","w","h","d","diameter","dynamic","height","kinematic","static","vel","width"];for(let t of this.p.Sprite.propsAll){if(v.includes(t))continue;let e=u[t];void 0!==e&&("function"==typeof e&&p(e)&&(e=e(u.length-1)),this[t]="object"==typeof e?Object.assign({},e):e)}v=["add","animation","animations","autoCull","contains","GroupSprite","Group","idNum","length","mod","mouse","p","parent","Sprite","Subgroup","subgroups","velocity"];for(let t=0;t1?1:50,h??=r,l=s(r-.08,h-.08,this.tileSize)),"box"==a)p=e.Box(l.x/2,l.y/2,s(t,i,this.tileSize),0);else if("circle"==a)p=e.Circle(s(t,i,this.tileSize),l.x/2);else if(n){let _,c,f=[{x:0,y:0}],g={x:0,y:0},y={x:0,y:0},m={x:0,y:0},v=Array.isArray(n[0]);function x(){g.xm.x&&(m.x=g.x),g.y>m.y&&(m.y=g.y)}if(v){this._vertexMode&&(_=n[0][0],c=n[0][1],this.fixture&&this._relativeOrigin?(_=this.x-this._relativeOrigin.x,c=this.y-this._relativeOrigin.y,f.pop()):(this.x=_,this.y=c));for(let b=0;b0?1:-1;S=Math.abs(S);let A=0;for(let k=0;ke.Settings.maxPolygonVertices||"chain"==this._shape)&&(a="chain"),"polygon"==a?p=e.Polygon(f):"chain"==a&&(p=e.Chain(f,!1))}return this.shape??=a,this._w=r,this._hw=.5*r,1!=this.__shape&&(this._h=h,this._hh=.5*h),p}removeColliders(){this.body&&(this._removeContacts(0),this._removeFixtures(0))}removeSensors(){this.body&&(this._removeContacts(1),this._removeFixtures(1),this._hasSensors=!1)}_removeFixtures(t){let e;for(let i=this.fixtureList;i;i=i.getNext())if(void 0===t||i.m_isSensor==t){let t=i.m_next;i.destroyProxies(this.p.world.m_broadPhase),e?e.m_next=t:this.body.m_fixtureList=t}else e=i}_removeContacts(t){if(!this.body)return;let e=this.body.m_contactList;for(;e;){let i=e.contact;e=e.next,void 0!==t&&i.m_fixtureA.m_isSensor!=t||this.p.world.destroyContact(i)}}_offsetCenterBy(t,e){if(!t&&!e)return;if(this._offset._x+=t,this._offset._y+=e,!this.body)return;let i=s(t,e,this.tileSize);for(let t=this.body.m_fixtureList;t;t=t.m_next){let e=t.m_shape;if("circle"!=e.m_type){let t=e.m_vertices;for(let e of t)e.x+=i.x,e.y+=i.y}else e.m_p.x+=i.x,e.m_p.y+=i.y}}_cloneBodyProps(){let t={},e=["bounciness","density","drag","friction","heading","isSuperFast","rotation","rotationDrag","rotationLock","rotationSpeed","scale","vel","x","y"];this._massUndef&&this._dimensionsUndef||e.push("mass");for(let i of e)"object"==typeof this[i]?t[i]=Object.assign({},this[i]):t[i]=this[i];return t}get animation(){return this._ani}set animation(t){this.changeAni(t)}get ani(){return this._ani}set ani(t){this.changeAni(t)}get anis(){return this.animations}get autoDraw(){return this._autoDraw}set autoDraw(t){this.watch&&(this.mod[6]=!0),this._autoDraw=t}get allowSleeping(){return this.body?.isSleepingAllowed()}set allowSleeping(t){this.watch&&(this.mod[7]=!0),this.body&&this.body.setSleepingAllowed(t)}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){this.watch&&(this.mod[8]=!0),this._autoUpdate=t}get bounciness(){if(this.fixture)return this.fixture.getRestitution()}set bounciness(t){this.watch&&(this.mod[9]=!0);for(let e=this.fixtureList;e;e=e.getNext())e.setRestitution(t)}get centerOfMass(){let t=this.body.getWorldCenter(),e=r(t.x,t.y,this.tileSize);return this.p.createVector(e.x,e.y)}get collider(){return this._collider}set collider(t){if(t==this._collider)return;let e=(t=t.toLowerCase())[0];if("d"==e&&(t="dynamic"),"s"==e&&(t="static"),"k"==e&&(t="kinematic"),"n"==e&&(t="none"),t==this._collider)return;if("none"==t&&("chain"==this._shape||"polygon"==this._shape))return void console.error('Cannot set the collider type of a polygon or chain collider to "none". To achieve the same effect, use .overlaps(allSprites) to have your sprite overlap with the allSprites group.');if(this._removed)throw new Error("Cannot change the collider type of a sprite that was removed.");let i=this.__collider;this._collider=t,this.__collider=["d","s","k","n"].indexOf(e),this.watch&&(this.mod[10]=!0),void 0!==i&&(3!=this.__collider?(this.body&&this.body.setType(t),3==i&&this.addCollider()):(this.removeColliders(),this.fixture?.m_isSensor?this.body.m_gravityScale=0:this.p.world.destroyBody(this.body)))}_parseColor(t){if(t instanceof p5.Color)return t;if("object"!=typeof t)return"string"==typeof t&&1==t.length?this.p.colorPal(t):this.p.color(t);if(t.levels)return this.p.color(...t.levels);if(void 0!==t._r)return this.p.color(t._r,t._g,t._b,255*t._a);if(void 0!==t._h)return this.p.color(t._h,t._s,t._v,255*t._a);throw new Error("Invalid color")}get color(){return this._color}set color(t){this.watch&&(this.mod[11]=!0),this._color=this._parseColor(t)}get colour(){return this._color}set colour(t){this.color=t}get fill(){return this._color}set fill(t){this.color=t}get fillColor(){return this._color}set fillColor(t){this.color=t}get stroke(){return this._stroke}set stroke(t){this.watch&&(this.mod[31]=!0),this._stroke=this._parseColor(t)}get strokeColor(){return this._stroke}set strokeColor(t){this.stroke=t}get strokeWeight(){return this._strokeWeight}set strokeWeight(t){this.watch&&(this.mod[32]=!0),this._strokeWeight=t}get textColor(){return this._textFill}set textColor(t){this.watch&&(this.mod[34]=!0),this._textFill=this._parseColor(t)}get textColour(){return this._textFill}set textColour(t){this.textColor=t}get textFill(){return this._textFill}set textFill(t){this.textColor=t}get textSize(){return this._textSize}set textSize(t){this.watch&&(this.mod[40]=!0),this._textSize=t}get textStroke(){return this._textStroke}set textStroke(t){this.watch&&(this.mod[41]=!0),this._textStroke=this._parseColor(t)}get textStrokeWeight(){return this._textStrokeWeight}set textStrokeWeight(t){this.watch&&(this.mod[42]=!0),this._textStrokeWeight=t}get bearing(){return this._bearing}set bearing(t){this.watch&&(this.mod[39]=!0),this._bearing=t}get debug(){return this._debug}set debug(t){this.watch&&(this.mod[12]=!0),this._debug=t}get density(){if(this.fixture)return this.fixture.getDensity()}set density(t){this.watch&&(this.mod[13]=!0);for(let e=this.fixtureList;e;e=e.getNext())e.setDensity(t)}_getDirectionAngle(t){t=t.toLowerCase().replaceAll(/[ _-]/g,"");let e={up:-90,down:90,left:180,right:0,upright:-45,rightup:-45,upleft:-135,leftup:-135,downright:45,rightdown:45,downleft:135,leftdown:135,forward:this.rotation,backward:this.rotation+180}[t];return"radians"==this.p._angleMode&&(e=this.p.radians(e)),e}get direction(){return 0!==this.vel.x||0!==this.vel.y?this.p.atan2(this.vel.y,this.vel.x):void 0===this._direction?this.rotation:this._direction}set direction(t){this.watch&&(this.mod[14]=!0),"string"==typeof t&&(this._heading=t,t=this._getDirectionAngle(t)),this._direction=t;let e=this.speed;this.vel.x=this.p.cos(t)*e,this.vel.y=this.p.sin(t)*e}get drag(){return this.body?.getLinearDamping()}set drag(t){this.watch&&(this.mod[15]=!0),this.body&&this.body.setLinearDamping(t)}get draw(){return this._display}set draw(t){this._draw=t}get dynamic(){return this.body?.isDynamic()}set dynamic(t){this.collider=t?"dynamic":"kinematic"}get fixture(){return this.fixtureList}get fixtureList(){return this.body?this.body.m_fixtureList:null}get friction(){if(this.fixture)return this.fixture.getFriction()}set friction(t){this.watch&&(this.mod[16]=!0);for(let e=this.fixtureList;e;e=e.getNext())e.setFriction(t)}get heading(){return this._heading}set heading(t){this.direction=t}get img(){return this._ani?.frameImage}set img(t){this.changeAni(t)}get image(){return this._ani?.frameImage}set image(t){this.changeAni(t)}get isMoving(){return 0!=this.vel.x||0!=this.vel.y}get isSuperFast(){return this.body?.isBullet()}set isSuperFast(t){this.watch&&(this.mod[18]=!0),this.body&&this.body.setBullet(t)}get kinematic(){return this.body?.isKinematic()}set kinematic(t){this.collider=t?"kinematic":"dynamic"}get layer(){return this._layer}set layer(t){this.watch&&(this.mod[19]=!0),this._layer=t}get life(){return this._life}set life(t){this.watch&&(this.mod[20]=!0),this._life=t}get mass(){return this.body?.getMass()}set mass(t){if(!this.body)return;this.watch&&(this.mod[21]=!0);let e=this.massData;e.mass=t>0?t:1e-8,this.body.setMassData(e),delete this._massUndef}get massData(){const t={I:0,center:new e.Vec2(0,0),mass:0};return this.body.getMassData(t),t.center=r(t.center.x,t.center.y,this.tileSize),t}resetMass(){this.body&&(this.watch&&(this.mod[21]=!0),this.body.resetMassData())}get mirror(){return this._mirror}set mirror(t){this.watch&&(this.mod[22]=!0),void 0!==t.x&&(this._mirror.x=t.x),void 0!==t.y&&(this._mirror.y=t.y)}get offset(){return this._offset}set offset(t){t.x??=this._offset._x,t.y??=this._offset._y,t.x==this._offset._x&&t.y==this._offset._y||(this.watch&&(this.mod[23]=!0),this._offsetCenterBy(t.x-this._offset._x,t.y-this._offset._y))}get previousPosition(){return this.prevPos}set previousPosition(t){this.prevPos=t}get previousRotation(){return this.prevRotation}set previousRotation(t){this.prevRotation=t}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(t){this.watch&&(this.mod[24]=!0),this._pixelPerfect=t}get rotation(){if(!this.body)return this._angle||0;let t=this.body.getAngle();return"degrees"===this.p._angleMode?this.p.degrees(t):t}set rotation(t){this.body?("degrees"===this.p._angleMode&&(t=this.p.radians(t)),this.body.setAngle(t),this.body.synchronizeTransform()):this._angle=t}get rotationDrag(){return this.body?.getAngularDamping()}set rotationDrag(t){this.body&&(this.watch&&(this.mod[26]=!0),this.body.setAngularDamping(t))}get rotationLock(){return this.body?.isFixedRotation()}set rotationLock(t){this.body&&(this.watch&&(this.mod[27]=!0),this.body.setFixedRotation(t))}get rotationSpeed(){return this.body?this.body.getAngularVelocity():this._rotationSpeed}set rotationSpeed(t){this.body?this.body.setAngularVelocity(t):this._rotationSpeed=t}get scale(){return this._scale}set scale(t){if(t<=0&&(t=.01),"number"==typeof t?t={x:t,y:t}:(t.x??=this._scale._x,t.y??=this._scale._y),t.x==this._scale._x&&t.y==this._scale._y)return;this.watch&&(this.mod[28]=!0);let e={x:t.x/this._scale._x,y:t.y/this._scale._y};this._w*=e.x,this._hw*=e.x,this._h&&(this._h*=e.y,this._hh*=e.y),this._resizeColliders(e),this._scale._x=t.x,this._scale._y=t.y,this._scale._avg=t.x}get sleeping(){if(this.body)return!this.body.isAwake()}set sleeping(t){this.body&&(this.watch&&(this.mod[30]=!0),this.body.setAwake(!t))}get speed(){return this.p.createVector(this.vel.x,this.vel.y).mag()}set speed(t){let e=this.direction;this.vel.x=this.p.cos(e)*t,this.vel.y=this.p.sin(e)*t}get static(){return this.body?.isStatic()}set static(t){this.collider=t?"static":"dynamic"}get removed(){return this._removed}set removed(t){t&&!this._removed&&(this.watch&&(this.mod[25]=!0),this._removed=!0,this._remove())}set vertices(t){if(3==this.__collider)throw new Error('Cannot set vertices of a sprite with collider type of "none".');this.watch&&(this.mod[29]=!0),this._removeFixtures(),this._originMode="start",this.addCollider(t),this._hasSensors&&this.addDefaultSensors()}get vertices(){return this._getVertices()}_getVertices(t){let e=this.fixture.getShape(),s=[...e.m_vertices];"polygon"==e.m_type&&s.unshift(s.at(-1));let r=this.x,o=this.y;for(let e=0;e=2)return void console.error('Cannot set the collider shape to chain or polygon if the sprite has a collider type of "none". To achieve the same effect, use .overlaps(allSprites) to have your sprite overlap with the allSprites group.');if(1==this.__shape&&0!=e)return void console.error("Cannot change a circle collider into a chain or polygon shape.");let i,s,r=this.__shape;if(this.__shape=e,this._shape=t,this.watch&&(this.mod[29]=!0),void 0===r)return;0==this.__shape?(this._h=this._w,this._hh=this._hw):(this._h=void 0,this._hh=void 0),1!=r&&1!=this.__shape?i=this._getVertices(!0):s=this._w,this._removeFixtures(),3!=this.__collider&&(i?(this._originMode??="center",this.addCollider(i)):this.addCollider()),this._hasSensors&&this.addDefaultSensors();let o=this._offset._x,h=this._offset._y;(o||h)&&(this._offset._x=0,this._offset._y=0,this._offsetCenterBy(o,h))}get update(){return this._update}set update(t){this._customUpdate=t}get vel(){return this._vel}set vel(t){this.vel.x=t.x,this.vel.y=t.y}set velocity(t){this.vel=t}get velocity(){return this._vel}_update(){this._ani?.update&&this._ani.update();for(let t in this.mouse)-1==this.mouse[t]&&(this.mouse[t]=0);this._customUpdate&&this._customUpdate(),this.autoUpdate&&(this.autoUpdate=null)}_step(){this.body||this._removed||(this.rotation+=this._rotationSpeed,this.x+=this.vel.x,this.y+=this.vel.y),this.watch&&(this.x!=this.prevX&&(this.mod[0]=this.mod[2]=!0),this.y!=this.prevY&&(this.mod[1]=this.mod[2]=!0),this.rotation!=this.prevRotation&&(this.mod[3]=this.mod[4]=!0)),(this.body||this._removed)&&this.__step()}_draw(){if(void 0!==this._strokeWeight&&this.p.strokeWeight(this._strokeWeight),this._ani&&"colliders"!=this.debug&&!this.p.p5play.disableImages&&this._ani.draw(this._offset._x,this._offset._y,0,this._scale._x,this._scale._y),!this._ani||this.debug||this.p.p5play.disableImages)if(this.debug&&"colliders"!=this.debug&&(this.p.noFill(),3!=this.__collider?this.p.stroke(0,255,0):this.p.stroke(120),this.p.line(0,-2,0,2),this.p.line(-2,0,2,0)),3!=this.__collider){0!==this._strokeWeight&&(2==this.__shape?this.p.stroke(this.stroke||this.color):this._stroke&&this.p.stroke(this._stroke));for(let t=this.fixtureList;t;t=t.getNext())t.m_isSensor&&!this.debug||this._drawFixture(t)}else 0!==this._strokeWeight&&this.p.stroke(this._stroke||120),0==this.__shape?this.p.rect(this._offset._x,this._offset._y,this.w*this.tileSize,this.h*this.tileSize):1==this.__shape&&this.p.circle(this._offset._x,this._offset._y,this.d*this.tileSize);void 0!==this.text&&(this.p.textAlign(this.p.CENTER,this.p.CENTER),this.p.fill(this._textFill),this._textStrokeWeight&&this.p.strokeWeight(this._textStrokeWeight),this._textStroke?this.p.stroke(this._textStroke):this.p.noStroke(),this.p.textSize(this.textSize*this.tileSize),this.p.text(this.text,0,0))}_display(){let t=this.x*this.tileSize+this.p.world.origin.x,e=this.y*this.tileSize+this.p.world.origin.y,i=Math.max(this._w,this._h);if("chain"!=this.shape&&this.p.camera.active&&(t+ithis.p.camera.bound.max.x||e+ithis.p.camera.bound.max.y))this._visible=null;else{if(this._visible=!0,this.p.p5play.spritesDrawn++,this._pixelPerfect){let i,s;this.ani&&!this.p.p5play.disableImages?(i=this.ani[this.ani._frame].w,s=this.ani[this.ani._frame].h):(i=this._w,s=this._h),t=i%2==0?Math.round(t):Math.round(t-.5)+.5,e=s%2==0?Math.round(e):Math.round(e-.5)+.5}else t=h(t),e=h(e);for(let t of this.joints)t.visible?this._uid==t.spriteA._uid?(!t.spriteB._visible||this.layer<=t.spriteB.layer)&&t._display():(!t.spriteA._visible||this.layer1&&(s??=.1),s??=1,s<=0)return console.warn("sprite.move: speed should be a positive number"),Promise.resolve(!1);let r=this._dest.y-this.y,o=this._dest.x-this.x,h=s/Math.sqrt(r*r+o*o);this.vel.x=o*h,this.vel.y=r*h;let n=this.direction,a=n-.1,l=n+.1,p=s+.01,d=this._destIdx,u=Math.max(this.p.world.velocityThreshold,.25*p)/this.tileSize;return(async()=>{let s=p+p,r=p+p;do{if(d!=this._destIdx)return!1;await t.delay();let e=this.direction;if(e<=a||e>=l||Math.abs(this.vel.x)<=u&&Math.abs(this.vel.y)<=u)return!1;s=Math.abs(this.x-this._dest.x),r=Math.abs(this.y-this._dest.y)}while(e&&s>p||i&&r>p);return s2&&(i=o[0],s=o[1],e=o[2],r=o[3]),void 0!==i?t=this.angleToFace(i,s,r):t-=this.rotation,e??=.1,this.rotationSpeed=t*e}angleTo(t,e){if("object"==typeof t){let i=t;if(i==this.p.mouse&&!this.p.mouse.active)return 0;if(void 0===i.x||void 0===i.y)return console.error("sprite.angleTo ERROR: rotation destination not defined, object given with no x or y properties"),0;e=i.y,t=i.x}return this.p.atan2(e-this.y,t-this.x)}angleToFace(t,e,i){if("object"==typeof t&&(i=e,e=t.y,t=t.x),Math.abs(t-this.x)<.01&&Math.abs(e-this.y)<.01)return 0;let s=this.angleTo(t,e);i??=0,s+=i;let r=s-this.rotation%360,o=360-Math.abs(r);return o*=r<0?1:-1,Math.abs(r)2&&(i=o[0],s=o[1],e=o[2],r=o[3]),void 0!==i)t=this.angleToFace(i,s,r);else{if(t==this.rotation)return;t-=this.rotation}return this.rotate(t,e)}rotate(e,i){if(1==this.__collider)throw new b(0);if(isNaN(e))throw new b(1,[e]);if(0==e)return;let s=Math.abs(e);i??=1,i>s&&(i=s);let r=this.rotation+e,o=e>0;this.rotationSpeed=i*(o?1:-1);let h=Math.floor(s/i)-1;this._rotateIdx??=0,this._rotateIdx++;let n=this._rotateIdx;return(async()=>{if(h>1){let e=Math.abs(this.rotationSpeed)+.01;do{if(this._rotateIdx!=n)return!1;if(await t.delay(),o&&this.rotationSpeed<.01||!o&&this.rotationSpeed>-.01)return!1}while((o&&r>this.rotation||!o&&r.01&&(this.rotationSpeed=r-this.rotation,await t.delay())}else await t.delay();return this._rotateIdx==n&&(this.rotationSpeed=0,this.rotation=r,!0)})()}async changeAni(t){if(this.p.p5play.disableImages)return;if(arguments.length>1)t=[...arguments];else if(t instanceof this.p.SpriteAnimation){if(t==this._ani)return;t=[t]}else if(!Array.isArray(t)){if(t==this._ani?.name)return;t=[t]}let e,i;this._aniChangeCount++;for(let s=0;s1&&("!"==r.name[0]&&(r.name=r.name.slice(1),r.start=-1,r.end=0),"<"!=r.name[0]&&">"!=r.name[0]||(r.name=r.name.slice(1),r.flipX=!0),"^"==r.name[0]&&(r.name=r.name.slice(1),r.flipY=!0),"**"==r.name&&(e=!0,t=t.slice(0,-1)),";;"==r.name&&(i=!0,t=t.slice(0,-1)))}let s=this._aniChangeCount;do{for(let e=0;e1&&(i.start=0),await this._playSequencedAni(i)}}while(e&&s==this._aniChangeCount);1!=t.length&&i&&this._ani.stop()}_playSequencedAni(t){return new Promise((e=>{let{name:i,start:s,end:r,flipX:o,flipY:h}=t;this._changeAni(i),o&&(this._ani.scale.x=-this._ani.scale.x),h&&(this._ani.scale.y=-this._ani.scale.y),s<0&&(s=this._ani.length+s),void 0!==s&&(this._ani._frame=s),void 0!==r?this._ani.goToFrame(r):this._ani._frame==this._ani.lastFrame&&e(),this._ani._onComplete=this._ani._onChange=()=>{o&&(this._ani.scale.x=-this._ani.scale.x),h&&(this._ani.scale.y=-this._ani.scale.y),this._ani._onComplete=this._ani._onChange=null,e()}}))}changeAnimation(){return this.changeAni(...arguments)}_changeAni(t){this._ani?._onChange&&this._ani._onChange(),this._ani?.onChange&&this._ani.onChange();let e=this.animations[t];if(!e)for(let i=this.groups.length-1;i>=0;i--){if(e=this.groups[i].animations[t],e){e=e.clone();break}}if(!e)throw this.p.noLoop(),new b("Sprite.changeAnimation",[t]);this._ani=e,this._ani.name=t,this.resetAnimationsOnChange&&(this._ani._frame=0)}remove(){this.removed=!0}_remove(){this.body&&this.p.world.destroyBody(this.body),this.body=null;for(let t of this.groups)t.remove(this)}toString(){return"s"+this.idNum}_setContactCB(t,e,i,s){let r;r=0==i?n._collisions[s]:n._overlappers[s];let o=this.p.p5play[r],h=o[this._uid]??={};h[t._uid]!=e&&(h[t._uid]=e,this._uid!=t._uid&&(h=o[t._uid],h&&h[this._uid]&&(delete h[this._uid],0==Object.keys(h).length&&delete o[t._uid])))}_validateCollideParams(t,e){if(!t)throw new b("Sprite.collide",2);if(!t._isSprite&&!t._isGroup)throw new b("Sprite.collide",0,[t]);if(e&&"function"!=typeof e)throw new b("Sprite.collide",1,[e])}_ensureCollide(t,e,i){if(!1!==this._hasOverlap[t._uid]&&(this._hasOverlap[t._uid]=!1),!1!==t._hasOverlap[this._uid]&&(t._hasOverlap[this._uid]=!1,t._isGroup))for(let e of t)e._hasOverlap[this._uid]=!1,this._hasOverlap[e._uid]=!1}collide(t,e){return this.collides(t,e)}collides(t,e){return this._validateCollideParams(t,e),this._ensureCollide(t),e&&this._setContactCB(t,e,0,0),1==this._collisions[t._uid]||this._collisions[t._uid]<=-3}colliding(t,e){this._validateCollideParams(t,e),this._ensureCollide(t),e&&this._setContactCB(t,e,0,1);let i=this._collisions[t._uid];return i<=-3?1:i>0?i:0}collided(t,e){return this._validateCollideParams(t,e),this._ensureCollide(t),e&&this._setContactCB(t,e,0,2),this._collisions[t._uid]<=-1}_validateOverlapParams(t,e){if(!t)throw new b("Sprite.overlap",2);if(!t._isSprite&&!t._isGroup)throw new b("Sprite.overlap",0,[t]);if(e&&"function"!=typeof e)throw new b("Sprite.overlap",1,[e])}_ensureOverlap(t){if(this._hasSensors||this.addDefaultSensors(),!t._hasSensors)if(t._isSprite)t.addDefaultSensors();else{for(let e of t)e._hasSensors||e.addDefaultSensors();t._hasSensors=!0}if(this._hasOverlap[t._uid]||(this._removeContactsWith(t),this._hasOverlap[t._uid]=!0),!t._hasOverlap[this._uid]&&(t._removeContactsWith(this),t._hasOverlap[this._uid]=!0,t._isGroup))for(let e of t)e._hasOverlap[this._uid]=!0,this._hasOverlap[e._uid]=!0}overlap(t,e){return this.overlaps(t,e)}overlaps(t,e){return this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,0),1==this._overlappers[t._uid]||this._overlappers[t._uid]<=-3}overlapping(t,e){this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,1);let i=this._overlappers[t._uid];return i<=-3?1:i>0?i:0}overlapped(t,e){return this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,2),this._overlappers[t._uid]<=-1}_removeContactsWith(t){if(t._isGroup)for(let e of t)this._removeContactsWith(e);else this.__removeContactsWith(t)}__removeContactsWith(t){if(this.body)for(let e=this.body.getContactList();e;e=e.next){let i=e.contact;i.m_fixtureA.m_body.sprite._uid!=t._uid&&i.m_fixtureB.m_body.sprite._uid!=t._uid||this.p.world.destroyContact(i)}}_sortFixtures(){let t,e,i=null,s=null;for(let r=this.fixtureList;r;r=r.getNext())r.m_isSensor?(s?s.m_next=r:s=r,e=r):(i?i.m_next=r:i=r,t=r);s&&(e.m_next=null),i&&(t.m_next=s),this.body.m_fixtureList=i||s}addDefaultSensors(){if(this._hasSensors)return;let t;if(this.body&&this.fixtureList){for(let e=this.fixtureList;e;e=e.getNext())e.m_isSensor||(t=e.m_shape,this.body.createFixture({shape:t,isSensor:!0}));this._sortFixtures()}else this.addSensor();this._hasSensors=!0}},this.Sprite.propTypes={x:"Float64",y:"Float64",vel:"Vec2",rotation:"number",rotationSpeed:"number",ani:"string",autoDraw:"boolean",allowSleeping:"boolean",autoUpdate:"boolean",bounciness:"number",collider:"Uint8",color:"color",debug:"boolean",density:"number",direction:"number",drag:"number",friction:"number",h:"number",isSuperFast:"boolean",layer:"number",life:"Int32",mass:"number",mirror:"Vec2_boolean",offset:"Vec2",pixelPerfect:"boolean",removed:"boolean",rotationDrag:"number",rotationLock:"boolean",scale:"Vec2",shape:"Uint8",sleeping:"boolean",stroke:"color",strokeWeight:"number",text:"string",textColor:"color",tile:"string",tileSize:"number",visible:"boolean",w:"number",bearing:"number",textSize:"number",textStroke:"color",textStrokeWeight:"number"},this.Sprite.props=Object.keys(this.Sprite.propTypes),this.Sprite.propsAll=this.Sprite.props.concat(["d","diameter","dynamic","fill","height","heading","kinematic","resetAnimationsOnChange","speed","static","width"]),this.Sprite.colliderTypes=["d","s","k","n"],this.Sprite.shapeTypes=["box","circle","chain","polygon"],this.Turtle=function(e){if(t.allSprites.tileSize>1)throw new Error("Turtle can't be used when allSprites.tileSize is greater than 1.");e??=25;let i=new t.Sprite(e,e,[[e,.4*e],[-e,.4*e],[0,.8*-e]]);i.color="green",i._isTurtleSprite=!0,i._prevPos={x:i.x,y:i.y};let s=i.move;return i.move=async function(){this._prevPos.x=this.x,this._prevPos.y=this.y,await s.call(this,...arguments)},i},this.SpriteAnimation=class extends Array{constructor(){super(),this.p=t;let e,i=[...arguments];if(this.name="default","object"==typeof i[0]&&(i[0]._isSprite||i[0]._isGroup)&&(e=i[0],i=i.slice(1),this._addedToSpriteOrGroup=!0),e??=this.p.allSprites,"string"!=typeof i[0]||1!=i[0].length&&i[0].includes(".")||(this.name=i[0],i=i.slice(1)),this._frame=0,this._cycles=0,this.targetFrame=-1,this.offset={x:e.anis.offset.x||0,y:e.anis.offset.y||0},this._frameDelay=e.anis.frameDelay||4,this.demoMode=e.anis.demoMode||!1,this.playing=!0,this.visible=!0,this.looping=e.anis.looping,this.looping??=!0,this.endOnFirstFrame=!1,this.frameChanged=!1,this.onComplete=this.onChange=null,this._onComplete=this._onChange=null,this.rotation=e.anis.rotation||0,this._scale=new l,0!=i.length&&"number"!=typeof i[0])if(e.animations[this.name]=this,e._ani=this,Array.isArray(i[0])&&"string"==typeof i[0][0]&&(i=[...i[0]]),2!=i.length||"string"!=typeof i[0]||"string"!=typeof i[1]&&"number"!=typeof i[1])if("string"==typeof i[i.length-1]||i[i.length-1]instanceof p5.Image)for(let s=0;s=3)throw new b("SpriteAnimation",1);o=i[0],r=i[1]}else r=i[0];let h=this;if(o instanceof p5.Image&&1!=o.width&&1!=o.height)this.spriteSheet=o,n();else{let a;a="string"==typeof o?o:o.url,this.spriteSheet=this.p.loadImage(a,(()=>{n()}))}function n(){if(Array.isArray(r)||Array.isArray(r.frames)){if("number"!=typeof r[0]){let t=r;if(Array.isArray(r.frames)){t=r.frames,delete r.frames;for(let e=0;e=h.spriteSheet.width&&(u=0,_+=i,_>=h.spriteSheet.height&&(_=0))}}else{let p,d,u=i[0];if(isNaN(i[1])?p=i[1]:d=Number(i[1]),".png"!=u.slice(-4)||p&&".png"!=p.slice(-4))throw new b("SpriteAnimation",0,[u]);let _=0,c=0;for(let y=u.length-5;y>=0&&!isNaN(u.charAt(y));y--)_++;if(p)for(let m=p.length-5;m>=0&&!isNaN(p.charAt(m));m--)c++;let f,g=u.slice(0,-4-_);if(p&&(f=p.slice(0,-4-c)),p&&g!=f)this.push(this.p.loadImage(u)),this.push(this.p.loadImage(p));else{let v,x=parseInt(u.slice(-4-_,-4),10);if(d??=parseInt(p.slice(-4-c,-4),10),d=this.length)throw new b("SpriteAnimation.frame",[t,this.length]);this._frame=t}get frameDelay(){return this._frameDelay}set frameDelay(t){t<=0&&(t=1),this._frameDelay=t}get scale(){return this._scale}set scale(t){"number"==typeof t&&(t={x:t,y:t}),this._scale._x=t.x,this._scale._y=t.y,this._scale._avg=t.x}clone(){let t=new this.p.SpriteAnimation;t.spriteSheet=this.spriteSheet;for(let e=0;ethis._frame&&-1!==this.targetFrame?this._frame++:this.targetFrame=this.lastFrame?this._frame=0:this._frame++:this._frame{this._onComplete=()=>{this._onComplete=null,t()}}))}pause(t){this.playing=!1,t&&(this._frame=t)}stop(t){this.playing=!1,t&&(this._frame=t)}rewind(){return this.looping=!1,this.goToFrame(0)}loop(){this.looping=!0,this.playing=!0}noLoop(){this.looping=!1}nextFrame(){this._frame0?this._frame=this._frame-1:this.looping&&(this._frame=this.length-1),this.targetFrame=-1,this.playing=!1}goToFrame(t){if(!(t<0||t>=this.length))return this.targetFrame=t,this.targetFrame!==this._frame&&(this.playing=!0),new Promise((t=>{this._onComplete=()=>{this._onComplete=null,t()}}))}get lastFrame(){return this.length-1}get frameImage(){let t=this[this._frame];if(t instanceof p5.Image)return t;let{x:e,y:i,w:s,h:r}=t,o=this.p.createImage(s,r);return o.copy(this.spriteSheet,this.offset.x,this.offset.y,s,r,e,i,s,r),o}get w(){return this.width}get width(){return this[this._frame]instanceof p5.Image?this[this._frame].width:this[this._frame]?this[this._frame].w:1}get h(){return this.height}get height(){return this[this._frame]instanceof p5.Image?this[this._frame].height:this[this._frame]?this[this._frame].h:1}get frames(){let t=[];for(let e=0;ee.#t[t],set(i){e.#t[t]=i;for(let s in e){let r=e[s];r instanceof SpriteAnimation&&(r[t]=i)}}});for(let t of s){this.#t[t]={_x:0,_y:0};for(let i of["x","y"])Object.defineProperty(this.#t[t],i,{get:()=>e.#t[t]["_"+i],set(s){e.#t[t]["_"+i]=s;for(let r in e){let o=e[r];o instanceof SpriteAnimation&&(o[t][i]=s)}}})}}},this.Group=class extends Array{constructor(...e){let i;if(e[0]instanceof t.Group&&(i=e[0],e=e.slice(1)),super(...e),this.p=t,"number"==typeof e[0])return;for(let t of this)if(!(t instanceof this.p.Sprite))throw new Error("A group can only contain sprites");if(this._isGroup=!0,this.x,this.y,this.vel,this.rotation,this.rotationSpeed,this.autoDraw,this.allowSleeping,this.autoUpdate,this.bounciness,this.collider,this.color,this.debug,this.density,this.direction,this.drag,this.friction,this.h,this.isSuperFast,this.layer,this.life,this.mass,this.mirror,this.offset,this.pixelPerfect,this.removed,this.rotationDrag,this.rotationLock,this.scale,this.shape,this.sleeping,this.stroke,this.strokeWeight,this.text,this.textColor,this.tile,this.tileSize,this.visible,this.w,this.bearing,this.d,this.diameter,this.dynamic,this.height,this.heading,this.kinematic,this.resetAnimationsOnChange,this.speed,this.static,this.width,this.idNum,this.p.p5play.groupsCreated<999)this.idNum=this.p.p5play.groupsCreated;else{for(let t=1;tt&&(t=e._layer);return t}get ani(){return this._ani}set ani(t){this.addAni(t);for(let e of this)e.changeAni(t)}get animation(){return this._ani}set animation(t){this.ani=t}get anis(){return this.animations}get img(){return this._ani.frameImage}set img(t){this.ani=t}get image(){return this._ani.frameImage}set image(t){this.ani=t}set amount(t){let e=t-this.length,i=e>0;e=Math.abs(e);for(let t=0;t0?i:0}collided(t,e){return this._validateCollideParams(t,e),this._ensureCollide(t),e&&this._setContactCB(t,e,0,2),this._collisions[t._uid]<=-1}_validateOverlapParams(t,e){if(e&&"function"!=typeof e)throw new b("Group.overlap",1,[e]);if(!t)throw new b("Group.overlap",2);if(t._isSprite)e&&!b.warned1&&(console.warn("Deprecated use of a group.overlap function with a sprite as input. Use sprite.overlaps, sprite.overlapping, or sprite.overlapped instead."),b.warned1=!0);else if(!t._isGroup)throw new b("Group.overlap",0,[t])}_ensureOverlap(t){if(!this._hasSensors){for(let t of this)t._hasSensors||t.addDefaultSensors();this._hasSensors=!0}if(!t._hasSensors)if(t._isSprite)t.addDefaultSensors();else{for(let e of t)e._hasSensors||e.addDefaultSensors();t._hasSensors=!0}if(1!=this._hasOverlap[t._uid]){this._removeContactsWith(t),this._hasOverlap[t._uid]=!0;for(let e of this)if(e._hasOverlap[t._uid]=!0,t._hasOverlap[e._uid]=!0,this._uid==t._uid)for(let i of t)e._hasOverlap[i._uid]=!0,i._hasOverlap[e._uid]=!0}if(1!=t._hasOverlap[this._uid]&&(t._removeContactsWith(this),t._hasOverlap[this._uid]=!0,t._isGroup))for(let e of t){e._hasOverlap[this._uid]=!0,this._hasOverlap[e._uid]=!0;for(let t of this)e._hasOverlap[t._uid]=!0,t._hasOverlap[e._uid]=!0}}overlap(t,e){return this.overlaps(t,e)}overlaps(t,e){return this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,0),1==this._overlappers[t._uid]||this._overlappers[t._uid]<=-3}overlapping(t,e){this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,1);let i=this._overlappers[t._uid];return i<=-3?1:i>0?i:0}overlapped(t,e){return this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,2),this._overlappers[t._uid]<=-1}_removeContactsWith(t){for(let e of this)e._removeContactsWith(t)}applyForce(){for(let t of this)t.applyForce(...arguments)}applyForceScaled(){for(let t of this)t.applyForceScaled(...arguments)}attractTo(){for(let t of this)t.attractTo(...arguments)}applyTorque(){for(let t of this)t.applyTorque(...arguments)}move(t,e,i){let s=[];for(let r of this)s.push(r.move(t,e,i));return Promise.all(s)}moveTo(t,e,i){if("number"!=typeof t){let s=t;if(s==this.p.mouse&&!this.p.mouse.active)return;i=e,e=s.y,t=s.x}let s=this._resetCentroid(),r=[];for(let o of this){let h={x:o.x-s.x+t,y:o.y-s.y+e};r.push(o.moveTo(h.x,h.y,i))}return Promise.all(r)}moveTowards(t,e,i){if("number"!=typeof t){let s=t;if(s==this.p.mouse&&!this.p.mouse.active)return;i=e,e=s.y,t=s.x}if(void 0!==t||void 0!==e){this._resetCentroid();for(let s of this){void 0===s.distCentroid&&this._resetDistancesFromCentroid();let r={x:s.distCentroid.x+t,y:s.distCentroid.y+e};s.moveTowards(r.x,r.y,i)}}}moveAway(t,e,i){if("number"!=typeof t){let s=t;if(s==this.p.mouse&&!this.p.mouse.active)return;i=e,e=s.y,t=s.x}if(void 0!==t||void 0!==e){this._resetCentroid();for(let s of this){void 0===s.distCentroid&&this._resetDistancesFromCentroid();let r={x:s.distCentroid.x+t,y:s.distCentroid.y+e};s.moveAway(r.x,r.y,i)}}}push(...t){this.removed&&(console.warn("Adding a sprite to a group that was removed. Use `group.removeAll()` to remove all of a group's sprites without removing the group itself. Restoring the group in p5play's memory."),this.p.p5play.groups[this._uid]=this,this.removed=!1);for(let e of t){if(!(e instanceof this.p.Sprite))throw new Error("You can only add sprites to a group, not "+typeof e);if(e.removed){console.error("Can't add a removed sprite to a group");continue}let t;for(let i in this._hasOverlap){let s=this._hasOverlap[i];s&&!e._hasSensors&&e.addDefaultSensors(),t=i>=1e3?this.p.p5play.sprites[i]:this.p.p5play.groups[i],t&&!t.removed&&(s?t._ensureOverlap(e):t._ensureCollide(e))}for(let t in n){let i=n[t];for(let t of i){let i=this.p.p5play[t],s=i[this._uid];if(!s)continue;let r=i[e._uid]??={};for(let t in s)r[t]=s[t]}}super.push(e),this.parent&&this.p.p5play.groups[this.parent].push(e),e.groups.push(this)}return this.length}size(){return this.length}toString(){return"g"+this.idNum}cull(t,e,i,s,r){if(void 0===i){r=e,t=e=i=s=t}if(isNaN(t)||isNaN(e)||isNaN(i)||isNaN(s))throw new TypeError("The culling boundary must be defined with numbers");if(r&&"function"!=typeof r)throw new TypeError("The callback to group.cull must be a function");let o=this.p.camera.x-this.p.canvas.hw/this.p.camera.zoom,h=this.p.camera.y-this.p.canvas.hh/this.p.camera.zoom,n=-i+o,a=-t+h,l=this.p.width+s+o,p=this.p.height+e+h,d=0;for(let t=0;tl||e.y>p)&&(d++,r?r(e,d):e.remove(),e.removed&&t--))}return d}remove(t){if(void 0===t)return this.removeAll(),void(this._isAllSpritesGroup||(this.removed=!0));let e;if(e="number"==typeof t?t>=0?t:this.length+t:this.indexOf(t),-1==e)return;let i=this[e];return this.splice(e,1),i}splice(t,e){let i=super.splice(t,e);if(!i)return;let s=[];for(let t of i){if(t.removed)continue;let e=this._uid;do{s.push(e);let i=t.groups.findIndex((t=>t._uid==e)),r=t.groups.splice(i,1);e=r[0].parent}while(e)}for(let t of s){let e=this.p.p5play.groups[t];for(let t in n)for(let i in e[t]){if(0==e[t][i])continue;let s;s=i>=1e3?this.p.p5play.sprites[i]:this.p.p5play.groups[i];let r=!1;for(let i of e)if(i[t][s._uid]>0){r=!0;break}r||(e[t][s._uid]=-2,s[t][e._uid]=-2)}}return i}pop(){return this.remove(this.length-1)}shift(){return this.remove(0)}unshift(){return console.error("unshift is not supported for groups"),this.length}removeAll(){for(;this.length>0;)this[0].remove()}_step(){this.__step()}draw(){let t=[...this];t.sort(((t,e)=>t._layer-e._layer));for(let e=0;e=1e3){if(e._isGroup||e._uid>=s)continue;t=this.p.p5play.sprites[s]}else{if(e._isGroup&&e._uid>=s)continue;t=this.p.p5play.groups[s]}let r=e[i][s]+1;t&&0!=r&&-2!=r?(this[i][s]=r,t[i][e._uid]=r):(delete e[i][s],t&&delete t[i][e._uid])}},this.Sprite.prototype.___step=this.Group.prototype.___step=function(){let t,e,i,s,r=this,o=!0;for(let h in n){for(let a in this[h]){if(a>=1e3){if(r._isGroup||r._uid>=a)continue;t=this.p.p5play.sprites[a]}else{if(r._isGroup&&r._uid>=a)continue;t=this.p.p5play.groups[a]}if(r._isGroup||t?._isGroup)continue;if(i=r._hasOverlap[t._uid]??t._hasOverlap[r._uid],o&&!1!==i||!o&&!0!==i)continue;let l=r[h][a];for(let i=0;i<3;i++){if(0==i&&1!=l&&-3!=l)continue;if(1==i&&-1==l)continue;if(2==i&&l>=1)continue;e=n[h][i];let o=this.p.p5play[e][r._uid];if(o){s=o[t._uid],s&&s.call(r,r,t,l);for(let e of t.groups)s=o[e._uid],s&&s.call(r,r,t,l)}let a=this.p.p5play[e][t._uid];if(a){s=a[r._uid],s&&s.call(t,t,r,l);for(let e of r.groups)s=a[e._uid],!s||o&&s==o[e._uid]||s.call(t,t,r,l)}}}o=!1}if(this._removed&&0==Object.keys(this._collisions).length&&0==Object.keys(this._overlappers).length){this._isSprite?delete this.p.p5play.sprites[this._uid]:this.p.p5play.targetVersion>=16&&delete this.p.p5play.groups[this._uid];for(let t in n)for(let e of n[t])delete this.p.p5play[e][this._uid]}},this.Sprite.prototype.addAnimation=this.Group.prototype.addAnimation=this.Sprite.prototype.addAni=this.Group.prototype.addAni=this.Sprite.prototype.addImage=this.Group.prototype.addImage=this.Sprite.prototype.addImg=this.Group.prototype.addImg=function(){if(this.p.p5play.disableImages)return void(this._ani=new this.p.SpriteAnimation);let t,e,i=[...arguments];return i[0]instanceof this.p.SpriteAnimation?(e=i[0],e._addedToSpriteOrGroup&&(e=e.clone()),t=e.name||"default",e.name=t):i[1]instanceof this.p.SpriteAnimation?(t=i[0],e=i[1],e._addedToSpriteOrGroup&&(e=e.clone()),e.name=t):(e=new this.p.SpriteAnimation(this,...i),t=e.name),this.animations[t]=e,this._ani=e,e._addedToSpriteOrGroup=!0,!this._dimensionsUndef||1==e.w&&1==e.h||(this.w=e.w,this.h=e.h),e},this.Sprite.prototype.addAnis=this.Group.prototype.addAnis=this.Sprite.prototype.addAnimations=this.Group.prototype.addAnimations=this.Sprite.prototype.addImages=this.Group.prototype.addImages=this.Sprite.prototype.addImgs=this.Group.prototype.addImgs=function(){let t,e=arguments;1==e.length?t=e[0]:(this.spriteSheet=e[0],t=e[1]);for(let e in t){let i=t[e];this.addAni(e,i)}},this.World=class extends e.World{constructor(){super(new e.Vec2(0,0),!0),this.p=t,this.mod=[],this.origin={x:0,y:0},this.contacts=[],this.on("begin-contact",this._beginContact),this.on("end-contact",this._endContact);let i=this;this._gravity={get x(){return i.m_gravity.x},set x(t){if((t=Math.round(t||0))!=i.m_gravity.x){i.mod[0]=!0;for(let t of i.p.allSprites)t.sleeping=!1;i.m_gravity.x=t}},get y(){return i.m_gravity.y},set y(t){if((t=Math.round(t||0))!=i.m_gravity.y){i.mod[0]=!0;for(let t of i.p.allSprites)t.sleeping=!1;i.m_gravity.y=t}}},this.velocityThreshold=.19,this.mouseTracking??=!0,this.mouseSprite=null,this.mouseSprites=[],this.autoStep=!0}get gravity(){return this._gravity}set gravity(t){this._gravity.x=t.x,this._gravity.y=t.y}get velocityThreshold(){return e.Settings.velocityThreshold}set velocityThreshold(t){e.Settings.velocityThreshold=t}step(t,e,i){for(let t of this.p.allSprites)t.prevPos.x=t.x,t.prevPos.y=t.y,t.prevRotation=t.rotation;super.step(t||1/(this.p._targetFrameRate||60),e||8,i||3);let s=Object.values(this.p.p5play.sprites),r=Object.values(this.p.p5play.groups);for(let t of s)t._step();for(let t of r)t._step();for(let t of s)t.___step();for(let t of r)t.___step();this.autoStep&&(this.autoStep=null)}getSpritesAt(t,s,r,o){o??=!0;const h=new e.Vec2(t/i,s/i),n=new e.AABB;n.lowerBound=new e.Vec2(h.x-.001,h.y-.001),n.upperBound=new e.Vec2(h.x+.001,h.y+.001);let a=[];if(this.queryAABB(n,(t=>(t.getShape().testPoint(t.getBody().getTransform(),h)&&a.push(t),!0))),0==a.length)return[];r??=this.p.allSprites;let l=[];for(let t of a){const e=t.m_body.sprite;e._cameraActiveWhenDrawn==o&&(l.find((t=>t._uid==e._uid))||l.push(e))}return l.sort(((t,e)=>-1*(t._layer-e._layer))),l}getSpriteAt(t,e,i){return this.getSpritesAt(t,e,i)[0]}getMouseSprites(){let t=this.getSpritesAt(this.p.mouse.x,this.p.mouse.y);if(this.p.camera._wasOff){let e=this.getSpritesAt(this.p.camera.mouse.x,this.p.camera.mouse.y,this.p.allSprites,!1);e.length&&(t=[...e,...t])}return t}_beginContact(t){let e=t.m_fixtureA,i=t.m_fixtureB,s="_collisions";e.m_isSensor&&(s="_overlappers"),e=e.m_body.sprite,i=i.m_body.sprite,e[s][i._uid]=0,i[s][e._uid]=0;for(let t of i.groups)(!e[s][t._uid]||e[s][t._uid]<0)&&(e[s][t._uid]=0,t[s][e._uid]=0);for(let t of e.groups){(!i[s][t._uid]||i[s][t._uid]<0)&&(i[s][t._uid]=0,t[s][i._uid]=0);for(let e of i.groups)(!t[s][e._uid]||t[s][e._uid]<0)&&(t[s][e._uid]=0,e[s][t._uid]=0)}}_endContact(t){let e=t.m_fixtureA,i=t.m_fixtureB,s="_collisions";e.m_isSensor&&(s="_overlappers"),e=e.m_body.sprite,i=i.m_body.sprite,e[s][i._uid]=0!=e[s][i._uid]?-2:-4,i[s][e._uid]=0!=i[s][e._uid]?-2:-4;for(let t of i.groups){let i=!1;for(let r of t)if(r[s][e._uid]>=0){i=!0;break}i||(t[s][e._uid]=0!=t[s][e._uid]?-2:-4,e[s][t._uid]=0!=e[s][t._uid]?-2:-4)}for(let t of e.groups){let e=!1;for(let r of t)if(r[s][i._uid]>=0){e=!0;break}if(!e){t[s][i._uid]=0!=t[s][i._uid]?-2:-4,i[s][t._uid]=0!=i[s][t._uid]?-2:-4;for(let e of i.groups)t[s][e._uid]=0!=t[s][e._uid]?-2:-4,e[s][t._uid]=0!=e[s][t._uid]?-2:-4}}}_findContact(t,e,i){let s=e[t][i._uid];if(s)return s;for(let r of i.groups)if(s=e[t][r._uid],s)return s;for(let r of e.groups){if(s=r[t][i._uid],s)return s;for(let e of i.groups)if(r._uid==e._uid&&(s=r[t][e._uid],s))return s}return!1}get allowSleeping(){return this.getAllowSleeping()}set allowSleeping(t){this.setAllowSleeping(t)}},this.Camera=class{constructor(){this.p=t;let e=this;this._pos=this.p.createVector.call(this.p),this.__pos={x:0,y:0,rounded:{}},this.mouse={x:this.p.mouseX,y:this.p.mouseY},this.mouse.pos=this.p.createVector.call(this.p),Object.defineProperty(this.mouse.pos,"x",{get:()=>e.mouse.x,set(t){e.mouse.x=t}}),Object.defineProperty(this.mouse.pos,"y",{get:()=>e.mouse.y,set(t){e.mouse.y=t}}),this.active=!1,this.bound={min:{x:0,y:0},max:{x:0,y:0}},this._zoomIdx=-1,this._zoom=1}get pos(){return this._pos}set pos(t){this.x=t.x,this.y=t.y}get position(){return this._pos}set position(t){this.x=t.x,this.y=t.y}_calcBoundsX(t){let e=this.p.canvas.hw/this._zoom;this.bound.min.x=t-e-100,this.bound.max.x=t+e+100}_calcBoundsY(t){let e=this.p.canvas.hh/this._zoom;this.bound.min.y=t-e-100,this.bound.max.y=t+e+100}get x(){return this._pos.x}set x(t){if(void 0===t||isNaN(t))return;this._pos.x=t;let e=-t+this.p.canvas.hw/this._zoom;this.__pos.x=e,this.p.allSprites.pixelPerfect&&(this.__pos.rounded.x=Math.round(e)),this._calcBoundsX(t)}get y(){return this._pos.y}set y(t){if(void 0===t||isNaN(t))return;this._pos.y=t;let e=-t+this.p.canvas.hh/this._zoom;this.__pos.y=e,this.p.allSprites.pixelPerfect&&(this.__pos.rounded.y=Math.round(e)),this._calcBoundsY(t)}get zoom(){return this._zoom}set zoom(t){if(void 0===t||isNaN(t))return;this._zoom=t;let e=-this._pos.x+this.p.canvas.hw/t,i=-this._pos.y+this.p.canvas.hh/t;this.__pos.x=e,this.__pos.y=i,this.p.allSprites.pixelPerfect&&(this.__pos.rounded.x=Math.round(e),this.__pos.rounded.y=Math.round(i)),this._calcBoundsX(this._pos.x),this._calcBoundsY(this._pos.y)}zoomTo(t,e){if(t==this._zoom)return Promise.resolve(!0);e??=.1;let i=Math.abs(t-this._zoom),s=Math.round(i/e);t{for(let t=0;t0&&(t=t<.1?this.p.map(t,0,.1,30,4):t<.5?this.p.map(t,.1,.5,4,2.5):t<.8?this.p.map(t,.5,.8,2.5,1):t<.9?this.p.map(t,.8,.9,1,.5):this.p.map(t,.9,1,.5,.2)),this._springiness=t,"wheel"==this.type?this._j.setSpringFrequencyHz(t):this._j.setFrequency(t)}get damping(){return"wheel"!=this.type?this._j.getDampingRatio():this._j.getSpringDampingRatio()}set damping(t){"wheel"==this.type?this._j.setSpringDampingRatio(t):this._j.setDampingRatio(t)}get speed(){return this._j.getJointSpeed()}set speed(t){this._j.isMotorEnabled()||this._j.enableMotor(!0),this._j.setMotorSpeed(t)}get motorSpeed(){return this._j.getMotorSpeed()}get enableMotor(){return this._j.isMotorEnabled()}set enableMotor(t){this._j.enableMotor(t)}get maxPower(){return this._j.getMaxMotorTorque()}set maxPower(t){!this._j.isMotorEnabled()&&t&&this._j.enableMotor(!0),this._j.setMaxMotorTorque(t),t||this._j.enableMotor(!1)}get power(){return this._j.getMotorTorque()}get collideConnected(){return this._j.getCollideConnected()}set collideConnected(t){this._j.m_collideConnected=t}remove(){this._removed||(this.spriteA.joints.splice(this.spriteA.joints.indexOf(this),1),this.spriteB.joints.splice(this.spriteB.joints.indexOf(this),1),this.p.world.destroyJoint(this._j),this._removed=!0)}},this.GlueJoint=class extends this.Joint{constructor(t,e){super(...arguments,"glue")}},this.DistanceJoint=class extends this.Joint{constructor(t,i){super(...arguments,"distance");let s=e.DistanceJoint({},t.body,i.body,t.body.getWorldCenter(),i.body.getWorldCenter());this._createJoint(s)}_display(){let t,e;(this.offsetA.x||this.offsetA.y)&&(t=this.spriteA.body.getWorldPoint(this._j.m_localAnchorA),t=r(t.x,t.y,this.spriteA.tileSize)),(this.offsetB.x||this.offsetB.y)&&(e=this.spriteB.body.getWorldPoint(this._j.m_localAnchorB),e=r(e.x,e.y,this.spriteB.tileSize)),this._draw(t?t.x:this.spriteA.x,t?t.y:this.spriteA.y,e?e.x:this.spriteB.x,e?e.y:this.spriteB.y),this.visible=null}},this.WheelJoint=class extends this.Joint{constructor(t,i){super(...arguments,"wheel");let s=e.WheelJoint({maxMotorTorque:1e3,frequencyHz:4,dampingRatio:.7},t.body,i.body,i.body.getWorldCenter(),new e.Vec2(0,1));this._createJoint(s),this._angle="degrees"==this.p._angleMode?90:1.5707963267948966}_display(){let t,e,i=this.spriteA.x,s=this.spriteA.y;if(this.offsetB.x||this.offsetB.y){let i=this.spriteB.body.getWorldPoint(this._j.m_localAnchorB);i=r(i.x,i.y,this.spriteB.tileSize),t=i.x,e=i.y}else t=this.spriteB.x,e=this.spriteB.y;let o=this.p.tan(this.spriteA.rotation),h=this.p.tan(this._angle+this.spriteA.rotation),n=(e-s+o*i-h*t)/(o-h),a=o*(n-i)+s;this._draw(n,a,t,e),this.visible=null}get angle(){return this._angle}set angle(t){t!=this._angle&&(this._angle=t,this._j.m_localXAxisA=new e.Vec2(this.p.cos(t),this.p.sin(t)),this._j.m_localXAxisA.normalize(),this._j.m_localYAxisA=e.Vec2.crossNumVec2(1,this._j.m_localXAxisA))}},this.HingeJoint=class extends this.Joint{constructor(t,i){super(...arguments,"hinge");let s=e.RevoluteJoint({},t.body,i.body,t.body.getWorldCenter());this._createJoint(s)}_display(){const t=this.offsetA.x,e=this.offsetA.y,i=this.spriteA.rotation,s=t*this.p.cos(i)-e*this.p.sin(i),r=t*this.p.sin(i)+e*this.p.cos(i);this._draw(this.spriteA.x+s,this.spriteA.y+r),this.visible=null}get range(){return this.upperLimit-this.lowerLimit}set range(t){t/=2,this.upperLimit=t,this.lowerLimit=-t}get lowerLimit(){let t=this._j.getLowerLimit();return"radians"==this.p._angleMode?t:this.p.degrees(t)}set lowerLimit(t){this._j.isLimitEnabled()||this._j.enableLimit(!0),this.spriteA.body.setAwake(!0),this.spriteB.body.setAwake(!0),"degrees"==this.p._angleMode&&(t=this.p.radians(t)),this._j.m_lowerAngle=t}get upperLimit(){let t=this._j.getUpperLimit();return"radians"==this.p._angleMode?t:this.p.degrees(t)}set upperLimit(t){this._j.isLimitEnabled()||this._j.enableLimit(!0),this.spriteA.body.setAwake(!0),this.spriteB.body.setAwake(!0),"degrees"==this.p._angleMode&&(t=this.p.radians(t)),this._j.m_upperAngle=t}get angle(){let e=this._j.getJointAngle();return"radians"==this.p._angleMode?e:t.radians(e)}},this.RevoluteJoint=this.HingeJoint,this.SliderJoint=class extends this.Joint{constructor(t,i){super(...arguments,"slider");let s=e.PrismaticJoint({lowerTranslation:-1,upperTranslation:1,enableLimit:!0,maxMotorForce:50,motorSpeed:0,enableMotor:!0},t.body,i.body,t.body.getWorldCenter(),new e.Vec2(1,0));this._createJoint(s),this._angle=0}get angle(){return this._angle}set angle(t){t!=this._angle&&(this._angle=t,this._j.m_localXAxisA=new e.Vec2(this.p.cos(t),this.p.sin(t)),this._j.m_localXAxisA.normalize(),this._j.m_localYAxisA=e.Vec2.crossNumVec2(1,this._j.m_localXAxisA))}get range(){return this.upperLimit-this.lowerLimit}set range(t){t/=2,this.upperLimit=t,this.lowerLimit=-t}get lowerLimit(){return this._j.getLowerLimit()/this.spriteA.tileSize*i}set lowerLimit(t){this._j.isLimitEnabled()||this._j.enableLimit(!0),t=t*this.spriteA.tileSize/i,this._j.setLimits(t,this._j.getUpperLimit())}get upperLimit(){return this._j.getUpperLimit()/this.spriteA.tileSize*i}set upperLimit(t){this._j.isLimitEnabled()||this._j.enableLimit(!0),t=t*this.spriteA.tileSize/i,this._j.setLimits(this._j.getLowerLimit(),t)}},this.PrismaticJoint=this.SliderJoint,this.RopeJoint=class extends this.Joint{constructor(t,i){super(...arguments,"rope");let s=e.RopeJoint({maxLength:1},t.body,i.body,t.body.getWorldCenter());this._createJoint(s),this._j.m_localAnchorB.x=0,this._j.m_localAnchorB.y=0}get maxLength(){return t=this._j.getMaxLength(),e=this.spriteA.tileSize,t/e*i;var t,e}set maxLength(t){var e,s;this._j.setMaxLength((e=t,s=this.spriteA.tileSize,e*s/i))}};class l{constructor(){let t=this;Object.defineProperties(this,{x:{get:()=>t._x,set(e){e!=t._x&&(t._x=e,t._avg=.5*(t._x+t._y))},configurable:!0,enumerable:!0},y:{get:()=>t._y,set(e){e!=t._y&&(t._y=e,t._avg=.5*(t._x+t._y))},configurable:!0,enumerable:!0},_x:{value:1,enumerable:!1,writable:!0},_y:{value:1,enumerable:!1,writable:!0},_avg:{value:1,enumerable:!1,writable:!0}})}valueOf(){return this._avg}}!function(){let t=new Float32Array(1),e=new Int32Array(t.buffer)}();function p(t){return!/^(?:(?:\/\*[^(?:\*\/)]*\*\/\s*)|(?:\/\/[^\r\n]*))*\s*(?:(?:(?:async\s(?:(?:\/\*[^(?:\*\/)]*\*\/\s*)|(?:\/\/[^\r\n]*))*\s*)?function|class)(?:\s|(?:(?:\/\*[^(?:\*\/)]*\*\/\s*)|(?:\/\/[^\r\n]*))*)|(?:[_$\w][\w0-9_$]*\s*(?:\/\*[^(?:\*\/)]*\*\/\s*)*\s*\()|(?:\[\s*(?:\/\*[^(?:\*\/)]*\*\/\s*)*\s*(?:(?:['][^']+['])|(?:["][^"]+["]))\s*(?:\/\*[^(?:\*\/)]*\*\/\s*)*\s*\]\())/.test(t.toString())}function d(t,e){let i=t,s=e.toLowerCase();if("triangle"==s?i=[i,-120,3]:"square"==s?i=[i,-90,4]:"pentagon"==s?i=[i,-72,5]:"hexagon"==s?i=[i,-60,6]:"septagon"==s?i=[i,-51.4285714286,7]:"octagon"==s?i=[i,-45,8]:"enneagon"==s?i=[i,-40,9]:"decagon"==s?i=[i,-36,10]:"hendecagon"==s?i=[i,-32.7272727273,11]:"dodecagon"==s&&(i=[i,-30,12]),i==t)throw new Error("Invalid, not a regular polygon: "+e);return i}this.p5play.palettes=[{a:"aqua",b:"black",c:"crimson",d:"darkviolet",e:"peachpuff",f:"olive",g:"green",h:"hotpink",i:"indigo",j:"navy",k:"khaki",l:"lime",m:"magenta",n:"brown",o:"orange",p:"pink",q:"turquoise",r:"red",s:"skyblue",t:"tan",u:"blue",v:"violet",w:"white",x:"gold",y:"yellow",z:"gray"}],this.colorPal=(e,i)=>{if(e instanceof p5.Color)return e;let s;return"number"==typeof i&&(i=t.p5play.palettes[i]),i??=t.p5play.palettes[0],i&&(s=i[e]),""===s||"."===e||" "===e?t.color(0,0,0,0):t.color(s||e)},this.spriteArt=(e,i,s)=>{i??=1,"number"==typeof s&&(s=t.p5play.palettes[s]),s??=t.p5play.palettes[0];let r=e;"string"==typeof e&&(r=(e=(e=(e=e.trim()).replace(/\r*\n\t+/g,"\n")).replace(/\s+$/g,"")).split("\n"));let o=0;for(let t of r)t.length>o&&(o=t.length);let h=r.length,n=t.createImage(o*i,h*i);n.loadPixels();for(let t=0;tnew Promise(t?e=>{setTimeout(e,t)}:requestAnimationFrame),this.sleep=t=>this.delay(t),this.play=t=>{if(!t?.play)throw new Error("Tried to play your sound but it wasn't a sound object.");return new Promise((e=>{t.play(),t.onended((()=>e()))}))};{let B=location.hostname;switch(B){case"":case"127.0.0.1":case"localhost":case"p5play.org":case"editor.p5js.org":case"codepen.io":case"codera.app":case"cdpn.io":case"glitch.com":case"replit.com":case"stackblitz.com":case"jsfiddle.net":case"aijs-912fe.web.app":break;default:if(/^[\d\.]+$/.test(B)||B.endsWith("stackblitz.io")||B.endsWith("glitch.me")||B.endsWith("repl.co")||B.endsWith("codehs.com")||B.endsWith("openprocessing.org")||location.origin.endsWith("preview.p5js.org"))break;!async function(){if(document.getElementById("p5play-intro"))return;t._incrementPreload();let e=document.createElement("div");e.id="p5play-intro",e.style="position: absolute; width: 100%; height: 100%; top: 0; left: 0; z-index: 1000; background-color: black;";let i=document.createElement("img");i.src="https://p5play.org/v3/made_with_p5play.png",i.style="position: absolute; top: 50%; left: 50%; width: 40vh; height: 20vh; margin-left: -20vh; margin-top: -10vh; z-index: 1000; opacity: 0; transition: opacity 0.1s ease-in-out;",document.body.append(e),e.append(i),await t.delay(100),i.style.opacity="1",i.style.transition="scale 1.4s, opacity 0.4s ease-in-out",i.style.scale="1.1",await t.delay(1100),i.style.opacity="0",await t.delay(300),e.style.display="none",e.remove(),document.getElementById("p5play-intro")?.remove(),t._decrementPreload()}()}}let u=p5.disableFriendlyErrors;p5.disableFriendlyErrors=!0,this.canvas=this.canvas;const _=this.createCanvas;this.createCanvas=function(){let e,i,s,r,o=[...arguments],h=!1,n=!1;if("string"==typeof o[0]&&(o[0].includes(":")?s=o[0].split(":"):(o[2]=o[0],o[0]=void 0),"fullscreen"==o[1]&&(h=!0)),o[0]?"number"==typeof o[0]&&"number"!=typeof o[1]&&(o[2]=o[1],o[1]=o[0]):(o[0]=window.innerWidth,o[1]=window.innerHeight,h=!0),"string"==typeof o[2]){let t=o[2].toLowerCase();"p2d"!=t&&"webgl"!=t&&(t=t.split(" "),o.pop()),"pixelated"==t[0]&&(n=!0,t[1]?r=Number(t[1].slice(1)):h=!0,s=[o[0],o[1]]),"fullscreen"==t[0]&&(h=!0)}if(s){let t=Number(s[0]),h=Number(s[1]);r?(e=t*r,i=h*r):(e=window.innerWidth,i=window.innerWidth*(h/t),i>window.innerHeight&&(e=window.innerHeight*(t/h),i=window.innerHeight)),e=Math.round(e),i=Math.round(i),n||(o[0]=e,o[1]=i)}let a=_.call(t,...o);this.canvas.tabIndex=0,this.canvas.w=o[0],this.canvas.h=o[1],this.canvas.addEventListener("keydown",(function(t){" "!=t.key&&"/"!=t.key&&"ArrowUp"!=t.key&&"ArrowDown"!=t.key&&"ArrowLeft"!=t.key&&"ArrowRight"!=t.key||t.preventDefault()})),this.canvas.addEventListener("mouseover",(()=>{this.mouse.isOnCanvas=!0,this.mouse.active=!0})),this.canvas.addEventListener("mouseleave",(()=>{this.mouse.isOnCanvas=!1})),this.canvas.addEventListener("touchstart",(t=>t.preventDefault())),this.canvas.addEventListener("contextmenu",(t=>t.preventDefault())),this.canvas.resize=this.resizeCanvas,this.canvas.hw=.5*this.canvas.w,this.canvas.hh=.5*this.canvas.h,this.camera.x=this.canvas.hw,this.camera.y=this.canvas.hh,u||(p5.disableFriendlyErrors=!1);let l="\n.p5Canvas, .q5Canvas {\n\toutline: none;\n\t-webkit-touch-callout: none;\n\t-webkit-text-size-adjust: none;\n\t-webkit-user-select: none;\n\toverscroll-behavior: none;\n}\nmain {\n\toverscroll-behavior: none;\n}";h&&(l="html,\nbody,\n"+l,l+="\nhtml, body {\n\tmargin: 0;\n\tpadding: 0;\n\toverflow: hidden;\n\theight: 100%;\n}\nmain {\n\tmargin: auto;\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\talign-content: center;\n\tjustify-content: center;\n\theight: 100%;\n}"),n&&(l+=`\n#${this.canvas.id} {\n\timage-rendering: pixelated;\n\twidth: ${e}px!important;\n\theight: ${i}px!important;\n}`);let p=document.createElement("style");p.innerHTML=l,document.head.appendChild(p),n&&(t.pixelDensity(1),t.noSmooth());let d=navigator.userAgent.indexOf("iPhone OS");if(d>-1){let e=navigator.userAgent.substring(d+10,d+12);this.p5play.version=e,e<16&&t.pixelDensity(1),this.p5play.os.platform="iOS",this.p5play.os.version=e}else void 0!==navigator.userAgentData&&(this.p5play.os.platform=navigator.userAgentData.platform);return a},this.Canvas=class{constructor(t,e,i){}get w(){}get width(){}get h(){}get height(){}resize(){}},this.Canvas=function(){return t.createCanvas(...arguments)};const c=this.resizeCanvas;this.resizeCanvas=(t,e)=>{c.call(this,t,e),this.canvas.hw=.5*this.canvas.w,this.canvas.hh=.5*this.canvas.h,this.camera._pos.x=this.canvas.hw,this.camera._pos.y=this.canvas.hh};const f=this.background;this.background=function(){let t,e=arguments;1==e.length&&("string"==typeof e[0]||e[0]instanceof p5.Color)&&(t=this.colorPal(e[0])),void 0!==t?f.call(this,t):f.call(this,...e)};const g=this.fill;this.fill=function(){let t,e=arguments;1==e.length&&(t=this.colorPal(e[0])),void 0!==t?g.call(this,t):g.call(this,...e)};const y=this.stroke;this.stroke=function(){let t,e=arguments;1==e.length&&(t=this.colorPal(e[0])),void 0!==t?y.call(this,t):y.call(this,...e)},this.p5play.images={onLoad:t=>{}},this.p5play.disableImages=!1;const m=this.loadImage;this.loadImage=this.loadImg=function(){if(this.p5play.disableImages)return t._decrementPreload(),{w:16,width:16,h:16,height:16,pixels:[]};let e,i=arguments,s=i[0],r=t.p5play.images[s];if("function"==typeof i[i.length-1]&&(e=i[i.length-1]),r)return 1==r.width&&1==r.height||!r.pixels.length?e?(r.cbs.push(e),r.calls++):t._decrementPreload():(e&&e(),t._decrementPreload()),r;return r=m.call(t,s,(e=>{e.w=e.width,e.h=e.height;for(let t of e.cbs)t(e);for(let i=1;ithis.maxSize&&this.gc()}get(t){const e=super.get(t);return e&&(e.lastAccessed=Date.now()),e}gc(){let t,e=1/0,i=0;for(const[s,r]of this.entries())r.lastAccessed(e&&(I._tic.maxSize=e),void 0!==t&&(I._textCache=t),I._textCache),I.createTextImage=(t,e,i)=>{let s=I._textCache;I._textCache=!0,I._useCache=!0,I.text(t,0,0,e,i),I._useCache=!1;let r=x(t,e,i);return I._textCache=s,I._tic.get(r)};const W=I.text;I.text=(t,e,i,s,r)=>{if(void 0===t)return;t=t.toString();const o=I._renderer;if(!o._doFill&&!o._doStroke)return;let h,n,a,l,p,d,u;const _=I.canvas.getContext("2d");let c=_.getTransform();if(!(I._useCache||I._textCache&&(0!=c.b||0!=c.c)))return W.call(I,t,e,i,s,r);if(a=x(t,s,r),n=I._tic.get(a),n)return void I.textImage(n,e,i);let f=I.pixelDensity(),g=I.createGraphics.call(I,1,1);h=g.canvas.getContext("2d"),h.font=`${o._textStyle} ${o._textSize*f}px ${o._textFont}`;let y=t.split("\n");l=0,p=o._textLeading*f*y.length;let m=h.measureText(" ");d=m.fontBoundingBoxAscent,u=m.fontBoundingBoxDescent,r??=p+u,g.resizeCanvas(Math.ceil(g.textWidth(t)),Math.ceil(r)),h.fillStyle=_.fillStyle,h.strokeStyle=_.strokeStyle,h.lineWidth=_.lineWidth*f;let v=h.fillStyle;o._fillSet||(h.fillStyle="black");for(let t=0;tr));t++);o._fillSet||(h.fillStyle=v),n=g.get(),n.width/=f,n.height/=f,n._ascent=d/f,n._descent=u/f,I._tic.set(a,n),I.textImage(n,e,i)},I.textImage=(t,e,i)=>{let s=I._renderer._imageMode;I.imageMode.call(I,"corner");const r=I.canvas.getContext("2d");let o;"center"==r.textAlign?e-=.5*t.width:"right"==r.textAlign&&(e-=t.width),"alphabetic"==r.textBaseline?i-=I._renderer._textLeading:o=I._renderer._textLeading-I._renderer._textSize,"middle"==r.textBaseline?i-=t._descent+.5*t._ascent+o:"bottom"==r.textBaseline?i-=t._ascent+t._descent+o:"top"==r.textBaseline&&(i-=t._descent+o),I.image.call(I,t,e,i),I.imageMode.call(I,s)}}let w={generic:["Ah! I found an error","Oh no! Something went wrong","Oof! Something went wrong","Houston, we have a problem","Whoops, having trouble here"],Sprite:{constructor:{base:"Sorry I'm unable to make a new Sprite",0:"What is $0 for? If you're trying to specify the x position of the sprite, please specify the y position as well.",1:"If you're trying to specify points for a chain Sprite, please use an array of position arrays.\n$0",2:"Invalid input parameters: $0"},hw:{0:"I can't change the halfWidth of a Sprite directly, change the sprite's width instead."},hh:{1:"I can't change the halfHeight of a Sprite directly, change the sprite's height instead."},rotate:{0:"Can't use this function on a sprite with a static collider, try changing the sprite's collider type to kinematic.",1:'Can\'t use "$0" for the angle of rotation, it must be a number.'},rotateTo:{},rotateTowards:{},changeAnimation:'I can\'t find any animation named "$0".',collide:{0:"I can't make that sprite collide with $0. Sprites can only collide with another sprite or a group.",1:"The collision callback has to be a function.",2:"You're trying to check for an collision with a sprite or group that doesn't exist!"},overlap:{0:"I can't make that sprite overlap with $0. Sprites can only overlap with another sprite or a group.",1:"The overlap callback has to be a function.",2:"You're trying to check for an overlap with a sprite or group that doesn't exist!"}},SpriteAnimation:{constructor:{base:"Hey so, I tried to make a new SpriteAnimation but couldn't",0:'I don\'t know how to display this type of image: "$0". I can only use ".png" image files.',1:"The name of the animation must be the first input parameter."},frame:"Index $0 out of bounds. That means there is no frame $0 in this animation. It only has $1 frames!"},Group:{constructor:{base:"Hmm awkward! Well it seems I can't make that new Group you wanted"}}};w.Group.collide=w.Sprite.collide,w.Group.overlap=w.Sprite.overlap,w.Sprite.rotateTo[0]=w.Sprite.rotateTowards[0]=w.Sprite.rotate[0];class b extends Error{constructor(t,e,i){super(),"string"!=typeof t&&(i=e,e=t,t=(t=this.stack.match(/\n\s*at ([^\(]*)/)[1]).slice(0,-1)),"number"!=typeof e&&(i=e,e=void 0),"new"==t.slice(0,3)&&(t=t.slice(4));let s=(t=t.split("."))[0];t=t[1]||"constructor";let r=this.stack.match(/\/([^p\/][^5][^\/:]*:[^\/:]+):/);r&&(r=r[1].split(":"),r=" in "+r[0]+" at line "+r[1]),r=" using "+s+"."+t+". ",i=i||[];let o,h=w[s][t];o=h.base?h.base+r:w.generic[Math.floor(Math.random()*w.generic.length)]+r,void 0!==e&&(h=h[e]),h=h.replace(/\$([0-9]+)/g,((t,e)=>i[e])),o+=h,p5._friendlyError(o,t)}}this.allSprites=new this.Group,this.world=new this.World,this.camera=new this.Camera,this.InputDevice=class{constructor(){this.holdThreshold=12,this._default=0}_init(t){for(let e of t)this[e]=0}_ac(t){return t}presses(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),1==this[t]||-3==this[t]}pressing(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),-3==this[t]?1:this[t]>0?this[t]:0}pressed(t){return this.released(t)}holds(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),this[t]==this.holdThreshold}holding(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),this[t]>=this.holdThreshold?this[t]:0}held(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),-2==this[t]}released(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),this[t]<=-1}releases(t){return this.released(t)}},this._Mouse=class extends this.InputDevice{constructor(){super(),this._default="left";let e=this;this._pos=t.createVector.call(t),Object.defineProperty(this._pos,"x",{get:()=>e.x,set(t){e.x=t}}),Object.defineProperty(this._pos,"y",{get:()=>e.y,set(t){e.y=t}}),this.x,this.y,this.left,this.center,this.right;this._init(["x","y","left","center","right"]),this.drag={left:0,center:0,right:0},this.isOnCanvas=!1,this.active=!1,this._visible=!0,this._cursor="default"}_ac(t){return"left"==(t=t.toLowerCase()).slice(0,4)?t="left":"right"==t.slice(0,5)?t="right":"middle"==t.slice(0,6)&&(t="center"),t}update(){this.x=(t.mouseX-t.canvas.hw)/t.camera.zoom+t.camera.x,this.y=(t.mouseY-t.canvas.hh)/t.camera.zoom+t.camera.y,t.camera.mouse.x=t.mouseX,t.camera.mouse.y=t.mouseY}get pos(){return this._pos}get position(){return this._pos}get cursor(){return t.canvas.style.cursor}set cursor(e){e!=this._cursor&&(t.cursor(e),this._cursor=e)}get visible(){return this._visible}set visible(e){this._visible=e,t.canvas.style.cursor=e?"default":"none"}drags(t){return t??=this._default,1==this.drag[t]}dragging(t){return t??=this._default,this.drag[t]>0?this.drag[t]:0}dragged(t){return t??=this._default,this.drag[t]<=-1}},this.mouse=new this._Mouse,this._SpriteMouse=class extends this._Mouse{constructor(){super(),this.hover=0}hovers(){return 1==this.hover}hovering(){return this.hover>0?this.hover:0}hovered(){return this.hover<=-1}};const S=function(t){if(this.mouse.active=!0,this.mouse[t]++,this.world.mouseSprites.length){let e=this.world.mouseSprite?.mouse;e&&(e[t]=0,e.hover=0,e.drag[t]=0),ms=this.world.mouseSprites[0],this.world.mouseSprite=ms,e=ms.mouse,e[t]=1,e.hover<=0&&(e.hover=1)}},C=t._onmousedown;t._onmousedown=function(t){if(!this._setupDone)return;let e="left";1===t.button?e="center":2===t.button&&(e="right"),S.call(this,e),C.call(this,t)};const A=t._ontouchstart;t._ontouchstart=function(t){if(!this._setupDone)return;A.call(this,t);let e=this.touches.at(-1);e.duration=0,e.presses=function(){return 1==this.duration||-3==this.duration},e.pressing=function(){return this.duration>0?this.duration:0},e.released=function(){return this.duration<=-1},1==this.touches.length&&(this.mouse.update(),this.world.mouseSprites=this.world.getMouseSprites()),S.call(this,"left")};const k=function(t){let e=this.mouse;if(e[t]>0&&e.drag[t]<=0){e.drag[t]=1;let i=this.world.mouseSprite?.mouse;i&&(i.drag[t]=1)}},z=t._onmousemove;t._onmousemove=function(t){if(!this._setupDone)return;let e="left";1===t.button?e="center":2===t.button&&(e="right"),k.call(this,e),z.call(this,t)};const M=t._ontouchmove;t._ontouchmove=function(t){this._setupDone&&(M.call(this,t),k.call(this,"left"))};const j=function(t){let e=this.mouse;e[t]>=e.holdThreshold?e[t]=-2:e[t]>1?e[t]=-1:e[t]=-3,e.drag[t]>0&&(e.drag[t]=-1);let i=this.world.mouseSprite?.mouse;i&&(i.hover>1?(i[t]>=this.mouse.holdThreshold?i[t]=-2:i[t]>1?i[t]=-1:i[t]=-3,i.drag[t]>0&&(i.drag[t]=-1)):(i[t]=0,i.drag[t]=0))},O=t._onmouseup;t._onmouseup=function(t){if(!this._setupDone)return;let e="left";1===t.button?e="center":2===t.button&&(e="right"),j.call(this,e),O.call(this,t)};const T=t._ontouchend;if(t._ontouchend=function(t){this._setupDone&&(T.call(this,t),j.call(this,"left"))},delete this._Mouse,this._KeyBoard=class extends this.InputDevice{#e;constructor(){super(),this._default=" ",this.alt=0,this.arrowUp=0,this.arrowDown=0,this.arrowLeft=0,this.arrowRight=0,this.backspace=0,this.capsLock=0,this.control=0,this.enter=0,this.meta=0,this.shift=0,this.tab=0;let t=this._simpleKeyControls={arrowUp:"up",arrowDown:"down",arrowLeft:"left",arrowRight:"right"};t.w=t.W="up",t.s=t.S="down",t.a=t.A="left",t.d=t.D="right",t.i=t.I="up2",t.k=t.K="down2",t.j=t.J="left2",t.l=t.L="right2"}_ac(t){if(1!=t.length){if(!isNaN(t)){if(38==t)return"arrowUp";if(40==t)return"arrowDown";if(37==t)return"arrowLeft";if(39==t)return"arrowRight";if(t>=10)throw new Error("Use key names with the keyboard input functions, not keyCode numbers!");return t}t=t.replaceAll(/[ _-]/g,"")}if(1!=(t=t.toLowerCase()).length){if("arrowup"==t)return"arrowUp";if("arrowdown"==t)return"arrowDown";if("arrowleft"==t)return"arrowLeft";if("arrowright"==t)return"arrowRight";if("capslock"==t)return"capsLock"}return t}_pre(t){(!this[t]||this[t]<0)&&(this[t]=1)}_rel(t){this[t]>=this.holdThreshold?this[t]=-2:this[t]>1?this[t]=-1:this[t]=-3}get cmd(){return this.meta}get command(){return this.meta}get ctrl(){return this.control}get space(){return this[" "]}get spacebar(){return this[" "]}get opt(){return this.alt}get option(){return this.alt}get win(){return this.meta}get windows(){return this.meta}},this.kb=new this._KeyBoard,delete this._KeyBoard,this.keyboard=this.kb,navigator.keyboard){const G=navigator.keyboard;window==window.top?G.getLayoutMap().then((t=>{"w"!=t.get("KeyW")&&(this.p5play.standardizeKeyboard=!0)})):this.p5play.standardizeKeyboard=!0}else this.p5play.standardizeKeyboard=!0;function P(t){let e=t.code;return 4==e.length&&"Key"==e.slice(0,3)?e[3].toLowerCase():t.key}const L=t._onkeydown;t._onkeydown=function(t){let e=t.key;if(this.p5play.standardizeKeyboard&&(e=P(t)),e.length>1)e=e[0].toLowerCase()+e.slice(1);else{let t=e.toLowerCase(),i=e.toUpperCase();t!=i&&(e!=i?this.kb._pre(i):this.kb._pre(t))}this.kb._pre(e);let i=this.kb._simpleKeyControls[e];i&&this.kb._pre(i),L.call(this,t)};const D=t._onkeyup;t._onkeyup=function(t){let e=t.key;if(this.p5play.standardizeKeyboard&&(e=P(t)),e.length>1)e=e[0].toLowerCase()+e.slice(1);else{let t=e.toLowerCase(),i=e.toUpperCase();t!=i&&(e!=i?this.kb._rel(i):this.kb._rel(t))}this.kb._rel(e);let i=this.kb._simpleKeyControls[e];if(i&&this.kb._rel(i),t.shiftKey){let t=e.toLowerCase();this.kb[t]>0&&this.kb._rel(t)}D.call(this,t)},this._Contro=class extends this.InputDevice{constructor(t){super(),this._default="a",this.connected=!0;this._init(["a","b","x","y","l","r","lt","rt","select","start","lsb","rsb","up","down","left","right","leftTrigger","rightTrigger"]),this.leftStick={x:0,y:0},this.rightStick={x:0,y:0},this._btns={a:0,b:1,x:2,y:3,l:4,r:5,lt:6,rt:7,select:8,start:9,lsb:10,rsb:11,up:12,down:13,left:14,right:15},this._axes={leftStick:{x:0,y:1},rightStick:{x:2,y:3},leftTrigger:4,rightTrigger:5},t.id.includes("GuliKit")&&(this._btns.a=1,this._btns.b=0,this._btns.x=3,this._btns.y=2),this.gamepad=t,this.id=t.id}_ac(t){return"lb"==(t=t.toLowerCase())?t="l":"rb"==t?t="r":"leftstickbutton"==t?t="lsb":"rightstickbutton"==t&&(t="rsb"),t}_update(){if(!this.connected)return;if(this.gamepad=navigator.getGamepads()[this.gamepad.index],!this.gamepad?.connected)return;let t=this.gamepad;for(let e in this._btns){let i=this._btns[e],s=t.buttons[i];s&&(s.pressed?this[e]++:this[e]=this[e]>0?-1:0)}return this.leftStick.x=t.axes[this._axes.leftStick.x],this.leftStick.y=t.axes[this._axes.leftStick.y],this.rightStick.x=t.axes[this._axes.rightStick.x],this.rightStick.y=t.axes[this._axes.rightStick.y],void 0!==t.axes[this._axes.leftTrigger]?(this.leftTrigger=t.axes[this._axes.leftTrigger],this.rightTrigger=t.axes[this._axes.rightTrigger]):(this.leftTrigger=t.buttons[this._btns.lt].value,this.rightTrigger=t.buttons[this._btns.rt].value),!0}get ls(){return this.leftStick}get rs(){return this.rightStick}get lb(){return this.l}get rb(){return this.r}get leftStickButton(){return this.lsb}get rightStickButton(){return this.rsb}},this._Contros=class extends Array{constructor(){super();let t=this;window.addEventListener("gamepadconnected",(e=>{t._onConnect(e.gamepad)})),window.addEventListener("gamepaddisconnected",(e=>{t._onDisconnect(e.gamepad)})),this.presses,this.pressing,this.pressed,this.holds,this.holding,this.held,this.released;let e=["presses","pressing","pressed","holds","holding","held","released"];for(let t of e)this[t]=e=>{if(this[0])return this[0][t](e)};this.a=0,this.b=0,this.x=0,this.y=0,this.l=0,this.r=0,this.lt=0,this.rt=0,this.select=0,this.start=0,this.lsb=0,this.rsb=0,this.up=0,this.down=0,this.left=0,this.right=0,this.leftTrigger=0,this.rightTrigger=0,this.lb=0,this.rb=0,this.leftStickButton=0,this.rightStickButton=0;let i=["connected","a","b","x","y","l","r","lt","rt","select","start","lsb","rsb","up","down","left","right","leftTrigger","rightTrigger","lb","rb","leftStickButton","rightStickButton"];for(let e of i)Object.defineProperty(this,e,{get:()=>t[0]?t[0][e]:0});this.leftStick,this.rightStick,i=["leftStick","rightStick"];for(let e of i){this[e]={};for(let i of["x","y"])Object.defineProperty(this[e],i,{get:()=>t[0]?t[0][e][i]:0})}if(!navigator?.getGamepads)return;let s=navigator.getGamepads();for(let t of s)t&&this._onConnect(t)}_onConnect(e){if(!e)return;for(let t=0;tthis.p5play._fps,this.p5play._fpsArr=[60],this.renderStats=(t,e)=>{let i=this.p5play._renderStats;void 0===i.show&&(1==this.allSprites.tileSize||this.allSprites.tileSize>16?i.fontSize=16:i.fontSize=10,i.gap=1.25*i.fontSize,console.warn("renderStats() uses inaccurate FPS approximations. Even if your game runs at a solid 60hz display rate, the fps calculations shown may be lower. The only way to get accurate results is to use your web browser's performance testing tools.")),i.x=t||10,i.y=e||20,i.show=!0}})),p5.prototype.registerMethod("pre",(function(){this.p5play._fps&&(this.p5play._preDrawFrameTime=performance.now()),this.p5play.spritesDrawn=0,this.mouse.update(),this.contro._update()})),p5.prototype.registerMethod("post",(function(){this.p5play._inPostDraw=!0,this.allSprites.autoCull&&this.allSprites.cull(1e4),this.allSprites._autoDraw&&(this.camera.on(),this.allSprites.draw(),this.camera.off()),this.allSprites._autoDraw??=!0;let t=this.p5play._renderStats;if(t.show){if(1==this.frameCount||this.frameCount%60==0){let t,e=this.p5play._fpsArr.reduce(((t,e)=>t+e));e=Math.round(e/this.p5play._fpsArr.length),this.p5play._fpsAvg=e,this.p5play._fpsMin=Math.min(...this.p5play._fpsArr),this.p5play._fpsMax=Math.max(...this.p5play._fpsArr),this.p5play._fpsArr=[],t=e>55?this.color(30,255,30):e>25?this.color(255,100,30):this.color(255,30,30),this.p5play._statsColor=t}this.p5play._fpsArr.push(this.getFPS()),this.push(),this.fill(0,0,0,128),this.rect(t.x-5,t.y-t.fontSize,8.5*t.fontSize,4*t.gap+5),this.fill(this.p5play._statsColor),this.textAlign("left"),this.textSize(t.fontSize),this.textFont("monospace");let e=t.x,i=t.y;this.text("sprites: "+this.p5play.spritesDrawn,e,i),this.text("fps avg: "+this.p5play._fpsAvg,e,i+t.gap),this.text("fps min: "+this.p5play._fpsMin,e,i+2*t.gap),this.text("fps max: "+this.p5play._fpsMax,e,i+3*t.gap),this.pop(),t.show=!1}this.world.autoStep&&this.world.step(),this.world.autoStep??=!0,this.allSprites._autoUpdate&&this.allSprites.update(),this.allSprites._autoUpdate??=!0;for(let t of this.allSprites)t.autoDraw??=!0,t.autoUpdate??=!0;for(let t in this.kb)"holdThreshold"!=t&&(this.kb[t]<0?this.kb[t]=0:this.kb[t]>0&&this.kb[t]++);let e=this.mouse,i=this.world.mouseSprite?.mouse;for(let t of["left","center","right"])e[t]<0?e[t]=0:e[t]>0&&e[t]++,i?.hover&&(i[t]=e[t]),e.drag[t]<0?e.drag[t]=0:e.drag[t]>0&&e.drag[t]++,i&&(i.drag[t]=e.drag[t]);if(this.world.mouseTracking){let t=this.world.getMouseSprites();for(let e=0;e0?i.mouse.hover=-1:i.mouse.hover<0&&(i.mouse.hover=0)}e.left<=0&&e.center<=0&&e.right<=0&&(this.world.mouseSprite=null);let s=this.world.mouseSprite,r=e.drag.left>0||e.drag.center>0||e.drag.right>0;for(let e of this.world.mouseSprites)if(!t.includes(e)){let t=e.mouse;t.hover>0&&(t.hover=-1,t.left=t.center=t.right=0),r||e!=s||(this.world.mouseSprite=s=null)}s&&(t.includes(s)||t.push(s),i.x=s.x-e.x,i.y=s.y-e.y),this.world.mouseSprites=t}this.camera.off(),this.p5play._fps&&(this.p5play._postDrawFrameTime=performance.now(),this.p5play._fps=Math.round(1e3/(this.p5play._postDrawFrameTime-this.p5play._preDrawFrameTime))||1),this.p5play._inPostDraw=!1})); +p5.prototype.registerMethod("init",(function(){if(void 0===window.planck)throw"planck.js must be loaded before p5play";const t=this,e=planck,i=60;if(void 0===window._p5play_gtagged&&"undefined"==typeof process){let F=document.createElement("script");F.src="https://www.googletagmanager.com/gtag/js?id=G-EHXNCTSYLK",F.async=!0,document.head.append(F),window._p5play_gtagged=!0,F.onload=()=>{window.dataLayer??=[],window.gtag=function(){dataLayer.push(arguments)},gtag("js",new Date),gtag("config","G-EHXNCTSYLK"),gtag("event","p5play_v3_14")}}this.angleMode("degrees");const s=(t,s,r)=>new e.Vec2(t*r/i,s*r/i),r=(t,s,r)=>new e.Vec2(t/r*i,s/r*i),o=t=>Math.abs(t)<=e.Settings.linearSlop,h=t=>Math.abs(t-Math.round(t))<=e.Settings.linearSlop?Math.round(t):t,n={_collisions:["_collides","_colliding","_collided"],_overlappers:["_overlaps","_overlapping","_overlapped"]};this.P5Play=class{constructor(){this.sprites={},this.groups={},this.groupsCreated=0,this.spritesCreated=0,this.spritesDrawn=0,this.disableImages=!1,this.palettes=[],this.targetVersion=0,this.os={},this.context="web",window.matchMedia?this.hasMouse=!window.matchMedia("(any-hover: none)").matches:this.hasMouse=!0,this.standardizeKeyboard=!1,this._renderStats={},this._collides={},this._colliding={},this._collided={},this._overlaps={},this._overlapping={},this._overlapped={}}},this.p5play=new this.P5Play,delete this.P5Play;const a=console.log;this.log=console.log,this.Sprite=class{constructor(s,r,o,n,a){this.p=t,this._isSprite=!0,this.idNum;let u,_,c=[...arguments];if(void 0!==c[0]&&c[0]._isGroup&&(u=c[0],c=c.slice(1)),void 0!==c[0]&&isNaN(c[0])&&("string"==typeof c[0]||c[0]instanceof this.p.SpriteAnimation||c[0]instanceof p5.Image)&&(_=c[0],c=c.slice(1)),1==c.length&&"number"==typeof c[0])throw new b("Sprite",0,[c[0]]);if(Array.isArray(c[0])){if(s=void 0,r=void 0,o=c[0],n=void 0,a=c[1],Array.isArray(a))throw new b("Sprite",1,[`[[${o}], [${n}]]`])}else s=c[0],r=c[1],o=c[2],n=c[3],a=c[4];"string"==typeof o&&(a=o,o=void 0),"string"==typeof n&&(!function(t){if("d"==t||"s"==t||"k"==t||"n"==t)return!0;let e=t.slice(0,2);return"dy"==e||"st"==e||"ki"==e||"no"==e}(n)?o=d(o,n):a=n,n=void 0),this.idNum=this.p.p5play.spritesCreated,this._uid=1e3+this.idNum,this.p.p5play.sprites[this._uid]=this,this.p.p5play.spritesCreated++,this.groups=[],this.animations=new this.p.SpriteAnimations,this.joints=[],this.joints.removeAll=()=>{for(let t of this.joints)t.remove()},this.watch,this.mod={},this._removed=!1,this._life=2147483647,this._visible=!0,this._pixelPerfect=!1,this._aniChangeCount=0,this._hasOverlap={},this._collisions={},this._overlappers={},u??=this.p.allSprites,this.tileSize=u.tileSize||1;let f=this;this._position={x:0,y:0},this._pos=t.createVector.call(t),Object.defineProperty(this._pos,"x",{get(){if(!f.body)return f._position.x;let t=f.body.getPosition().x/f.tileSize*i;return h(t)},set(t){if(f.body){let s=new e.Vec2(t*f.tileSize/i,f.body.getPosition().y);f.body.setPosition(s)}f._position.x=t}}),Object.defineProperty(this._pos,"y",{get(){if(!f.body)return f._position.y;let t=f.body.getPosition().y/f.tileSize*i;return h(t)},set(t){if(f.body){let s=new e.Vec2(f.body.getPosition().x,t*f.tileSize/i);f.body.setPosition(s)}f._position.y=t}}),this._velocity={x:0,y:0},this._vel=t.createVector.call(t),Object.defineProperties(this._vel,{x:{get(){let t;return t=f.body?f.body.getLinearVelocity().x:f._velocity.x,h(t/f.tileSize)},set(t){t*=f.tileSize,f.body?f.body.setLinearVelocity(new e.Vec2(t,f.body.getLinearVelocity().y)):f._velocity.x=t}},y:{get(){let t;return t=f.body?f.body.getLinearVelocity().y:f._velocity.y,h(t/f.tileSize)},set(t){t*=f.tileSize,f.body?f.body.setLinearVelocity(new e.Vec2(f.body.getLinearVelocity().x,t)):f._velocity.y=t}}}),this._mirror={_x:1,_y:1,get x(){return this._x<0},set x(t){f.watch&&(f.mod[22]=!0),this._x=t?-1:1},get y(){return this._y<0},set y(t){f.watch&&(f.mod[22]=!0),this._y=t?-1:1}},this._heading="right",this._layer=u._layer,this._layer??=this.p.allSprites._getTopLayer()+1,u.dynamic&&(a??="dynamic"),u.kinematic&&(a??="kinematic"),u.static&&(a??="static"),a??=u.collider,a&&"string"==typeof a||(a="dynamic"),this.collider=a,s??=u.x,void 0===s&&(s=this.p.width/this.tileSize/2,o&&(this._vertexMode=!0)),r??=u.y,void 0===r&&(r=this.p.height/this.tileSize/2);let g=!1;if(void 0===o&&(o=u.w||u.width||u.d||u.diameter||u.v||u.vertices,n||u.d||u.diameter||(n=u.h||u.height,g=!0)),"function"==typeof s&&(s=s(u.length)),"function"==typeof r&&(r=r(u.length)),"function"==typeof o&&(o=o(u.length)),"function"==typeof n&&(n=n(u.length)),this.x=s,this.y=r,!u._isAllSpritesGroup&&!_)for(let t in u.animations){_=t;break}for(let t=u;t;t=this.p.p5play.groups[t.parent])this.groups.push(t);if(this.groups.reverse(),_){_ instanceof p5.Image?this.addAni(_):"string"==typeof _?this._changeAni(_):this._ani=_.clone();let t=this.tileSize;o||1==this._ani.w&&1==this._ani.h||(o=this._ani.w/t,n??=this._ani.h/t)}if(this.groups=[],this.mouse=new this.p._SpriteMouse,this._angle=0,this._rotationSpeed=0,this._bearing=0,this._scale=new l,Object.defineProperty(this._scale,"x",{get(){return this._x},set(t){if(t==this._x)return;f.watch&&(f.mod[28]=!0);let e=t/this._x;f._w*=e,f._hw*=e,f._resizeColliders({x:e,y:1}),this._x=t,this._avg=.5*(this._x+this._y)}}),Object.defineProperty(this._scale,"y",{get(){return this._y},set(t){if(t==this._y)return;f.watch&&(f.mod[28]=!0);let e=t/this._y;f._h&&(this._h*=e,this._hh*=e),f._resizeColliders({x:1,y:e}),this._y=t,this._avg=.5*(this._x+this._y)}}),this._offset={_x:0,_y:0,get x(){return this._x},set x(t){t!=this._x&&(f.watch&&(f.mod[23]=!0),f._offsetCenterBy(t-this._x,0))},get y(){return this._y},set y(t){t!=this._y&&(f.watch&&(f.mod[23]=!0),f._offsetCenterBy(0,t-this._y))}},this._massUndef=!0,void 0===o&&(this._dimensionsUndef=!0,this._widthUndef=!0,o=this.tileSize>1?1:50,void 0===n&&(this._heightUndef=!0)),g&&(n??=this.tileSize>1?1:50),this._shape=u.shape,3!=this.__collider)this._vertexMode?this.addCollider(o):this.addCollider(0,0,o,n),this.shape=this._shape;else{if(this.w=o,Array.isArray(o))throw new Error('Cannot set the collider type of a sprite with a polygon or chain shape to "none". To achieve the same effect, use .overlaps(allSprites) to have your sprite overlap with the allSprites group.');void 0!==o&&void 0===n?this.shape="circle":(this.shape="box",this.h=n)}this.prevPos={x:s,y:r},this.prevRotation=0,this._dest={x:s,y:r},this._destIdx=0,this.drag=0,this.debug=!1,u._isAllSpritesGroup||this.p.allSprites.push(this),u.push(this);let y=u.vel.x||0,m=u.vel.y||0;"function"==typeof y&&(y=y(u.length-1)),"function"==typeof m&&(m=m(u.length-1)),this.vel.x=y,this.vel.y=m;let v=["ani","collider","x","y","w","h","d","diameter","dynamic","height","kinematic","static","vel","width"];for(let t of this.p.Sprite.propsAll){if(v.includes(t))continue;let e=u[t];void 0!==e&&("function"==typeof e&&p(e)&&(e=e(u.length-1)),this[t]="object"==typeof e?Object.assign({},e):e)}v=["add","animation","animations","autoCull","contains","GroupSprite","Group","idNum","length","mod","mouse","p","parent","Sprite","Subgroup","subgroups","velocity"];for(let t=0;t1?1:50,h??=r,l=s(r-.08,h-.08,this.tileSize)),"box"==a)p=e.Box(l.x/2,l.y/2,s(t,i,this.tileSize),0);else if("circle"==a)p=e.Circle(s(t,i,this.tileSize),l.x/2);else if(n){let _,c,f=[{x:0,y:0}],g={x:0,y:0},y={x:0,y:0},m={x:0,y:0},v=Array.isArray(n[0]);function x(){g.xm.x&&(m.x=g.x),g.y>m.y&&(m.y=g.y)}if(v){this._vertexMode&&(_=n[0][0],c=n[0][1],this.fixture&&this._relativeOrigin?(_=this.x-this._relativeOrigin.x,c=this.y-this._relativeOrigin.y,f.pop()):(this.x=_,this.y=c));for(let b=0;b0?1:-1;S=Math.abs(S);let A=0;for(let k=0;ke.Settings.maxPolygonVertices||"chain"==this._shape)&&(a="chain"),"polygon"==a?p=e.Polygon(f):"chain"==a&&(p=e.Chain(f,!1))}return this.shape??=a,this._w=r,this._hw=.5*r,1!=this.__shape&&(this._h=h,this._hh=.5*h),p}removeColliders(){this.body&&(this._removeContacts(0),this._removeFixtures(0))}removeSensors(){this.body&&(this._removeContacts(1),this._removeFixtures(1),this._hasSensors=!1)}_removeFixtures(t){let e;for(let i=this.fixtureList;i;i=i.getNext())if(void 0===t||i.m_isSensor==t){let t=i.m_next;i.destroyProxies(this.p.world.m_broadPhase),e?e.m_next=t:this.body.m_fixtureList=t}else e=i}_removeContacts(t){if(!this.body)return;let e=this.body.m_contactList;for(;e;){let i=e.contact;e=e.next,void 0!==t&&i.m_fixtureA.m_isSensor!=t||this.p.world.destroyContact(i)}}_offsetCenterBy(t,e){if(!t&&!e)return;if(this._offset._x+=t,this._offset._y+=e,!this.body)return;let i=s(t,e,this.tileSize);for(let t=this.body.m_fixtureList;t;t=t.m_next){let e=t.m_shape;if("circle"!=e.m_type){let t=e.m_vertices;for(let e of t)e.x+=i.x,e.y+=i.y}else e.m_p.x+=i.x,e.m_p.y+=i.y}}_cloneBodyProps(){let t={},e=["bounciness","density","drag","friction","heading","isSuperFast","rotation","rotationDrag","rotationLock","rotationSpeed","scale","vel","x","y"];this._massUndef&&this._dimensionsUndef||e.push("mass");for(let i of e)"object"==typeof this[i]?t[i]=Object.assign({},this[i]):t[i]=this[i];return t}get animation(){return this._ani}set animation(t){this.changeAni(t)}get ani(){return this._ani}set ani(t){this.changeAni(t)}get anis(){return this.animations}get autoDraw(){return this._autoDraw}set autoDraw(t){this.watch&&(this.mod[6]=!0),this._autoDraw=t}get allowSleeping(){return this.body?.isSleepingAllowed()}set allowSleeping(t){this.watch&&(this.mod[7]=!0),this.body&&this.body.setSleepingAllowed(t)}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){this.watch&&(this.mod[8]=!0),this._autoUpdate=t}get bounciness(){if(this.fixture)return this.fixture.getRestitution()}set bounciness(t){this.watch&&(this.mod[9]=!0);for(let e=this.fixtureList;e;e=e.getNext())e.setRestitution(t)}get centerOfMass(){let t=this.body.getWorldCenter(),e=r(t.x,t.y,this.tileSize);return this.p.createVector(e.x,e.y)}get collider(){return this._collider}set collider(t){if(t==this._collider)return;let e=(t=t.toLowerCase())[0];if("d"==e&&(t="dynamic"),"s"==e&&(t="static"),"k"==e&&(t="kinematic"),"n"==e&&(t="none"),t==this._collider)return;if("none"==t&&("chain"==this._shape||"polygon"==this._shape))return void console.error('Cannot set the collider type of a polygon or chain collider to "none". To achieve the same effect, use .overlaps(allSprites) to have your sprite overlap with the allSprites group.');if(this._removed)throw new Error("Cannot change the collider type of a sprite that was removed.");let i=this.__collider;this._collider=t,this.__collider=["d","s","k","n"].indexOf(e),this.watch&&(this.mod[10]=!0),void 0!==i&&(3!=this.__collider?(this.body&&this.body.setType(t),3==i&&this.addCollider()):(this.removeColliders(),this.fixture?.m_isSensor?this.body.m_gravityScale=0:this.p.world.destroyBody(this.body)))}_parseColor(t){if(t instanceof p5.Color)return t;if("object"!=typeof t)return"string"==typeof t&&1==t.length?this.p.colorPal(t):this.p.color(t);if(t.levels)return this.p.color(...t.levels);if(void 0!==t._r)return this.p.color(t._r,t._g,t._b,255*t._a);if(void 0!==t._h)return this.p.color(t._h,t._s,t._v,255*t._a);throw new Error("Invalid color")}get color(){return this._color}set color(t){this.watch&&(this.mod[11]=!0),this._color=this._parseColor(t)}get colour(){return this._color}set colour(t){this.color=t}get fill(){return this._color}set fill(t){this.color=t}get fillColor(){return this._color}set fillColor(t){this.color=t}get stroke(){return this._stroke}set stroke(t){this.watch&&(this.mod[31]=!0),this._stroke=this._parseColor(t)}get strokeColor(){return this._stroke}set strokeColor(t){this.stroke=t}get strokeWeight(){return this._strokeWeight}set strokeWeight(t){this.watch&&(this.mod[32]=!0),this._strokeWeight=t}get textColor(){return this._textFill}set textColor(t){this.watch&&(this.mod[34]=!0),this._textFill=this._parseColor(t)}get textColour(){return this._textFill}set textColour(t){this.textColor=t}get textFill(){return this._textFill}set textFill(t){this.textColor=t}get textSize(){return this._textSize}set textSize(t){this.watch&&(this.mod[40]=!0),this._textSize=t}get textStroke(){return this._textStroke}set textStroke(t){this.watch&&(this.mod[41]=!0),this._textStroke=this._parseColor(t)}get textStrokeWeight(){return this._textStrokeWeight}set textStrokeWeight(t){this.watch&&(this.mod[42]=!0),this._textStrokeWeight=t}get bearing(){return this._bearing}set bearing(t){this.watch&&(this.mod[39]=!0),this._bearing=t}get debug(){return this._debug}set debug(t){this.watch&&(this.mod[12]=!0),this._debug=t}get density(){if(this.fixture)return this.fixture.getDensity()}set density(t){this.watch&&(this.mod[13]=!0);for(let e=this.fixtureList;e;e=e.getNext())e.setDensity(t)}_getDirectionAngle(t){t=t.toLowerCase().replaceAll(/[ _-]/g,"");let e={up:-90,down:90,left:180,right:0,upright:-45,rightup:-45,upleft:-135,leftup:-135,downright:45,rightdown:45,downleft:135,leftdown:135,forward:this.rotation,backward:this.rotation+180}[t];return"radians"==this.p._angleMode&&(e=this.p.radians(e)),e}get direction(){return 0!==this.vel.x||0!==this.vel.y?this.p.atan2(this.vel.y,this.vel.x):void 0===this._direction?this.rotation:this._direction}set direction(t){this.watch&&(this.mod[14]=!0),"string"==typeof t&&(this._heading=t,t=this._getDirectionAngle(t)),this._direction=t;let e=this.speed;this.vel.x=this.p.cos(t)*e,this.vel.y=this.p.sin(t)*e}get drag(){return this.body?.getLinearDamping()}set drag(t){this.watch&&(this.mod[15]=!0),this.body&&this.body.setLinearDamping(t)}get draw(){return this._display}set draw(t){this._draw=t}get dynamic(){return this.body?.isDynamic()}set dynamic(t){this.collider=t?"dynamic":"kinematic"}get fixture(){return this.fixtureList}get fixtureList(){return this.body?this.body.m_fixtureList:null}get friction(){if(this.fixture)return this.fixture.getFriction()}set friction(t){this.watch&&(this.mod[16]=!0);for(let e=this.fixtureList;e;e=e.getNext())e.setFriction(t)}get heading(){return this._heading}set heading(t){this.direction=t}get img(){return this._ani?.frameImage}set img(t){this.changeAni(t)}get image(){return this._ani?.frameImage}set image(t){this.changeAni(t)}get isMoving(){return 0!=this.vel.x||0!=this.vel.y}get isSuperFast(){return this.body?.isBullet()}set isSuperFast(t){this.watch&&(this.mod[18]=!0),this.body&&this.body.setBullet(t)}get kinematic(){return this.body?.isKinematic()}set kinematic(t){this.collider=t?"kinematic":"dynamic"}get layer(){return this._layer}set layer(t){this.watch&&(this.mod[19]=!0),this._layer=t}get life(){return this._life}set life(t){this.watch&&(this.mod[20]=!0),this._life=t}get mass(){return this.body?.getMass()}set mass(t){if(!this.body)return;this.watch&&(this.mod[21]=!0);let e=this.massData;e.mass=t>0?t:1e-8,this.body.setMassData(e),delete this._massUndef}get massData(){const t={I:0,center:new e.Vec2(0,0),mass:0};return this.body.getMassData(t),t.center=r(t.center.x,t.center.y,this.tileSize),t}resetMass(){this.body&&(this.watch&&(this.mod[21]=!0),this.body.resetMassData())}get mirror(){return this._mirror}set mirror(t){this.watch&&(this.mod[22]=!0),void 0!==t.x&&(this._mirror.x=t.x),void 0!==t.y&&(this._mirror.y=t.y)}get offset(){return this._offset}set offset(t){t.x??=this._offset._x,t.y??=this._offset._y,t.x==this._offset._x&&t.y==this._offset._y||(this.watch&&(this.mod[23]=!0),this._offsetCenterBy(t.x-this._offset._x,t.y-this._offset._y))}get previousPosition(){return this.prevPos}set previousPosition(t){this.prevPos=t}get previousRotation(){return this.prevRotation}set previousRotation(t){this.prevRotation=t}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(t){this.watch&&(this.mod[24]=!0),this._pixelPerfect=t}get rotation(){if(!this.body)return this._angle||0;let t=this.body.getAngle();return"degrees"===this.p._angleMode?this.p.degrees(t):t}set rotation(t){this.body?("degrees"===this.p._angleMode&&(t=this.p.radians(t)),this.body.setAngle(t),this.body.synchronizeTransform()):this._angle=t}get rotationDrag(){return this.body?.getAngularDamping()}set rotationDrag(t){this.body&&(this.watch&&(this.mod[26]=!0),this.body.setAngularDamping(t))}get rotationLock(){return this.body?.isFixedRotation()}set rotationLock(t){this.body&&(this.watch&&(this.mod[27]=!0),this.body.setFixedRotation(t))}get rotationSpeed(){return this.body?this.body.getAngularVelocity():this._rotationSpeed}set rotationSpeed(t){this.body?this.body.setAngularVelocity(t):this._rotationSpeed=t}get scale(){return this._scale}set scale(t){if(t<=0&&(t=.01),"number"==typeof t?t={x:t,y:t}:(t.x??=this._scale._x,t.y??=this._scale._y),t.x==this._scale._x&&t.y==this._scale._y)return;this.watch&&(this.mod[28]=!0);let e={x:t.x/this._scale._x,y:t.y/this._scale._y};this._w*=e.x,this._hw*=e.x,this._h&&(this._h*=e.y,this._hh*=e.y),this._resizeColliders(e),this._scale._x=t.x,this._scale._y=t.y,this._scale._avg=t.x}get sleeping(){if(this.body)return!this.body.isAwake()}set sleeping(t){this.body&&(this.watch&&(this.mod[30]=!0),this.body.setAwake(!t))}get speed(){return this.p.createVector(this.vel.x,this.vel.y).mag()}set speed(t){let e=this.direction;this.vel.x=this.p.cos(e)*t,this.vel.y=this.p.sin(e)*t}get static(){return this.body?.isStatic()}set static(t){this.collider=t?"static":"dynamic"}get removed(){return this._removed}set removed(t){t&&!this._removed&&(this.watch&&(this.mod[25]=!0),this._removed=!0,this._remove())}set vertices(t){if(3==this.__collider)throw new Error('Cannot set vertices of a sprite with collider type of "none".');this.watch&&(this.mod[29]=!0),this._removeFixtures(),this._originMode="start",this.addCollider(t),this._hasSensors&&this.addDefaultSensors()}get vertices(){return this._getVertices()}_getVertices(t){let e=this.fixture.getShape(),s=[...e.m_vertices];"polygon"==e.m_type&&s.unshift(s.at(-1));let r=this.x,o=this.y;for(let e=0;e=2)return void console.error('Cannot set the collider shape to chain or polygon if the sprite has a collider type of "none". To achieve the same effect, use .overlaps(allSprites) to have your sprite overlap with the allSprites group.');if(1==this.__shape&&0!=e)return void console.error("Cannot change a circle collider into a chain or polygon shape.");let i,s,r=this.__shape;if(this.__shape=e,this._shape=t,this.watch&&(this.mod[29]=!0),void 0===r)return;0==this.__shape?(this._h=this._w,this._hh=this._hw):(this._h=void 0,this._hh=void 0),1!=r&&1!=this.__shape?i=this._getVertices(!0):s=this._w,this._removeFixtures(),3!=this.__collider&&(i?(this._originMode??="center",this.addCollider(i)):this.addCollider()),this._hasSensors&&this.addDefaultSensors();let o=this._offset._x,h=this._offset._y;(o||h)&&(this._offset._x=0,this._offset._y=0,this._offsetCenterBy(o,h))}get update(){return this._update}set update(t){this._customUpdate=t}get vel(){return this._vel}set vel(t){this.vel.x=t.x,this.vel.y=t.y}set velocity(t){this.vel=t}get velocity(){return this._vel}_update(){this._ani?.update&&this._ani.update();for(let t in this.mouse)-1==this.mouse[t]&&(this.mouse[t]=0);this._customUpdate&&this._customUpdate(),this.autoUpdate&&(this.autoUpdate=null)}_step(){this.body||this._removed||(this.rotation+=this._rotationSpeed,this.x+=this.vel.x,this.y+=this.vel.y),this.watch&&(this.x!=this.prevX&&(this.mod[0]=this.mod[2]=!0),this.y!=this.prevY&&(this.mod[1]=this.mod[2]=!0),this.rotation!=this.prevRotation&&(this.mod[3]=this.mod[4]=!0)),(this.body||this._removed)&&this.__step()}_draw(){if(void 0!==this._strokeWeight&&this.p.strokeWeight(this._strokeWeight),this._ani&&"colliders"!=this.debug&&!this.p.p5play.disableImages&&this._ani.draw(this._offset._x,this._offset._y,0,this._scale._x,this._scale._y),!this._ani||this.debug||this.p.p5play.disableImages)if(this.debug&&"colliders"!=this.debug&&(this.p.noFill(),3!=this.__collider?this.p.stroke(0,255,0):this.p.stroke(120),this.p.line(0,-2,0,2),this.p.line(-2,0,2,0)),3!=this.__collider){0!==this._strokeWeight&&(2==this.__shape?this.p.stroke(this.stroke||this.color):this._stroke&&this.p.stroke(this._stroke));for(let t=this.fixtureList;t;t=t.getNext())t.m_isSensor&&!this.debug||this._drawFixture(t)}else 0!==this._strokeWeight&&this.p.stroke(this._stroke||120),0==this.__shape?this.p.rect(this._offset._x,this._offset._y,this.w*this.tileSize,this.h*this.tileSize):1==this.__shape&&this.p.circle(this._offset._x,this._offset._y,this.d*this.tileSize);void 0!==this.text&&(this.p.textAlign(this.p.CENTER,this.p.CENTER),this.p.fill(this._textFill),this._textStrokeWeight&&this.p.strokeWeight(this._textStrokeWeight),this._textStroke?this.p.stroke(this._textStroke):this.p.noStroke(),this.p.textSize(this.textSize*this.tileSize),this.p.text(this.text,0,0))}_display(){let t=this.x*this.tileSize+this.p.world.origin.x,e=this.y*this.tileSize+this.p.world.origin.y,i=Math.max(this._w,this._h);if("chain"!=this.shape&&this.p.camera.active&&(t+ithis.p.camera.bound.max.x||e+ithis.p.camera.bound.max.y))this._visible=null;else{if(this._visible=!0,this.p.p5play.spritesDrawn++,this._pixelPerfect){let i,s;this.ani&&!this.p.p5play.disableImages?(i=this.ani[this.ani._frame].w,s=this.ani[this.ani._frame].h):(i=this._w,s=this._h),t=i%2==0?Math.round(t):Math.round(t-.5)+.5,e=s%2==0?Math.round(e):Math.round(e-.5)+.5}else t=h(t),e=h(e);for(let t of this.joints)t.visible?this._uid==t.spriteA._uid?(!t.spriteB._visible||this.layer<=t.spriteB.layer)&&t._display():(!t.spriteA._visible||this.layer1&&(s??=.1),s??=1,s<=0)return console.warn("sprite.move: speed should be a positive number"),Promise.resolve(!1);let r=this._dest.y-this.y,o=this._dest.x-this.x,h=s/Math.sqrt(r*r+o*o);this.vel.x=o*h,this.vel.y=r*h;let n=this.direction,a=n-.1,l=n+.1,p=s+.01,d=this._destIdx,u=Math.max(this.p.world.velocityThreshold,.25*p)/this.tileSize;return(async()=>{let s=p+p,r=p+p;do{if(d!=this._destIdx)return!1;await t.delay();let e=this.direction;if(e<=a||e>=l||Math.abs(this.vel.x)<=u&&Math.abs(this.vel.y)<=u)return!1;s=Math.abs(this.x-this._dest.x),r=Math.abs(this.y-this._dest.y)}while(e&&s>p||i&&r>p);return s2&&(i=o[0],s=o[1],e=o[2],r=o[3]),void 0!==i?t=this.angleToFace(i,s,r):t-=this.rotation,e??=.1,this.rotationSpeed=t*e}angleTo(t,e){if("object"==typeof t){let i=t;if(i==this.p.mouse&&!this.p.mouse.active)return 0;if(void 0===i.x||void 0===i.y)return console.error("sprite.angleTo ERROR: rotation destination not defined, object given with no x or y properties"),0;e=i.y,t=i.x}return this.p.atan2(e-this.y,t-this.x)}angleToFace(t,e,i){if("object"==typeof t&&(i=e,e=t.y,t=t.x),Math.abs(t-this.x)<.01&&Math.abs(e-this.y)<.01)return 0;let s=this.angleTo(t,e);i??=0,s+=i;let r=s-this.rotation%360,o=360-Math.abs(r);return o*=r<0?1:-1,Math.abs(r)2&&(i=o[0],s=o[1],e=o[2],r=o[3]),void 0!==i)t=this.angleToFace(i,s,r);else{if(t==this.rotation)return;t-=this.rotation}return this.rotate(t,e)}rotate(e,i){if(1==this.__collider)throw new b(0);if(isNaN(e))throw new b(1,[e]);if(0==e)return;let s=Math.abs(e);i??=1,i>s&&(i=s);let r=this.rotation+e,o=e>0;this.rotationSpeed=i*(o?1:-1);let h=Math.floor(s/i)-1;this._rotateIdx??=0,this._rotateIdx++;let n=this._rotateIdx;return(async()=>{if(h>1){let e=Math.abs(this.rotationSpeed)+.01;do{if(this._rotateIdx!=n)return!1;if(await t.delay(),o&&this.rotationSpeed<.01||!o&&this.rotationSpeed>-.01)return!1}while((o&&r>this.rotation||!o&&r.01&&(this.rotationSpeed=r-this.rotation,await t.delay())}else await t.delay();return this._rotateIdx==n&&(this.rotationSpeed=0,this.rotation=r,!0)})()}async changeAni(t){if(this.p.p5play.disableImages)return;if(arguments.length>1)t=[...arguments];else if(t instanceof this.p.SpriteAnimation){if(t==this._ani)return;t=[t]}else if(!Array.isArray(t)){if(t==this._ani?.name)return;t=[t]}let e,i;this._aniChangeCount++;for(let s=0;s1&&("!"==r.name[0]&&(r.name=r.name.slice(1),r.start=-1,r.end=0),"<"!=r.name[0]&&">"!=r.name[0]||(r.name=r.name.slice(1),r.flipX=!0),"^"==r.name[0]&&(r.name=r.name.slice(1),r.flipY=!0),"**"==r.name&&(e=!0,t=t.slice(0,-1)),";;"==r.name&&(i=!0,t=t.slice(0,-1)))}let s=this._aniChangeCount;do{for(let e=0;e1&&(i.start=0),await this._playSequencedAni(i)}}while(e&&s==this._aniChangeCount);1!=t.length&&i&&this._ani.stop()}_playSequencedAni(t){return new Promise((e=>{let{name:i,start:s,end:r,flipX:o,flipY:h}=t;this._changeAni(i),o&&(this._ani.scale.x=-this._ani.scale.x),h&&(this._ani.scale.y=-this._ani.scale.y),s<0&&(s=this._ani.length+s),void 0!==s&&(this._ani._frame=s),void 0!==r?this._ani.goToFrame(r):this._ani._frame==this._ani.lastFrame&&e(),this._ani._onComplete=this._ani._onChange=()=>{o&&(this._ani.scale.x=-this._ani.scale.x),h&&(this._ani.scale.y=-this._ani.scale.y),this._ani._onComplete=this._ani._onChange=null,e()}}))}changeAnimation(){return this.changeAni(...arguments)}_changeAni(t){this._ani?._onChange&&this._ani._onChange(),this._ani?.onChange&&this._ani.onChange();let e=this.animations[t];if(!e)for(let i=this.groups.length-1;i>=0;i--){if(e=this.groups[i].animations[t],e){e=e.clone();break}}if(!e)throw this.p.noLoop(),new b("Sprite.changeAnimation",[t]);this._ani=e,this._ani.name=t,this.resetAnimationsOnChange&&(this._ani._frame=0)}remove(){this.removed=!0}_remove(){this.body&&this.p.world.destroyBody(this.body),this.body=null;for(let t of this.groups)t.remove(this)}toString(){return"s"+this.idNum}_setContactCB(t,e,i,s){let r;r=0==i?n._collisions[s]:n._overlappers[s];let o=this.p.p5play[r],h=o[this._uid]??={};h[t._uid]!=e&&(h[t._uid]=e,this._uid!=t._uid&&(h=o[t._uid],h&&h[this._uid]&&(delete h[this._uid],0==Object.keys(h).length&&delete o[t._uid])))}_validateCollideParams(t,e){if(!t)throw new b("Sprite.collide",2);if(!t._isSprite&&!t._isGroup)throw new b("Sprite.collide",0,[t]);if(e&&"function"!=typeof e)throw new b("Sprite.collide",1,[e])}_ensureCollide(t,e,i){if(!1!==this._hasOverlap[t._uid]&&(this._hasOverlap[t._uid]=!1),!1!==t._hasOverlap[this._uid]&&(t._hasOverlap[this._uid]=!1,t._isGroup))for(let e of t)e._hasOverlap[this._uid]=!1,this._hasOverlap[e._uid]=!1}collide(t,e){return this.collides(t,e)}collides(t,e){return this._validateCollideParams(t,e),this._ensureCollide(t),e&&this._setContactCB(t,e,0,0),1==this._collisions[t._uid]||this._collisions[t._uid]<=-3}colliding(t,e){this._validateCollideParams(t,e),this._ensureCollide(t),e&&this._setContactCB(t,e,0,1);let i=this._collisions[t._uid];return i<=-3?1:i>0?i:0}collided(t,e){return this._validateCollideParams(t,e),this._ensureCollide(t),e&&this._setContactCB(t,e,0,2),this._collisions[t._uid]<=-1}_validateOverlapParams(t,e){if(!t)throw new b("Sprite.overlap",2);if(!t._isSprite&&!t._isGroup)throw new b("Sprite.overlap",0,[t]);if(e&&"function"!=typeof e)throw new b("Sprite.overlap",1,[e])}_ensureOverlap(t){if(this._hasSensors||this.addDefaultSensors(),!t._hasSensors)if(t._isSprite)t.addDefaultSensors();else{for(let e of t)e._hasSensors||e.addDefaultSensors();t._hasSensors=!0}if(this._hasOverlap[t._uid]||(this._removeContactsWith(t),this._hasOverlap[t._uid]=!0),!t._hasOverlap[this._uid]&&(t._removeContactsWith(this),t._hasOverlap[this._uid]=!0,t._isGroup))for(let e of t)e._hasOverlap[this._uid]=!0,this._hasOverlap[e._uid]=!0}overlap(t,e){return this.overlaps(t,e)}overlaps(t,e){return this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,0),1==this._overlappers[t._uid]||this._overlappers[t._uid]<=-3}overlapping(t,e){this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,1);let i=this._overlappers[t._uid];return i<=-3?1:i>0?i:0}overlapped(t,e){return this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,2),this._overlappers[t._uid]<=-1}_removeContactsWith(t){if(t._isGroup)for(let e of t)this._removeContactsWith(e);else this.__removeContactsWith(t)}__removeContactsWith(t){if(this.body)for(let e=this.body.getContactList();e;e=e.next){let i=e.contact;i.m_fixtureA.m_body.sprite._uid!=t._uid&&i.m_fixtureB.m_body.sprite._uid!=t._uid||this.p.world.destroyContact(i)}}_sortFixtures(){let t,e,i=null,s=null;for(let r=this.fixtureList;r;r=r.getNext())r.m_isSensor?(s?s.m_next=r:s=r,e=r):(i?i.m_next=r:i=r,t=r);s&&(e.m_next=null),i&&(t.m_next=s),this.body.m_fixtureList=i||s}addDefaultSensors(){if(this._hasSensors)return;let t;if(this.body&&this.fixtureList){for(let e=this.fixtureList;e;e=e.getNext())e.m_isSensor||(t=e.m_shape,this.body.createFixture({shape:t,isSensor:!0}));this._sortFixtures()}else this.addSensor();this._hasSensors=!0}},this.Sprite.propTypes={x:"Float64",y:"Float64",vel:"Vec2",rotation:"number",rotationSpeed:"number",ani:"string",autoDraw:"boolean",allowSleeping:"boolean",autoUpdate:"boolean",bounciness:"number",collider:"Uint8",color:"color",debug:"boolean",density:"number",direction:"number",drag:"number",friction:"number",h:"number",isSuperFast:"boolean",layer:"number",life:"Int32",mass:"number",mirror:"Vec2_boolean",offset:"Vec2",pixelPerfect:"boolean",removed:"boolean",rotationDrag:"number",rotationLock:"boolean",scale:"Vec2",shape:"Uint8",sleeping:"boolean",stroke:"color",strokeWeight:"number",text:"string",textColor:"color",tile:"string",tileSize:"number",visible:"boolean",w:"number",bearing:"number",textSize:"number",textStroke:"color",textStrokeWeight:"number"},this.Sprite.props=Object.keys(this.Sprite.propTypes),this.Sprite.propsAll=this.Sprite.props.concat(["d","diameter","dynamic","fill","height","heading","kinematic","resetAnimationsOnChange","speed","static","width"]),this.Sprite.colliderTypes=["d","s","k","n"],this.Sprite.shapeTypes=["box","circle","chain","polygon"],this.Turtle=function(e){if(t.allSprites.tileSize>1)throw new Error("Turtle can't be used when allSprites.tileSize is greater than 1.");e??=25;let i=new t.Sprite(e,e,[[e,.4*e],[-e,.4*e],[0,.8*-e]]);i.color="green",i._isTurtleSprite=!0,i._prevPos={x:i.x,y:i.y};let s=i.move;return i.move=async function(){this._prevPos.x=this.x,this._prevPos.y=this.y,await s.call(this,...arguments)},i},this.SpriteAnimation=class extends Array{constructor(){super(),this.p=t;let e,i=[...arguments];if(this.name="default","object"==typeof i[0]&&(i[0]._isSprite||i[0]._isGroup)&&(e=i[0],i=i.slice(1),this._addedToSpriteOrGroup=!0),e??=this.p.allSprites,"string"!=typeof i[0]||1!=i[0].length&&i[0].includes(".")||(this.name=i[0],i=i.slice(1)),this._frame=0,this._cycles=0,this.targetFrame=-1,this.offset={x:e.anis.offset.x||0,y:e.anis.offset.y||0},this._frameDelay=e.anis.frameDelay||4,this.demoMode=e.anis.demoMode||!1,this.playing=!0,this.visible=!0,this.looping=e.anis.looping,this.looping??=!0,this.endOnFirstFrame=!1,this.frameChanged=!1,this.onComplete=this.onChange=null,this._onComplete=this._onChange=null,this.rotation=e.anis.rotation||0,this._scale=new l,0!=i.length&&"number"!=typeof i[0])if(e.animations[this.name]=this,e._ani=this,Array.isArray(i[0])&&"string"==typeof i[0][0]&&(i=[...i[0]]),2!=i.length||"string"!=typeof i[0]||"string"!=typeof i[1]&&"number"!=typeof i[1])if("string"==typeof i[i.length-1]||i[i.length-1]instanceof p5.Image)for(let s=0;s=3)throw new b("SpriteAnimation",1);o=i[0],r=i[1]}else r=i[0];let h=this;if(o instanceof p5.Image&&1!=o.width&&1!=o.height)this.spriteSheet=o,n();else{let a;a="string"==typeof o?o:o.url,this.spriteSheet=this.p.loadImage(a,(()=>{n()}))}function n(){if(Array.isArray(r)||Array.isArray(r.frames)){if("number"!=typeof r[0]){let t=r;if(Array.isArray(r.frames)){t=r.frames,delete r.frames;for(let e=0;e=h.spriteSheet.width&&(u=0,_+=i,_>=h.spriteSheet.height&&(_=0))}}else{let p,d,u=i[0];if(isNaN(i[1])?p=i[1]:d=Number(i[1]),".png"!=u.slice(-4)||p&&".png"!=p.slice(-4))throw new b("SpriteAnimation",0,[u]);let _=0,c=0;for(let y=u.length-5;y>=0&&!isNaN(u.charAt(y));y--)_++;if(p)for(let m=p.length-5;m>=0&&!isNaN(p.charAt(m));m--)c++;let f,g=u.slice(0,-4-_);if(p&&(f=p.slice(0,-4-c)),p&&g!=f)this.push(this.p.loadImage(u)),this.push(this.p.loadImage(p));else{let v,x=parseInt(u.slice(-4-_,-4),10);if(d??=parseInt(p.slice(-4-c,-4),10),d=this.length)throw new b("SpriteAnimation.frame",[t,this.length]);this._frame=t}get frameDelay(){return this._frameDelay}set frameDelay(t){t<=0&&(t=1),this._frameDelay=t}get scale(){return this._scale}set scale(t){"number"==typeof t&&(t={x:t,y:t}),this._scale._x=t.x,this._scale._y=t.y,this._scale._avg=t.x}clone(){let t=new this.p.SpriteAnimation;t.spriteSheet=this.spriteSheet;for(let e=0;ethis._frame&&-1!==this.targetFrame?this._frame++:this.targetFrame=this.lastFrame?this._frame=0:this._frame++:this._frame{this._onComplete=()=>{this._onComplete=null,t()}}))}pause(t){this.playing=!1,t&&(this._frame=t)}stop(t){this.playing=!1,t&&(this._frame=t)}rewind(){return this.looping=!1,this.goToFrame(0)}loop(){this.looping=!0,this.playing=!0}noLoop(){this.looping=!1}nextFrame(){this._frame0?this._frame=this._frame-1:this.looping&&(this._frame=this.length-1),this.targetFrame=-1,this.playing=!1}goToFrame(t){if(!(t<0||t>=this.length))return this.targetFrame=t,this.targetFrame!==this._frame&&(this.playing=!0),new Promise((t=>{this._onComplete=()=>{this._onComplete=null,t()}}))}get lastFrame(){return this.length-1}get frameImage(){let t=this[this._frame];if(t instanceof p5.Image)return t;let{x:e,y:i,w:s,h:r}=t,o=this.p.createImage(s,r);return o.copy(this.spriteSheet,this.offset.x,this.offset.y,s,r,e,i,s,r),o}get w(){return this.width}get width(){return this[this._frame]instanceof p5.Image?this[this._frame].width:this[this._frame]?this[this._frame].w:1}get h(){return this.height}get height(){return this[this._frame]instanceof p5.Image?this[this._frame].height:this[this._frame]?this[this._frame].h:1}get frames(){let t=[];for(let e=0;ee.#t[t],set(i){e.#t[t]=i;for(let s in e){let r=e[s];r instanceof SpriteAnimation&&(r[t]=i)}}});for(let t of s){this.#t[t]={_x:0,_y:0};for(let i of["x","y"])Object.defineProperty(this.#t[t],i,{get:()=>e.#t[t]["_"+i],set(s){e.#t[t]["_"+i]=s;for(let r in e){let o=e[r];o instanceof SpriteAnimation&&(o[t][i]=s)}}})}}},this.Group=class extends Array{constructor(...e){let i;if(e[0]instanceof t.Group&&(i=e[0],e=e.slice(1)),super(...e),this.p=t,"number"==typeof e[0])return;for(let t of this)if(!(t instanceof this.p.Sprite))throw new Error("A group can only contain sprites");if(this._isGroup=!0,this.x,this.y,this.vel,this.rotation,this.rotationSpeed,this.autoDraw,this.allowSleeping,this.autoUpdate,this.bounciness,this.collider,this.color,this.debug,this.density,this.direction,this.drag,this.friction,this.h,this.isSuperFast,this.layer,this.life,this.mass,this.mirror,this.offset,this.pixelPerfect,this.removed,this.rotationDrag,this.rotationLock,this.scale,this.shape,this.sleeping,this.stroke,this.strokeWeight,this.text,this.textColor,this.tile,this.tileSize,this.visible,this.w,this.bearing,this.d,this.diameter,this.dynamic,this.height,this.heading,this.kinematic,this.resetAnimationsOnChange,this.speed,this.static,this.width,this.idNum,this.p.p5play.groupsCreated<999)this.idNum=this.p.p5play.groupsCreated;else{for(let t=1;tt&&(t=e._layer);return t}get ani(){return this._ani}set ani(t){this.addAni(t);for(let e of this)e.changeAni(t)}get animation(){return this._ani}set animation(t){this.ani=t}get anis(){return this.animations}get img(){return this._ani.frameImage}set img(t){this.ani=t}get image(){return this._ani.frameImage}set image(t){this.ani=t}set amount(t){let e=t-this.length,i=e>0;e=Math.abs(e);for(let t=0;t0?i:0}collided(t,e){return this._validateCollideParams(t,e),this._ensureCollide(t),e&&this._setContactCB(t,e,0,2),this._collisions[t._uid]<=-1}_validateOverlapParams(t,e){if(e&&"function"!=typeof e)throw new b("Group.overlap",1,[e]);if(!t)throw new b("Group.overlap",2);if(t._isSprite)e&&!b.warned1&&(console.warn("Deprecated use of a group.overlap function with a sprite as input. Use sprite.overlaps, sprite.overlapping, or sprite.overlapped instead."),b.warned1=!0);else if(!t._isGroup)throw new b("Group.overlap",0,[t])}_ensureOverlap(t){if(!this._hasSensors){for(let t of this)t._hasSensors||t.addDefaultSensors();this._hasSensors=!0}if(!t._hasSensors)if(t._isSprite)t.addDefaultSensors();else{for(let e of t)e._hasSensors||e.addDefaultSensors();t._hasSensors=!0}if(1!=this._hasOverlap[t._uid]){this._removeContactsWith(t),this._hasOverlap[t._uid]=!0;for(let e of this)if(e._hasOverlap[t._uid]=!0,t._hasOverlap[e._uid]=!0,this._uid==t._uid)for(let i of t)e._hasOverlap[i._uid]=!0,i._hasOverlap[e._uid]=!0}if(1!=t._hasOverlap[this._uid]&&(t._removeContactsWith(this),t._hasOverlap[this._uid]=!0,t._isGroup))for(let e of t){e._hasOverlap[this._uid]=!0,this._hasOverlap[e._uid]=!0;for(let t of this)e._hasOverlap[t._uid]=!0,t._hasOverlap[e._uid]=!0}}overlap(t,e){return this.overlaps(t,e)}overlaps(t,e){return this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,0),1==this._overlappers[t._uid]||this._overlappers[t._uid]<=-3}overlapping(t,e){this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,1);let i=this._overlappers[t._uid];return i<=-3?1:i>0?i:0}overlapped(t,e){return this._validateOverlapParams(t,e),this._ensureOverlap(t),e&&this._setContactCB(t,e,1,2),this._overlappers[t._uid]<=-1}_removeContactsWith(t){for(let e of this)e._removeContactsWith(t)}applyForce(){for(let t of this)t.applyForce(...arguments)}applyForceScaled(){for(let t of this)t.applyForceScaled(...arguments)}attractTo(){for(let t of this)t.attractTo(...arguments)}applyTorque(){for(let t of this)t.applyTorque(...arguments)}move(t,e,i){let s=[];for(let r of this)s.push(r.move(t,e,i));return Promise.all(s)}moveTo(t,e,i){if("number"!=typeof t){let s=t;if(s==this.p.mouse&&!this.p.mouse.active)return;i=e,e=s.y,t=s.x}let s=this._resetCentroid(),r=[];for(let o of this){let h={x:o.x-s.x+t,y:o.y-s.y+e};r.push(o.moveTo(h.x,h.y,i))}return Promise.all(r)}moveTowards(t,e,i){if("number"!=typeof t){let s=t;if(s==this.p.mouse&&!this.p.mouse.active)return;i=e,e=s.y,t=s.x}if(void 0!==t||void 0!==e){this._resetCentroid();for(let s of this){void 0===s.distCentroid&&this._resetDistancesFromCentroid();let r={x:s.distCentroid.x+t,y:s.distCentroid.y+e};s.moveTowards(r.x,r.y,i)}}}moveAway(t,e,i){if("number"!=typeof t){let s=t;if(s==this.p.mouse&&!this.p.mouse.active)return;i=e,e=s.y,t=s.x}if(void 0!==t||void 0!==e){this._resetCentroid();for(let s of this){void 0===s.distCentroid&&this._resetDistancesFromCentroid();let r={x:s.distCentroid.x+t,y:s.distCentroid.y+e};s.moveAway(r.x,r.y,i)}}}push(...t){this.removed&&(console.warn("Adding a sprite to a group that was removed. Use `group.removeAll()` to remove all of a group's sprites without removing the group itself. Restoring the group in p5play's memory."),this.p.p5play.groups[this._uid]=this,this.removed=!1);for(let e of t){if(!(e instanceof this.p.Sprite))throw new Error("You can only add sprites to a group, not "+typeof e);if(e.removed){console.error("Can't add a removed sprite to a group");continue}let t;for(let i in this._hasOverlap){let s=this._hasOverlap[i];s&&!e._hasSensors&&e.addDefaultSensors(),t=i>=1e3?this.p.p5play.sprites[i]:this.p.p5play.groups[i],t&&!t.removed&&(s?t._ensureOverlap(e):t._ensureCollide(e))}for(let t in n){let i=n[t];for(let t of i){let i=this.p.p5play[t],s=i[this._uid];if(!s)continue;let r=i[e._uid]??={};for(let t in s)r[t]=s[t]}}super.push(e),this.parent&&this.p.p5play.groups[this.parent].push(e),e.groups.push(this)}return this.length}size(){return this.length}toString(){return"g"+this.idNum}cull(t,e,i,s,r){if(void 0===i){r=e,t=e=i=s=t}if(isNaN(t)||isNaN(e)||isNaN(i)||isNaN(s))throw new TypeError("The culling boundary must be defined with numbers");if(r&&"function"!=typeof r)throw new TypeError("The callback to group.cull must be a function");let o=this.p.camera.x-this.p.canvas.hw/this.p.camera.zoom,h=this.p.camera.y-this.p.canvas.hh/this.p.camera.zoom,n=-i+o,a=-t+h,l=this.p.width+s+o,p=this.p.height+e+h,d=0;for(let t=0;tl||e.y>p)&&(d++,r?r(e,d):e.remove(),e.removed&&t--))}return d}remove(t){if(void 0===t)return this.removeAll(),void(this._isAllSpritesGroup||(this.removed=!0));let e;if(e="number"==typeof t?t>=0?t:this.length+t:this.indexOf(t),-1==e)return;let i=this[e];return this.splice(e,1),i}splice(t,e){let i=super.splice(t,e);if(!i)return;let s=[];for(let t of i){if(t.removed)continue;let e=this._uid;do{s.push(e);let i=t.groups.findIndex((t=>t._uid==e)),r=t.groups.splice(i,1);e=r[0].parent}while(e)}for(let t of s){let e=this.p.p5play.groups[t];for(let t in n)for(let i in e[t]){if(0==e[t][i])continue;let s;s=i>=1e3?this.p.p5play.sprites[i]:this.p.p5play.groups[i];let r=!1;for(let i of e)if(i[t][s._uid]>0){r=!0;break}r||(e[t][s._uid]=-2,s[t][e._uid]=-2)}}return i}pop(){return this.remove(this.length-1)}shift(){return this.remove(0)}unshift(){return console.error("unshift is not supported for groups"),this.length}removeAll(){for(;this.length>0;)this[0].remove()}_step(){this.__step()}draw(){let t=[...this];t.sort(((t,e)=>t._layer-e._layer));for(let e=0;e=1e3){if(e._isGroup||e._uid>=s)continue;t=this.p.p5play.sprites[s]}else{if(e._isGroup&&e._uid>=s)continue;t=this.p.p5play.groups[s]}let r=e[i][s]+1;t&&0!=r&&-2!=r?(this[i][s]=r,t[i][e._uid]=r):(delete e[i][s],t&&delete t[i][e._uid])}},this.Sprite.prototype.___step=this.Group.prototype.___step=function(){let t,e,i,s,r=this,o=!0;for(let h in n){for(let a in this[h]){if(a>=1e3){if(r._isGroup||r._uid>=a)continue;t=this.p.p5play.sprites[a]}else{if(r._isGroup&&r._uid>=a)continue;t=this.p.p5play.groups[a]}if(r._isGroup||t?._isGroup)continue;if(i=r._hasOverlap[t._uid]??t._hasOverlap[r._uid],o&&!1!==i||!o&&!0!==i)continue;let l=r[h][a];for(let i=0;i<3;i++){if(0==i&&1!=l&&-3!=l)continue;if(1==i&&-1==l)continue;if(2==i&&l>=1)continue;e=n[h][i];let o=this.p.p5play[e][r._uid];if(o){s=o[t._uid],s&&s.call(r,r,t,l);for(let e of t.groups)s=o[e._uid],s&&s.call(r,r,t,l)}let a=this.p.p5play[e][t._uid];if(a){s=a[r._uid],s&&s.call(t,t,r,l);for(let e of r.groups)s=a[e._uid],!s||o&&s==o[e._uid]||s.call(t,t,r,l)}}}o=!1}if(this._removed&&0==Object.keys(this._collisions).length&&0==Object.keys(this._overlappers).length){this._isSprite?delete this.p.p5play.sprites[this._uid]:this.p.p5play.targetVersion>=16&&delete this.p.p5play.groups[this._uid];for(let t in n)for(let e of n[t])delete this.p.p5play[e][this._uid]}},this.Sprite.prototype.addAnimation=this.Group.prototype.addAnimation=this.Sprite.prototype.addAni=this.Group.prototype.addAni=this.Sprite.prototype.addImage=this.Group.prototype.addImage=this.Sprite.prototype.addImg=this.Group.prototype.addImg=function(){if(this.p.p5play.disableImages)return void(this._ani=new this.p.SpriteAnimation);let t,e,i=[...arguments];return i[0]instanceof this.p.SpriteAnimation?(e=i[0],e._addedToSpriteOrGroup&&(e=e.clone()),t=e.name||"default",e.name=t):i[1]instanceof this.p.SpriteAnimation?(t=i[0],e=i[1],e._addedToSpriteOrGroup&&(e=e.clone()),e.name=t):(e=new this.p.SpriteAnimation(this,...i),t=e.name),this.animations[t]=e,this._ani=e,e._addedToSpriteOrGroup=!0,!this._dimensionsUndef||1==e.w&&1==e.h||(this.w=e.w,this.h=e.h),e},this.Sprite.prototype.addAnis=this.Group.prototype.addAnis=this.Sprite.prototype.addAnimations=this.Group.prototype.addAnimations=this.Sprite.prototype.addImages=this.Group.prototype.addImages=this.Sprite.prototype.addImgs=this.Group.prototype.addImgs=function(){let t,e=arguments;1==e.length?t=e[0]:(this.spriteSheet=e[0],t=e[1]);for(let e in t){let i=t[e];this.addAni(e,i)}},this.World=class extends e.World{constructor(){super(new e.Vec2(0,0),!0),this.p=t,this.mod=[],this.origin={x:0,y:0},this.contacts=[],this.on("begin-contact",this._beginContact),this.on("end-contact",this._endContact);let i=this;this._gravity={get x(){return i.m_gravity.x},set x(t){if((t=Math.round(t||0))!=i.m_gravity.x){i.mod[0]=!0;for(let t of i.p.allSprites)t.sleeping=!1;i.m_gravity.x=t}},get y(){return i.m_gravity.y},set y(t){if((t=Math.round(t||0))!=i.m_gravity.y){i.mod[0]=!0;for(let t of i.p.allSprites)t.sleeping=!1;i.m_gravity.y=t}}},this.velocityThreshold=.19,this.mouseTracking??=!0,this.mouseSprite=null,this.mouseSprites=[],this.autoStep=!0}get gravity(){return this._gravity}set gravity(t){this._gravity.x=t.x,this._gravity.y=t.y}get velocityThreshold(){return e.Settings.velocityThreshold}set velocityThreshold(t){e.Settings.velocityThreshold=t}step(t,e,i){for(let t of this.p.allSprites)t.prevPos.x=t.x,t.prevPos.y=t.y,t.prevRotation=t.rotation;super.step(t||1/(this.p._targetFrameRate||60),e||8,i||3);let s=Object.values(this.p.p5play.sprites),r=Object.values(this.p.p5play.groups);for(let t of s)t._step();for(let t of r)t._step();for(let t of s)t.___step();for(let t of r)t.___step();this.autoStep&&(this.autoStep=null)}getSpritesAt(t,s,r,o){o??=!0;const h=new e.Vec2(t/i,s/i),n=new e.AABB;n.lowerBound=new e.Vec2(h.x-.001,h.y-.001),n.upperBound=new e.Vec2(h.x+.001,h.y+.001);let a=[];if(this.queryAABB(n,(t=>(t.getShape().testPoint(t.getBody().getTransform(),h)&&a.push(t),!0))),0==a.length)return[];r??=this.p.allSprites;let l=[];for(let t of a){const e=t.m_body.sprite;e._cameraActiveWhenDrawn==o&&(l.find((t=>t._uid==e._uid))||l.push(e))}return l.sort(((t,e)=>-1*(t._layer-e._layer))),l}getSpriteAt(t,e,i){return this.getSpritesAt(t,e,i)[0]}getMouseSprites(){let t=this.getSpritesAt(this.p.mouse.x,this.p.mouse.y);if(this.p.camera._wasOff){let e=this.getSpritesAt(this.p.camera.mouse.x,this.p.camera.mouse.y,this.p.allSprites,!1);e.length&&(t=[...e,...t])}return t}_beginContact(t){let e=t.m_fixtureA,i=t.m_fixtureB,s="_collisions";e.m_isSensor&&(s="_overlappers"),e=e.m_body.sprite,i=i.m_body.sprite,e[s][i._uid]=0,i[s][e._uid]=0;for(let t of i.groups)(!e[s][t._uid]||e[s][t._uid]<0)&&(e[s][t._uid]=0,t[s][e._uid]=0);for(let t of e.groups){(!i[s][t._uid]||i[s][t._uid]<0)&&(i[s][t._uid]=0,t[s][i._uid]=0);for(let e of i.groups)(!t[s][e._uid]||t[s][e._uid]<0)&&(t[s][e._uid]=0,e[s][t._uid]=0)}}_endContact(t){let e=t.m_fixtureA,i=t.m_fixtureB,s="_collisions";e.m_isSensor&&(s="_overlappers"),e=e.m_body.sprite,i=i.m_body.sprite,e[s][i._uid]=0!=e[s][i._uid]?-2:-4,i[s][e._uid]=0!=i[s][e._uid]?-2:-4;for(let t of i.groups){let i=!1;for(let r of t)if(r[s][e._uid]>=0){i=!0;break}i||(t[s][e._uid]=0!=t[s][e._uid]?-2:-4,e[s][t._uid]=0!=e[s][t._uid]?-2:-4)}for(let t of e.groups){let e=!1;for(let r of t)if(r[s][i._uid]>=0){e=!0;break}if(!e){t[s][i._uid]=0!=t[s][i._uid]?-2:-4,i[s][t._uid]=0!=i[s][t._uid]?-2:-4;for(let e of i.groups)t[s][e._uid]=0!=t[s][e._uid]?-2:-4,e[s][t._uid]=0!=e[s][t._uid]?-2:-4}}}_findContact(t,e,i){let s=e[t][i._uid];if(s)return s;for(let r of i.groups)if(s=e[t][r._uid],s)return s;for(let r of e.groups){if(s=r[t][i._uid],s)return s;for(let e of i.groups)if(r._uid==e._uid&&(s=r[t][e._uid],s))return s}return!1}get allowSleeping(){return this.getAllowSleeping()}set allowSleeping(t){this.setAllowSleeping(t)}},this.Camera=class{constructor(){this.p=t;let e=this;this._pos=this.p.createVector.call(this.p),this.__pos={x:0,y:0,rounded:{}},this.mouse={x:this.p.mouseX,y:this.p.mouseY},this.mouse.pos=this.p.createVector.call(this.p),Object.defineProperty(this.mouse.pos,"x",{get:()=>e.mouse.x,set(t){e.mouse.x=t}}),Object.defineProperty(this.mouse.pos,"y",{get:()=>e.mouse.y,set(t){e.mouse.y=t}}),this.active=!1,this.bound={min:{x:0,y:0},max:{x:0,y:0}},this._zoomIdx=-1,this._zoom=1}get pos(){return this._pos}set pos(t){this.x=t.x,this.y=t.y}get position(){return this._pos}set position(t){this.x=t.x,this.y=t.y}_calcBoundsX(t){let e=this.p.canvas.hw/this._zoom;this.bound.min.x=t-e-100,this.bound.max.x=t+e+100}_calcBoundsY(t){let e=this.p.canvas.hh/this._zoom;this.bound.min.y=t-e-100,this.bound.max.y=t+e+100}get x(){return this._pos.x}set x(t){if(void 0===t||isNaN(t))return;this._pos.x=t;let e=-t+this.p.canvas.hw/this._zoom;this.__pos.x=e,this.p.allSprites.pixelPerfect&&(this.__pos.rounded.x=Math.round(e)),this._calcBoundsX(t)}get y(){return this._pos.y}set y(t){if(void 0===t||isNaN(t))return;this._pos.y=t;let e=-t+this.p.canvas.hh/this._zoom;this.__pos.y=e,this.p.allSprites.pixelPerfect&&(this.__pos.rounded.y=Math.round(e)),this._calcBoundsY(t)}get zoom(){return this._zoom}set zoom(t){if(void 0===t||isNaN(t))return;this._zoom=t;let e=-this._pos.x+this.p.canvas.hw/t,i=-this._pos.y+this.p.canvas.hh/t;this.__pos.x=e,this.__pos.y=i,this.p.allSprites.pixelPerfect&&(this.__pos.rounded.x=Math.round(e),this.__pos.rounded.y=Math.round(i)),this._calcBoundsX(this._pos.x),this._calcBoundsY(this._pos.y)}zoomTo(t,e){if(t==this._zoom)return Promise.resolve(!0);e??=.1;let i=Math.abs(t-this._zoom),s=Math.round(i/e);t{for(let t=0;t0&&(t=t<.1?this.p.map(t,0,.1,30,4):t<.5?this.p.map(t,.1,.5,4,2.5):t<.8?this.p.map(t,.5,.8,2.5,1):t<.9?this.p.map(t,.8,.9,1,.5):this.p.map(t,.9,1,.5,.2)),this._springiness=t,"wheel"==this.type?this._j.setSpringFrequencyHz(t):this._j.setFrequency(t)}get damping(){return"wheel"!=this.type?this._j.getDampingRatio():this._j.getSpringDampingRatio()}set damping(t){"wheel"==this.type?this._j.setSpringDampingRatio(t):this._j.setDampingRatio(t)}get speed(){return this._j.getJointSpeed()}set speed(t){this._j.isMotorEnabled()||this._j.enableMotor(!0),this._j.setMotorSpeed(t)}get motorSpeed(){return this._j.getMotorSpeed()}get enableMotor(){return this._j.isMotorEnabled()}set enableMotor(t){this._j.enableMotor(t)}get maxPower(){return this._j.getMaxMotorTorque()}set maxPower(t){!this._j.isMotorEnabled()&&t&&this._j.enableMotor(!0),this._j.setMaxMotorTorque(t),t||this._j.enableMotor(!1)}get power(){return this._j.getMotorTorque()}get collideConnected(){return this._j.getCollideConnected()}set collideConnected(t){this._j.m_collideConnected=t}remove(){this._removed||(this.spriteA.joints.splice(this.spriteA.joints.indexOf(this),1),this.spriteB.joints.splice(this.spriteB.joints.indexOf(this),1),this.p.world.destroyJoint(this._j),this._removed=!0)}},this.GlueJoint=class extends this.Joint{constructor(t,e){super(...arguments,"glue")}},this.DistanceJoint=class extends this.Joint{constructor(t,i){super(...arguments,"distance");let s=e.DistanceJoint({},t.body,i.body,t.body.getWorldCenter(),i.body.getWorldCenter());this._createJoint(s)}_display(){let t,e;(this.offsetA.x||this.offsetA.y)&&(t=this.spriteA.body.getWorldPoint(this._j.m_localAnchorA),t=r(t.x,t.y,this.spriteA.tileSize)),(this.offsetB.x||this.offsetB.y)&&(e=this.spriteB.body.getWorldPoint(this._j.m_localAnchorB),e=r(e.x,e.y,this.spriteB.tileSize)),this._draw(t?t.x:this.spriteA.x,t?t.y:this.spriteA.y,e?e.x:this.spriteB.x,e?e.y:this.spriteB.y),this.visible=null}},this.WheelJoint=class extends this.Joint{constructor(t,i){super(...arguments,"wheel");let s=e.WheelJoint({maxMotorTorque:1e3,frequencyHz:4,dampingRatio:.7},t.body,i.body,i.body.getWorldCenter(),new e.Vec2(0,1));this._createJoint(s),this._angle="degrees"==this.p._angleMode?90:1.5707963267948966}_display(){let t,e,i=this.spriteA.x,s=this.spriteA.y;if(this.offsetB.x||this.offsetB.y){let i=this.spriteB.body.getWorldPoint(this._j.m_localAnchorB);i=r(i.x,i.y,this.spriteB.tileSize),t=i.x,e=i.y}else t=this.spriteB.x,e=this.spriteB.y;let o=this.p.tan(this.spriteA.rotation),h=this.p.tan(this._angle+this.spriteA.rotation),n=(e-s+o*i-h*t)/(o-h),a=o*(n-i)+s;this._draw(n,a,t,e),this.visible=null}get angle(){return this._angle}set angle(t){t!=this._angle&&(this._angle=t,this._j.m_localXAxisA=new e.Vec2(this.p.cos(t),this.p.sin(t)),this._j.m_localXAxisA.normalize(),this._j.m_localYAxisA=e.Vec2.crossNumVec2(1,this._j.m_localXAxisA))}},this.HingeJoint=class extends this.Joint{constructor(t,i){super(...arguments,"hinge");let s=e.RevoluteJoint({},t.body,i.body,t.body.getWorldCenter());this._createJoint(s)}_display(){const t=this.offsetA.x,e=this.offsetA.y,i=this.spriteA.rotation,s=t*this.p.cos(i)-e*this.p.sin(i),r=t*this.p.sin(i)+e*this.p.cos(i);this._draw(this.spriteA.x+s,this.spriteA.y+r),this.visible=null}get range(){return this.upperLimit-this.lowerLimit}set range(t){t/=2,this.upperLimit=t,this.lowerLimit=-t}get lowerLimit(){let t=this._j.getLowerLimit();return"radians"==this.p._angleMode?t:this.p.degrees(t)}set lowerLimit(t){this._j.isLimitEnabled()||this._j.enableLimit(!0),this.spriteA.body.setAwake(!0),this.spriteB.body.setAwake(!0),"degrees"==this.p._angleMode&&(t=this.p.radians(t)),this._j.m_lowerAngle=t}get upperLimit(){let t=this._j.getUpperLimit();return"radians"==this.p._angleMode?t:this.p.degrees(t)}set upperLimit(t){this._j.isLimitEnabled()||this._j.enableLimit(!0),this.spriteA.body.setAwake(!0),this.spriteB.body.setAwake(!0),"degrees"==this.p._angleMode&&(t=this.p.radians(t)),this._j.m_upperAngle=t}get angle(){let e=this._j.getJointAngle();return"radians"==this.p._angleMode?e:t.radians(e)}},this.RevoluteJoint=this.HingeJoint,this.SliderJoint=class extends this.Joint{constructor(t,i){super(...arguments,"slider");let s=e.PrismaticJoint({lowerTranslation:-1,upperTranslation:1,enableLimit:!0,maxMotorForce:50,motorSpeed:0,enableMotor:!0},t.body,i.body,t.body.getWorldCenter(),new e.Vec2(1,0));this._createJoint(s),this._angle=0}get angle(){return this._angle}set angle(t){t!=this._angle&&(this._angle=t,this._j.m_localXAxisA=new e.Vec2(this.p.cos(t),this.p.sin(t)),this._j.m_localXAxisA.normalize(),this._j.m_localYAxisA=e.Vec2.crossNumVec2(1,this._j.m_localXAxisA))}get range(){return this.upperLimit-this.lowerLimit}set range(t){t/=2,this.upperLimit=t,this.lowerLimit=-t}get lowerLimit(){return this._j.getLowerLimit()/this.spriteA.tileSize*i}set lowerLimit(t){this._j.isLimitEnabled()||this._j.enableLimit(!0),t=t*this.spriteA.tileSize/i,this._j.setLimits(t,this._j.getUpperLimit())}get upperLimit(){return this._j.getUpperLimit()/this.spriteA.tileSize*i}set upperLimit(t){this._j.isLimitEnabled()||this._j.enableLimit(!0),t=t*this.spriteA.tileSize/i,this._j.setLimits(this._j.getLowerLimit(),t)}},this.PrismaticJoint=this.SliderJoint,this.RopeJoint=class extends this.Joint{constructor(t,i){super(...arguments,"rope");let s=e.RopeJoint({maxLength:1},t.body,i.body,t.body.getWorldCenter());this._createJoint(s),this._j.m_localAnchorB.x=0,this._j.m_localAnchorB.y=0}get maxLength(){return t=this._j.getMaxLength(),e=this.spriteA.tileSize,t/e*i;var t,e}set maxLength(t){var e,s;this._j.setMaxLength((e=t,s=this.spriteA.tileSize,e*s/i))}};class l{constructor(){let t=this;Object.defineProperties(this,{x:{get:()=>t._x,set(e){e!=t._x&&(t._x=e,t._avg=.5*(t._x+t._y))},configurable:!0,enumerable:!0},y:{get:()=>t._y,set(e){e!=t._y&&(t._y=e,t._avg=.5*(t._x+t._y))},configurable:!0,enumerable:!0},_x:{value:1,enumerable:!1,writable:!0},_y:{value:1,enumerable:!1,writable:!0},_avg:{value:1,enumerable:!1,writable:!0}})}valueOf(){return this._avg}}!function(){let t=new Float32Array(1),e=new Int32Array(t.buffer)}();function p(t){return!/^(?:(?:\/\*[^(?:\*\/)]*\*\/\s*)|(?:\/\/[^\r\n]*))*\s*(?:(?:(?:async\s(?:(?:\/\*[^(?:\*\/)]*\*\/\s*)|(?:\/\/[^\r\n]*))*\s*)?function|class)(?:\s|(?:(?:\/\*[^(?:\*\/)]*\*\/\s*)|(?:\/\/[^\r\n]*))*)|(?:[_$\w][\w0-9_$]*\s*(?:\/\*[^(?:\*\/)]*\*\/\s*)*\s*\()|(?:\[\s*(?:\/\*[^(?:\*\/)]*\*\/\s*)*\s*(?:(?:['][^']+['])|(?:["][^"]+["]))\s*(?:\/\*[^(?:\*\/)]*\*\/\s*)*\s*\]\())/.test(t.toString())}function d(t,e){let i=t,s=e.toLowerCase();if("triangle"==s?i=[i,-120,3]:"square"==s?i=[i,-90,4]:"pentagon"==s?i=[i,-72,5]:"hexagon"==s?i=[i,-60,6]:"septagon"==s?i=[i,-51.4285714286,7]:"octagon"==s?i=[i,-45,8]:"enneagon"==s?i=[i,-40,9]:"decagon"==s?i=[i,-36,10]:"hendecagon"==s?i=[i,-32.7272727273,11]:"dodecagon"==s&&(i=[i,-30,12]),i==t)throw new Error("Invalid, not a regular polygon: "+e);return i}this.p5play.palettes=[{a:"aqua",b:"black",c:"crimson",d:"darkviolet",e:"peachpuff",f:"olive",g:"green",h:"hotpink",i:"indigo",j:"navy",k:"khaki",l:"lime",m:"magenta",n:"brown",o:"orange",p:"pink",q:"turquoise",r:"red",s:"skyblue",t:"tan",u:"blue",v:"violet",w:"white",x:"gold",y:"yellow",z:"gray"}],this.colorPal=(e,i)=>{if(e instanceof p5.Color)return e;let s;return"number"==typeof i&&(i=t.p5play.palettes[i]),i??=t.p5play.palettes[0],i&&(s=i[e]),""===s||"."===e||" "===e?t.color(0,0,0,0):t.color(s||e)},this.spriteArt=(e,i,s)=>{i??=1,"number"==typeof s&&(s=t.p5play.palettes[s]),s??=t.p5play.palettes[0];let r=e;"string"==typeof e&&(r=(e=(e=(e=e.trim()).replace(/\r*\n\t+/g,"\n")).replace(/\s+$/g,"")).split("\n"));let o=0;for(let t of r)t.length>o&&(o=t.length);let h=r.length,n=t.createImage(o*i,h*i);n.loadPixels();for(let t=0;tnew Promise(t?e=>{setTimeout(e,t)}:requestAnimationFrame),this.sleep=t=>this.delay(t),this.play=t=>{if(!t?.play)throw new Error("Tried to play your sound but it wasn't a sound object.");return new Promise((e=>{t.play(),t.onended((()=>e()))}))};{let B=location.hostname;switch(B){case"":case"127.0.0.1":case"localhost":case"p5play.org":case"editor.p5js.org":case"codepen.io":case"codera.app":case"cdpn.io":case"glitch.com":case"replit.com":case"stackblitz.com":case"jsfiddle.net":case"aijs-912fe.web.app":break;default:if(/^[\d\.]+$/.test(B)||B.endsWith("stackblitz.io")||B.endsWith("glitch.me")||B.endsWith("repl.co")||B.endsWith("codehs.com")||B.endsWith("openprocessing.org")||location.origin.endsWith("preview.p5js.org"))break;!async function(){if(document.getElementById("p5play-intro"))return;t._incrementPreload();let e=document.createElement("div");e.id="p5play-intro",e.style="position: absolute; width: 100%; height: 100%; top: 0; left: 0; z-index: 1000; background-color: black;";let i=document.createElement("img");i.src="https://p5play.org/v3/made_with_p5play.png",i.style="position: absolute; top: 50%; left: 50%; width: 40vh; height: 20vh; margin-left: -20vh; margin-top: -10vh; z-index: 1000; opacity: 0; transition: opacity 0.1s ease-in-out;",document.body.append(e),e.append(i),await t.delay(100),i.style.opacity="1",i.style.transition="scale 1.4s, opacity 0.4s ease-in-out",i.style.scale="1.1",await t.delay(1100),i.style.opacity="0",await t.delay(300),e.style.display="none",e.remove(),document.getElementById("p5play-intro")?.remove(),t._decrementPreload()}()}}let u=p5.disableFriendlyErrors;p5.disableFriendlyErrors=!0,this.canvas=this.canvas;const _=this.createCanvas;this.createCanvas=function(){let e,i,s,r,o=[...arguments],h=!1,n=!1;if("string"==typeof o[0]&&(o[0].includes(":")?s=o[0].split(":"):(o[2]=o[0],o[0]=void 0),"fullscreen"==o[1]&&(h=!0)),o[0]?"number"==typeof o[0]&&"number"!=typeof o[1]&&(o[2]=o[1],o[1]=o[0]):(o[0]=window.innerWidth,o[1]=window.innerHeight,h=!0),"string"==typeof o[2]){let t=o[2].toLowerCase();"p2d"!=t&&"webgl"!=t&&(t=t.split(" "),o.pop()),"pixelated"==t[0]&&(n=!0,t[1]?r=Number(t[1].slice(1)):h=!0,s=[o[0],o[1]]),"fullscreen"==t[0]&&(h=!0)}if(s){let t=Number(s[0]),h=Number(s[1]);r?(e=t*r,i=h*r):(e=window.innerWidth,i=window.innerWidth*(h/t),i>window.innerHeight&&(e=window.innerHeight*(t/h),i=window.innerHeight)),e=Math.round(e),i=Math.round(i),n||(o[0]=e,o[1]=i)}let a=_.call(t,...o);this.canvas.tabIndex=0,this.canvas.w=o[0],this.canvas.h=o[1],this.canvas.addEventListener("keydown",(function(t){" "!=t.key&&"/"!=t.key&&"ArrowUp"!=t.key&&"ArrowDown"!=t.key&&"ArrowLeft"!=t.key&&"ArrowRight"!=t.key||t.preventDefault()})),this.canvas.addEventListener("mouseover",(()=>{this.mouse.isOnCanvas=!0,this.mouse.active=!0})),this.canvas.addEventListener("mouseleave",(()=>{this.mouse.isOnCanvas=!1})),this.canvas.addEventListener("touchstart",(t=>t.preventDefault())),this.canvas.addEventListener("contextmenu",(t=>t.preventDefault())),this.canvas.resize=this.resizeCanvas,this.canvas.hw=.5*this.canvas.w,this.canvas.hh=.5*this.canvas.h,this.camera.x=this.canvas.hw,this.camera.y=this.canvas.hh,u||(p5.disableFriendlyErrors=!1);let l="\n.p5Canvas, .q5Canvas {\n\toutline: none;\n\t-webkit-touch-callout: none;\n\t-webkit-text-size-adjust: none;\n\t-webkit-user-select: none;\n\toverscroll-behavior: none;\n}\nmain {\n\toverscroll-behavior: none;\n}";h&&(l="html,\nbody,\n"+l,l+="\nhtml, body {\n\tmargin: 0;\n\tpadding: 0;\n\toverflow: hidden;\n\theight: 100%;\n}\nmain {\n\tmargin: auto;\n\tdisplay: flex;\n\tflex-wrap: wrap;\n\talign-content: center;\n\tjustify-content: center;\n\theight: 100%;\n}"),n&&(l+=`\n#${this.canvas.id} {\n\timage-rendering: pixelated;\n\twidth: ${e}px!important;\n\theight: ${i}px!important;\n}`);let p=document.createElement("style");p.innerHTML=l,document.head.appendChild(p),n&&(t.pixelDensity(1),t.noSmooth());let d=navigator.userAgent.indexOf("iPhone OS");if(d>-1){let e=navigator.userAgent.substring(d+10,d+12);this.p5play.version=e,e<16&&t.pixelDensity(1),this.p5play.os.platform="iOS",this.p5play.os.version=e}else void 0!==navigator.userAgentData&&(this.p5play.os.platform=navigator.userAgentData.platform);return a},this.Canvas=class{constructor(t,e,i){}get w(){}get width(){}get h(){}get height(){}resize(){}},this.Canvas=function(){return t.createCanvas(...arguments)};const c=this.resizeCanvas;this.resizeCanvas=(t,e)=>{c.call(this,t,e),this.canvas.hw=.5*this.canvas.w,this.canvas.hh=.5*this.canvas.h,this.camera._pos.x=this.canvas.hw,this.camera._pos.y=this.canvas.hh};const f=this.background;this.background=function(){let t,e=arguments;1==e.length&&("string"==typeof e[0]||e[0]instanceof p5.Color)&&(t=this.colorPal(e[0])),void 0!==t?f.call(this,t):f.call(this,...e)};const g=this.fill;this.fill=function(){let t,e=arguments;1==e.length&&(t=this.colorPal(e[0])),void 0!==t?g.call(this,t):g.call(this,...e)};const y=this.stroke;this.stroke=function(){let t,e=arguments;1==e.length&&(t=this.colorPal(e[0])),void 0!==t?y.call(this,t):y.call(this,...e)},this.p5play.images={onLoad:t=>{}},this.p5play.disableImages=!1;const m=this.loadImage;this.loadImage=this.loadImg=function(){if(this.p5play.disableImages)return t._decrementPreload(),{w:16,width:16,h:16,height:16,pixels:[]};let e,i=arguments,s=i[0],r=t.p5play.images[s];if("function"==typeof i[i.length-1]&&(e=i[i.length-1]),r)return 1==r.width&&1==r.height||!r.pixels.length?e?(r.cbs.push(e),r.calls++):t._decrementPreload():(e&&e(),t._decrementPreload()),r;return r=m.call(t,s,(e=>{e.w=e.width,e.h=e.height;for(let t of e.cbs)t(e);for(let i=1;ithis.maxSize&&this.gc()}get(t){const e=super.get(t);return e&&(e.lastAccessed=Date.now()),e}gc(){let t,e=1/0,i=0;for(const[s,r]of this.entries())r.lastAccessed(e&&(I._tic.maxSize=e),void 0!==t&&(I._textCache=t),I._textCache),I.createTextImage=(t,e,i)=>{let s=I._textCache;I._textCache=!0,I._useCache=!0,I.text(t,0,0,e,i),I._useCache=!1;let r=x(t,e,i);return I._textCache=s,I._tic.get(r)};const W=I.text;I.text=(t,e,i,s,r)=>{if(void 0===t)return;t=t.toString();const o=I._renderer;if(!o._doFill&&!o._doStroke)return;let h,n,a,l,p,d,u;const _=I.canvas.getContext("2d");let c=_.getTransform();if(!(I._useCache||I._textCache&&(0!=c.b||0!=c.c)))return W.call(I,t,e,i,s,r);if(a=x(t,s,r),n=I._tic.get(a),n)return void I.textImage(n,e,i);let f=I.pixelDensity(),g=I.createGraphics.call(I,1,1);h=g.canvas.getContext("2d"),h.font=`${o._textStyle} ${o._textSize*f}px ${o._textFont}`;let y=t.split("\n");l=0,p=o._textLeading*f*y.length;let m=h.measureText(" ");d=m.fontBoundingBoxAscent,u=m.fontBoundingBoxDescent,r??=p+u,g.resizeCanvas(Math.ceil(g.textWidth(t)),Math.ceil(r)),h.fillStyle=_.fillStyle,h.strokeStyle=_.strokeStyle,h.lineWidth=_.lineWidth*f;let v=h.fillStyle;o._fillSet||(h.fillStyle="black");for(let t=0;tr));t++);o._fillSet||(h.fillStyle=v),n=g.get(),n.width/=f,n.height/=f,n._ascent=d/f,n._descent=u/f,I._tic.set(a,n),I.textImage(n,e,i)},I.textImage=(t,e,i)=>{let s=I._renderer._imageMode;I.imageMode.call(I,"corner");const r=I.canvas.getContext("2d");let o;"center"==r.textAlign?e-=.5*t.width:"right"==r.textAlign&&(e-=t.width),"alphabetic"==r.textBaseline?i-=I._renderer._textLeading:o=I._renderer._textLeading-I._renderer._textSize,"middle"==r.textBaseline?i-=t._descent+.5*t._ascent+o:"bottom"==r.textBaseline?i-=t._ascent+t._descent+o:"top"==r.textBaseline&&(i-=t._descent+o),I.image.call(I,t,e,i),I.imageMode.call(I,s)}}let w={generic:["Ah! I found an error","Oh no! Something went wrong","Oof! Something went wrong","Houston, we have a problem","Whoops, having trouble here"],Sprite:{constructor:{base:"Sorry I'm unable to make a new Sprite",0:"What is $0 for? If you're trying to specify the x position of the sprite, please specify the y position as well.",1:"If you're trying to specify points for a chain Sprite, please use an array of position arrays.\n$0",2:"Invalid input parameters: $0"},hw:{0:"I can't change the halfWidth of a Sprite directly, change the sprite's width instead."},hh:{1:"I can't change the halfHeight of a Sprite directly, change the sprite's height instead."},rotate:{0:"Can't use this function on a sprite with a static collider, try changing the sprite's collider type to kinematic.",1:'Can\'t use "$0" for the angle of rotation, it must be a number.'},rotateTo:{},rotateTowards:{},changeAnimation:'I can\'t find any animation named "$0".',collide:{0:"I can't make that sprite collide with $0. Sprites can only collide with another sprite or a group.",1:"The collision callback has to be a function.",2:"You're trying to check for an collision with a sprite or group that doesn't exist!"},overlap:{0:"I can't make that sprite overlap with $0. Sprites can only overlap with another sprite or a group.",1:"The overlap callback has to be a function.",2:"You're trying to check for an overlap with a sprite or group that doesn't exist!"}},SpriteAnimation:{constructor:{base:"Hey so, I tried to make a new SpriteAnimation but couldn't",0:'I don\'t know how to display this type of image: "$0". I can only use ".png" image files.',1:"The name of the animation must be the first input parameter."},frame:"Index $0 out of bounds. That means there is no frame $0 in this animation. It only has $1 frames!"},Group:{constructor:{base:"Hmm awkward! Well it seems I can't make that new Group you wanted"}}};w.Group.collide=w.Sprite.collide,w.Group.overlap=w.Sprite.overlap,w.Sprite.rotateTo[0]=w.Sprite.rotateTowards[0]=w.Sprite.rotate[0];class b extends Error{constructor(t,e,i){super(),"string"!=typeof t&&(i=e,e=t,t=(t=this.stack.match(/\n\s*at ([^\(]*)/)[1]).slice(0,-1)),"number"!=typeof e&&(i=e,e=void 0),"new"==t.slice(0,3)&&(t=t.slice(4));let s=(t=t.split("."))[0];t=t[1]||"constructor";let r=this.stack.match(/\/([^p\/][^5][^\/:]*:[^\/:]+):/);r&&(r=r[1].split(":"),r=" in "+r[0]+" at line "+r[1]),r=" using "+s+"."+t+". ",i=i||[];let o,h=w[s][t];o=h.base?h.base+r:w.generic[Math.floor(Math.random()*w.generic.length)]+r,void 0!==e&&(h=h[e]),h=h.replace(/\$([0-9]+)/g,((t,e)=>i[e])),o+=h,p5._friendlyError(o,t)}}this.allSprites=new this.Group,this.world=new this.World,this.camera=new this.Camera,this.InputDevice=class{constructor(){this.holdThreshold=12,this._default=0}_init(t){for(let e of t)this[e]=0}_ac(t){return t}presses(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),1==this[t]||-3==this[t]}pressing(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),-3==this[t]?1:this[t]>0?this[t]:0}pressed(t){return this.released(t)}holds(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),this[t]==this.holdThreshold}holding(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),this[t]>=this.holdThreshold?this[t]:0}held(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),-2==this[t]}released(t){return t??=this._default,void 0===this[t]&&(t=this._ac(t)),this[t]<=-1}releases(t){return this.released(t)}},this._Mouse=class extends this.InputDevice{constructor(){super(),this._default="left";let e=this;this._pos=t.createVector.call(t),Object.defineProperty(this._pos,"x",{get:()=>e.x,set(t){e.x=t}}),Object.defineProperty(this._pos,"y",{get:()=>e.y,set(t){e.y=t}}),this.x,this.y,this.left,this.center,this.right;this._init(["x","y","left","center","right"]),this.drag={left:0,center:0,right:0},this.isOnCanvas=!1,this.active=!1,this._visible=!0,this._cursor="default"}_ac(t){return"left"==(t=t.toLowerCase()).slice(0,4)?t="left":"right"==t.slice(0,5)?t="right":"middle"==t.slice(0,6)&&(t="center"),t}update(){this.x=(t.mouseX-t.canvas.hw)/t.camera.zoom+t.camera.x,this.y=(t.mouseY-t.canvas.hh)/t.camera.zoom+t.camera.y,t.camera.mouse.x=t.mouseX,t.camera.mouse.y=t.mouseY}get pos(){return this._pos}get position(){return this._pos}get cursor(){return t.canvas.style.cursor}set cursor(e){e!=this._cursor&&(t.cursor(e),this._cursor=e)}get visible(){return this._visible}set visible(e){this._visible=e,t.canvas.style.cursor=e?"default":"none"}drags(t){return t??=this._default,1==this.drag[t]}dragging(t){return t??=this._default,this.drag[t]>0?this.drag[t]:0}dragged(t){return t??=this._default,this.drag[t]<=-1}},this.mouse=new this._Mouse,this._SpriteMouse=class extends this._Mouse{constructor(){super(),this.hover=0}hovers(){return 1==this.hover}hovering(){return this.hover>0?this.hover:0}hovered(){return this.hover<=-1}};const S=function(t){if(this.mouse.active=!0,this.mouse[t]++,this.world.mouseSprites.length){let e=this.world.mouseSprite?.mouse;e&&(e[t]=0,e.hover=0,e.drag[t]=0),ms=this.world.mouseSprites[0],this.world.mouseSprite=ms,e=ms.mouse,e[t]=1,e.hover<=0&&(e.hover=1)}},C=t._onmousedown;t._onmousedown=function(t){if(!this._setupDone)return;let e="left";1===t.button?e="center":2===t.button&&(e="right"),S.call(this,e),C.call(this,t)};const A=t._ontouchstart;t._ontouchstart=function(t){if(!this._setupDone)return;A.call(this,t);let e=this.touches.at(-1);e.duration=0,e.presses=function(){return 1==this.duration||-3==this.duration},e.pressing=function(){return this.duration>0?this.duration:0},e.released=function(){return this.duration<=-1},1==this.touches.length&&(this.mouse.update(),this.world.mouseSprites=this.world.getMouseSprites()),S.call(this,"left")};const k=function(t){let e=this.mouse;if(e[t]>0&&e.drag[t]<=0){e.drag[t]=1;let i=this.world.mouseSprite?.mouse;i&&(i.drag[t]=1)}},z=t._onmousemove;t._onmousemove=function(t){if(!this._setupDone)return;let e="left";1===t.button?e="center":2===t.button&&(e="right"),k.call(this,e),z.call(this,t)};const M=t._ontouchmove;t._ontouchmove=function(t){this._setupDone&&(M.call(this,t),k.call(this,"left"))};const j=function(t){let e=this.mouse;e[t]>=e.holdThreshold?e[t]=-2:e[t]>1?e[t]=-1:e[t]=-3,e.drag[t]>0&&(e.drag[t]=-1);let i=this.world.mouseSprite?.mouse;i&&(i.hover>1?(i[t]>=this.mouse.holdThreshold?i[t]=-2:i[t]>1?i[t]=-1:i[t]=-3,i.drag[t]>0&&(i.drag[t]=-1)):(i[t]=0,i.drag[t]=0))},O=t._onmouseup;t._onmouseup=function(t){if(!this._setupDone)return;let e="left";1===t.button?e="center":2===t.button&&(e="right"),j.call(this,e),O.call(this,t)};const T=t._ontouchend;if(t._ontouchend=function(t){this._setupDone&&(T.call(this,t),j.call(this,"left"))},delete this._Mouse,this._KeyBoard=class extends this.InputDevice{#e;constructor(){super(),this._default=" ",this.alt=0,this.arrowUp=0,this.arrowDown=0,this.arrowLeft=0,this.arrowRight=0,this.backspace=0,this.capsLock=0,this.control=0,this.enter=0,this.meta=0,this.shift=0,this.tab=0;let t=this._simpleKeyControls={arrowUp:"up",arrowDown:"down",arrowLeft:"left",arrowRight:"right"};t.w=t.W="up",t.s=t.S="down",t.a=t.A="left",t.d=t.D="right",t.i=t.I="up2",t.k=t.K="down2",t.j=t.J="left2",t.l=t.L="right2"}_ac(t){if(1!=t.length){if(!isNaN(t)){if(38==t)return"arrowUp";if(40==t)return"arrowDown";if(37==t)return"arrowLeft";if(39==t)return"arrowRight";if(t>=10)throw new Error("Use key names with the keyboard input functions, not keyCode numbers!");return t}t=t.replaceAll(/[ _-]/g,"")}if(1!=(t=t.toLowerCase()).length){if("arrowup"==t)return"arrowUp";if("arrowdown"==t)return"arrowDown";if("arrowleft"==t)return"arrowLeft";if("arrowright"==t)return"arrowRight";if("capslock"==t)return"capsLock"}return t}_pre(t){(!this[t]||this[t]<0)&&(this[t]=1)}_rel(t){this[t]>=this.holdThreshold?this[t]=-2:this[t]>1?this[t]=-1:this[t]=-3}get cmd(){return this.meta}get command(){return this.meta}get ctrl(){return this.control}get space(){return this[" "]}get spacebar(){return this[" "]}get opt(){return this.alt}get option(){return this.alt}get win(){return this.meta}get windows(){return this.meta}},this.kb=new this._KeyBoard,delete this._KeyBoard,this.keyboard=this.kb,navigator.keyboard){const G=navigator.keyboard;window==window.top?G.getLayoutMap().then((t=>{"w"!=t.get("KeyW")&&(this.p5play.standardizeKeyboard=!0)})):this.p5play.standardizeKeyboard=!0}else this.p5play.standardizeKeyboard=!0;function P(t){let e=t.code;return 4==e.length&&"Key"==e.slice(0,3)?e[3].toLowerCase():t.key}const L=t._onkeydown;t._onkeydown=function(t){let e=t.key;if(this.p5play.standardizeKeyboard&&(e=P(t)),e.length>1)e=e[0].toLowerCase()+e.slice(1);else{let t=e.toLowerCase(),i=e.toUpperCase();t!=i&&(e!=i?this.kb._pre(i):this.kb._pre(t))}this.kb._pre(e);let i=this.kb._simpleKeyControls[e];i&&this.kb._pre(i),L.call(this,t)};const D=t._onkeyup;t._onkeyup=function(t){let e=t.key;if(this.p5play.standardizeKeyboard&&(e=P(t)),e.length>1)e=e[0].toLowerCase()+e.slice(1);else{let t=e.toLowerCase(),i=e.toUpperCase();t!=i&&(e!=i?this.kb._rel(i):this.kb._rel(t))}this.kb._rel(e);let i=this.kb._simpleKeyControls[e];if(i&&this.kb._rel(i),t.shiftKey){let t=e.toLowerCase();this.kb[t]>0&&this.kb._rel(t)}D.call(this,t)},this._Contro=class extends this.InputDevice{constructor(t){super(),this._default="a",this.connected=!0;this._init(["a","b","x","y","l","r","lt","rt","select","start","lsb","rsb","up","down","left","right","leftTrigger","rightTrigger"]),this.leftStick={x:0,y:0},this.rightStick={x:0,y:0},this._btns={a:0,b:1,x:2,y:3,l:4,r:5,lt:6,rt:7,select:8,start:9,lsb:10,rsb:11,up:12,down:13,left:14,right:15},this._axes={leftStick:{x:0,y:1},rightStick:{x:2,y:3},leftTrigger:4,rightTrigger:5},t.id.includes("GuliKit")&&(this._btns.a=1,this._btns.b=0,this._btns.x=3,this._btns.y=2),this.gamepad=t,this.id=t.id}_ac(t){return"lb"==(t=t.toLowerCase())?t="l":"rb"==t?t="r":"leftstickbutton"==t?t="lsb":"rightstickbutton"==t&&(t="rsb"),t}_update(){if(!this.connected)return;if(this.gamepad=navigator.getGamepads()[this.gamepad.index],!this.gamepad?.connected)return;let t=this.gamepad;for(let e in this._btns){let i=this._btns[e],s=t.buttons[i];s&&(s.pressed?this[e]++:this[e]=this[e]>0?-1:0)}return this.leftStick.x=t.axes[this._axes.leftStick.x],this.leftStick.y=t.axes[this._axes.leftStick.y],this.rightStick.x=t.axes[this._axes.rightStick.x],this.rightStick.y=t.axes[this._axes.rightStick.y],void 0!==t.axes[this._axes.leftTrigger]?(this.leftTrigger=t.axes[this._axes.leftTrigger],this.rightTrigger=t.axes[this._axes.rightTrigger]):(this.leftTrigger=t.buttons[this._btns.lt].value,this.rightTrigger=t.buttons[this._btns.rt].value),!0}get ls(){return this.leftStick}get rs(){return this.rightStick}get lb(){return this.l}get rb(){return this.r}get leftStickButton(){return this.lsb}get rightStickButton(){return this.rsb}},this._Contros=class extends Array{constructor(){super();let t=this;window.addEventListener("gamepadconnected",(e=>{t._onConnect(e.gamepad)})),window.addEventListener("gamepaddisconnected",(e=>{t._onDisconnect(e.gamepad)})),this.presses,this.pressing,this.pressed,this.holds,this.holding,this.held,this.released;let e=["presses","pressing","pressed","holds","holding","held","released"];for(let t of e)this[t]=e=>{if(this[0])return this[0][t](e)};this.a=0,this.b=0,this.x=0,this.y=0,this.l=0,this.r=0,this.lt=0,this.rt=0,this.select=0,this.start=0,this.lsb=0,this.rsb=0,this.up=0,this.down=0,this.left=0,this.right=0,this.leftTrigger=0,this.rightTrigger=0,this.lb=0,this.rb=0,this.leftStickButton=0,this.rightStickButton=0;let i=["connected","a","b","x","y","l","r","lt","rt","select","start","lsb","rsb","up","down","left","right","leftTrigger","rightTrigger","lb","rb","leftStickButton","rightStickButton"];for(let e of i)Object.defineProperty(this,e,{get:()=>t[0]?t[0][e]:0});this.leftStick,this.rightStick,i=["leftStick","rightStick"];for(let e of i){this[e]={};for(let i of["x","y"])Object.defineProperty(this[e],i,{get:()=>t[0]?t[0][e][i]:0})}if(!navigator?.getGamepads)return;let s=navigator.getGamepads();for(let t of s)t&&this._onConnect(t)}_onConnect(e){if(!e)return;for(let t=0;tthis.p5play._fps,this.p5play._fpsArr=[60],this.renderStats=(t,e)=>{let i=this.p5play._renderStats;void 0===i.show&&(1==this.allSprites.tileSize||this.allSprites.tileSize>16?i.fontSize=16:i.fontSize=10,i.gap=1.25*i.fontSize,console.warn("renderStats() uses inaccurate FPS approximations. Even if your game runs at a solid 60hz display rate, the fps calculations shown may be lower. The only way to get accurate results is to use your web browser's performance testing tools.")),i.x=t||10,i.y=e||20,i.show=!0}})),p5.prototype.registerMethod("pre",(function(){this.p5play._fps&&(this.p5play._preDrawFrameTime=performance.now()),this.p5play.spritesDrawn=0,this.mouse.update(),this.contro._update()})),p5.prototype.registerMethod("post",(function(){this.p5play._inPostDraw=!0,this.allSprites.autoCull&&this.allSprites.cull(1e4),this.allSprites._autoDraw&&(this.camera.on(),this.allSprites.draw(),this.camera.off()),this.allSprites._autoDraw??=!0;let t=this.p5play._renderStats;if(t.show){if(1==this.frameCount||this.frameCount%60==0){let t,e=this.p5play._fpsArr.reduce(((t,e)=>t+e));e=Math.round(e/this.p5play._fpsArr.length),this.p5play._fpsAvg=e,this.p5play._fpsMin=Math.min(...this.p5play._fpsArr),this.p5play._fpsMax=Math.max(...this.p5play._fpsArr),this.p5play._fpsArr=[],t=e>55?this.color(30,255,30):e>25?this.color(255,100,30):this.color(255,30,30),this.p5play._statsColor=t}this.p5play._fpsArr.push(this.getFPS()),this.push(),this.fill(0,0,0,128),this.rect(t.x-5,t.y-t.fontSize,8.5*t.fontSize,4*t.gap+5),this.fill(this.p5play._statsColor),this.textAlign("left"),this.textSize(t.fontSize),this.textFont("monospace");let e=t.x,i=t.y;this.text("sprites: "+this.p5play.spritesDrawn,e,i),this.text("fps avg: "+this.p5play._fpsAvg,e,i+t.gap),this.text("fps min: "+this.p5play._fpsMin,e,i+2*t.gap),this.text("fps max: "+this.p5play._fpsMax,e,i+3*t.gap),this.pop(),t.show=!1}this.world.autoStep&&this.world.step(),this.world.autoStep??=!0,this.allSprites._autoUpdate&&this.allSprites.update(),this.allSprites._autoUpdate??=!0;for(let t of this.allSprites)t.autoDraw??=!0,t.autoUpdate??=!0;for(let t in this.kb)"holdThreshold"!=t&&(this.kb[t]<0?this.kb[t]=0:this.kb[t]>0&&this.kb[t]++);let e=this.mouse,i=this.world.mouseSprite?.mouse;for(let t of["left","center","right"])e[t]<0?e[t]=0:e[t]>0&&e[t]++,i?.hover&&(i[t]=e[t]),e.drag[t]<0?e.drag[t]=0:e.drag[t]>0&&e.drag[t]++,i&&(i.drag[t]=e.drag[t]);if(this.world.mouseTracking){let t=this.world.getMouseSprites();for(let e=0;e0?i.mouse.hover=-1:i.mouse.hover<0&&(i.mouse.hover=0)}e.left<=0&&e.center<=0&&e.right<=0&&(this.world.mouseSprite=null);let s=this.world.mouseSprite,r=e.drag.left>0||e.drag.center>0||e.drag.right>0;for(let e of this.world.mouseSprites)if(!t.includes(e)){let t=e.mouse;t.hover>0&&(t.hover=-1,t.left=t.center=t.right=0),r||e!=s||(this.world.mouseSprite=s=null)}s&&(t.includes(s)||t.push(s),i.x=s.x-e.x,i.y=s.y-e.y),this.world.mouseSprites=t}this.camera.off(),this.p5play._fps&&(this.p5play._postDrawFrameTime=performance.now(),this.p5play._fps=Math.round(1e3/(this.p5play._postDrawFrameTime-this.p5play._preDrawFrameTime))||1),this.p5play._inPostDraw=!1})); diff --git a/package.json b/package.json index 15507f1c..d80d3943 100644 --- a/package.json +++ b/package.json @@ -39,5 +39,5 @@ "version": "git add -A", "postversion": "git push" }, - "version": "3.16.5" + "version": "3.16.6" }