gdcore-tools 2.0.0-gd-v5.5.231-autobuild → 2.0.0-gd-v5.5.232-autobuild
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Runtime/CustomRuntimeObject.js +1 -1
- package/dist/Runtime/CustomRuntimeObject.js.map +2 -2
- package/dist/Runtime/CustomRuntimeObject2D.js +1 -1
- package/dist/Runtime/CustomRuntimeObject2D.js.map +2 -2
- package/dist/Runtime/CustomRuntimeObjectInstanceContainer.js +1 -1
- package/dist/Runtime/CustomRuntimeObjectInstanceContainer.js.map +2 -2
- package/dist/Runtime/Extensions/3D/CustomRuntimeObject3D.js +1 -1
- package/dist/Runtime/Extensions/3D/CustomRuntimeObject3D.js.map +2 -2
- package/dist/Runtime/Extensions/3D/CustomRuntimeObject3DRenderer.js +1 -1
- package/dist/Runtime/Extensions/3D/CustomRuntimeObject3DRenderer.js.map +2 -2
- package/dist/Runtime/Extensions/PanelSpriteObject/panelspriteruntimeobject-pixi-renderer.js +1 -1
- package/dist/Runtime/Extensions/PanelSpriteObject/panelspriteruntimeobject-pixi-renderer.js.map +2 -2
- package/dist/Runtime/Extensions/PlatformBehavior/platformerobjectruntimebehavior.js +1 -1
- package/dist/Runtime/Extensions/PlatformBehavior/platformerobjectruntimebehavior.js.map +2 -2
- package/dist/Runtime/Extensions/TopDownMovementBehavior/topdownmovementruntimebehavior.js +1 -1
- package/dist/Runtime/Extensions/TopDownMovementBehavior/topdownmovementruntimebehavior.js.map +2 -2
- package/dist/Runtime/Extensions/TweenBehavior/JsExtension.js +1 -1
- package/dist/Runtime/RuntimeInstanceContainer.js +1 -1
- package/dist/Runtime/RuntimeInstanceContainer.js.map +2 -2
- package/dist/Runtime/debugger-client/hot-reloader.js +3 -2
- package/dist/Runtime/debugger-client/hot-reloader.js.map +2 -2
- package/dist/Runtime/howler-sound-manager/howler-sound-manager.js +1 -1
- package/dist/Runtime/howler-sound-manager/howler-sound-manager.js.map +2 -2
- package/dist/Runtime/pixi-renderers/CustomRuntimeObject2DPixiRenderer.js +1 -1
- package/dist/Runtime/pixi-renderers/CustomRuntimeObject2DPixiRenderer.js.map +2 -2
- package/dist/Runtime/types/project-data.d.ts +1 -1
- package/dist/lib/libGD.cjs +1 -1
- package/dist/lib/libGD.wasm +0 -0
- package/gd.d.ts +6 -0
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(l){class p extends l.RuntimeBehavior{constructor(t,e,d){super(t,e,d);this._angle=0;this._xVelocity=0;this._yVelocity=0;this._angularSpeed=0;this._leftKey=!1;this._rightKey=!1;this._upKey=!1;this._downKey=!1;this._leftKeyPressedDuration=0;this._rightKeyPressedDuration=0;this._upKeyPressedDuration=0;this._downKeyPressedDuration=0;this._wasStickUsed=!1;this._stickAngle=0;this._stickForce=0;this._dontClearInputsBetweenFrames=!1;this._ignoreDefaultControlsAsSyncedByNetwork=!1;this._wasLeftKeyPressed=!1;this._wasRightKeyPressed=!1;this._wasUpKeyPressed=!1;this._wasDownKeyPressed=!1;this._temporaryPointForTransformations=[0,0];this._topDownMovementHooks=[];this._allowDiagonals=e.allowDiagonals,this._acceleration=e.acceleration,this._deceleration=e.deceleration,this._maxSpeed=e.maxSpeed,this._angularMaxSpeed=e.angularMaxSpeed,this._rotateObject=e.rotateObject,this._angleOffset=e.angleOffset,this._ignoreDefaultControls=e.ignoreDefaultControls,this.setViewpoint(e.viewpoint,e.customIsometryAngle),this._movementAngleOffset=e.movementAngleOffset||0}getNetworkSyncData(){return this._dontClearInputsBetweenFrames=!1,this._ignoreDefaultControlsAsSyncedByNetwork=!1,{...super.getNetworkSyncData(),props:{a:this._angle,xv:this._xVelocity,yv:this._yVelocity,as:this._angularSpeed,lk:this._wasLeftKeyPressed,rk:this._wasRightKeyPressed,uk:this._wasUpKeyPressed,dk:this._wasDownKeyPressed,wsu:this._wasStickUsed,sa:this._stickAngle,sf:this._stickForce}}}updateFromNetworkSyncData(t){super.updateFromNetworkSyncData(t);const e=t.props;e.a!==void 0&&(this._angle=e.a),e.xv!==void 0&&(this._xVelocity=e.xv),e.yv!==void 0&&(this._yVelocity=e.yv),e.as!==void 0&&(this._angularSpeed=e.as),e.lk!==void 0&&(this._leftKey=e.lk),e.rk!==void 0&&(this._rightKey=e.rk),e.uk!==void 0&&(this._upKey=e.uk),e.dk!==void 0&&(this._downKey=e.dk),e.wsu!==void 0&&(this._wasStickUsed=e.wsu),e.sa!==void 0&&(this._stickAngle=e.sa),e.sf!==void 0&&(this._stickForce=e.sf),this._dontClearInputsBetweenFrames=!0,this._ignoreDefaultControlsAsSyncedByNetwork=!0}updateFromBehaviorData(t,e){return t.allowDiagonals!==e.allowDiagonals&&(this._allowDiagonals=e.allowDiagonals),t.acceleration!==e.acceleration&&(this._acceleration=e.acceleration),t.deceleration!==e.deceleration&&(this._deceleration=e.deceleration),t.maxSpeed!==e.maxSpeed&&(this._maxSpeed=e.maxSpeed),t.angularMaxSpeed!==e.angularMaxSpeed&&(this._angularMaxSpeed=e.angularMaxSpeed),t.rotateObject!==e.rotateObject&&(this._rotateObject=e.rotateObject),t.angleOffset!==e.angleOffset&&(this._angleOffset=e.angleOffset),t.ignoreDefaultControls!==e.ignoreDefaultControls&&(this._ignoreDefaultControls=e.ignoreDefaultControls),(t.platformType!==e.platformType||t.customIsometryAngle!==e.customIsometryAngle)&&this.setViewpoint(e.platformType,e.customIsometryAngle),t.movementAngleOffset!==e.movementAngleOffset&&(this._movementAngleOffset=e.movementAngleOffset),!0}setViewpoint(t,e){t==="PixelIsometry"?this._basisTransformation=new l.TopDownMovementRuntimeBehavior.IsometryTransformation(Math.atan(.5)):t==="TrueIsometry"?this._basisTransformation=new l.TopDownMovementRuntimeBehavior.IsometryTransformation(Math.PI/6):t==="CustomIsometry"?this._basisTransformation=new l.TopDownMovementRuntimeBehavior.IsometryTransformation(e*Math.PI/180):this._basisTransformation=null}setAcceleration(t){this._acceleration=t}getAcceleration(){return this._acceleration}setDeceleration(t){this._deceleration=t}getDeceleration(){return this._deceleration}setMaxSpeed(t){this._maxSpeed=t}getMaxSpeed(){return this._maxSpeed}setAngularMaxSpeed(t){this._angularMaxSpeed=t}getAngularMaxSpeed(){return this._angularMaxSpeed}setAngleOffset(t){this._angleOffset=t}getAngleOffset(){return this._angleOffset}allowDiagonals(t){this._allowDiagonals=t}diagonalsAllowed(){return this._allowDiagonals}setRotateObject(t){this._rotateObject=t}isObjectRotated(){return this._rotateObject}isMoving(){return this._xVelocity!==0||this._yVelocity!==0}getSpeed(){return Math.sqrt(this._xVelocity*this._xVelocity+this._yVelocity*this._yVelocity)}getXVelocity(){return this._xVelocity}setXVelocity(t){this._xVelocity=t}getYVelocity(){return this._yVelocity}setYVelocity(t){this._yVelocity=t}getAngle(){return this._angle}isMovementAngleAround(t,e){return Math.abs(l.evtTools.common.angleDifference(this._angle,t))<=e}setMovementAngleOffset(t){this._movementAngleOffset=t}getMovementAngleOffset(){return this._movementAngleOffset}doStepPreEvents(t){const e=37,d=38,u=39,r=40;this._leftKey||(this._leftKey=!this.shouldIgnoreDefaultControls()&&t.getGame().getInputManager().isKeyPressed(e)),this._rightKey||(this._rightKey=!this.shouldIgnoreDefaultControls()&&t.getGame().getInputManager().isKeyPressed(u)),this._downKey||(this._downKey=!this.shouldIgnoreDefaultControls()&&t.getGame().getInputManager().isKeyPressed(r)),this._upKey||(this._upKey=!this.shouldIgnoreDefaultControls()&&t.getGame().getInputManager().isKeyPressed(d));const _=this.owner.getElapsedTime();this._leftKey?this._leftKeyPressedDuration+=_:this._leftKeyPressedDuration=0,this._rightKey?this._rightKeyPressedDuration+=_:this._rightKeyPressedDuration=0,this._downKey?this._downKeyPressedDuration+=_:this._downKeyPressedDuration=0,this._upKey?this._upKeyPressedDuration+=_:this._upKeyPressedDuration=0;let s=-1;this._allowDiagonals?this._upKey&&!this._downKey?this._leftKey&&!this._rightKey?s=5:!this._leftKey&&this._rightKey?s=7:s=6:!this._upKey&&this._downKey?this._leftKey&&!this._rightKey?s=3:!this._leftKey&&this._rightKey?s=1:s=2:this._leftKey&&!this._rightKey?s=4:!this._leftKey&&this._rightKey&&(s=0):(this._upKey&&!this._downKey?s=6:!this._upKey&&this._downKey&&(s=2),this._leftKey&&!this._rightKey&&(this._upKey===this._downKey||this._upKey&&this._leftKeyPressedDuration<this._upKeyPressedDuration||this._downKey&&this._leftKeyPressedDuration<this._downKeyPressedDuration)?s=4:this._rightKey&&!this._leftKey&&(this._upKey===this._downKey||this._upKey&&this._rightKeyPressedDuration<this._upKeyPressedDuration||this._downKey&&this._rightKeyPressedDuration<this._downKeyPressedDuration)&&(s=0));const h=l.TopDownMovementRuntimeBehavior._topDownMovementHookContext;for(const o of this._topDownMovementHooks)h._setDirection(s),s=o.overrideDirection(h);h._setDirection(s);for(const o of this._topDownMovementHooks)o.beforeSpeedUpdate(h);const a=this.owner,y=this.owner.getElapsedTime()/1e3,w=this._xVelocity,v=this._yVelocity;this._wasStickUsed=!1;let f=0,c=0,i=1,n=0;if(s!==-1)f=(s+this._movementAngleOffset/45)*Math.PI/4,c=s*45+this._movementAngleOffset,i=Math.cos(f),n=Math.sin(f),(i===-1||i===1)&&(n=0),(n===-1||n===1)&&(i=0),this._xVelocity+=this._acceleration*y*i,this._yVelocity+=this._acceleration*y*n;else if(this._stickForce!==0){this._allowDiagonals||(this._stickAngle=90*Math.floor((this._stickAngle+45)/90)),c=this._stickAngle+this._movementAngleOffset,f=c*Math.PI/180;const o=this._acceleration*y*this._stickForce;i=Math.cos(f),n=Math.sin(f),(i===-1||i===1)&&(n=0),(n===-1||n===1)&&(i=0),this._xVelocity+=o*i,this._yVelocity+=o*n,this._wasStickUsed=!0,this._stickForce=0}else if(this._yVelocity!==0||this._xVelocity!==0){f=Math.atan2(this._yVelocity,this._xVelocity),c=f*180/Math.PI;const o=this._xVelocity>=0,M=this._yVelocity>=0;i=Math.cos(f),n=Math.sin(f),(i===-1||i===1)&&(n=0),(n===-1||n===1)&&(i=0),this._xVelocity-=this._deceleration*y*i,this._yVelocity-=this._deceleration*y*n,this._xVelocity>0!==o&&(this._xVelocity=0),this._yVelocity>0!==M&&(this._yVelocity=0)}this._xVelocity*this._xVelocity+this._yVelocity*this._yVelocity>this._maxSpeed*this._maxSpeed&&(this._xVelocity=this._maxSpeed*i,this._yVelocity=this._maxSpeed*n),this._angularSpeed=this._angularMaxSpeed;for(const o of this._topDownMovementHooks)o.beforePositionUpdate(h);const g=(w+this._xVelocity)/2*y,m=(v+this._yVelocity)/2*y;if(this._basisTransformation===null)a.setX(a.getX()+g),a.setY(a.getY()+m);else{const o=this._temporaryPointForTransformations;o[0]=g,o[1]=m,this._basisTransformation.toScreen(o,o),a.setX(a.getX()+o[0]),a.setY(a.getY()+o[1])}(this._xVelocity!==0||this._yVelocity!==0)&&(this._angle=c,this._rotateObject&&a.rotateTowardAngle(c+this._angleOffset,this._angularSpeed)),this._wasLeftKeyPressed=this._leftKey,this._wasRightKeyPressed=this._rightKey,this._wasUpKeyPressed=this._upKey,this._wasDownKeyPressed=this._downKey,this._dontClearInputsBetweenFrames||(this._leftKey=!1,this._rightKey=!1,this._upKey=!1,this._downKey=!1)}simulateControl(t){t==="Left"?this._leftKey=!0:t==="Right"?this._rightKey=!0:t==="Up"?this._upKey=!0:t==="Down"&&(this._downKey=!0)}ignoreDefaultControls(t){this._ignoreDefaultControls=t}shouldIgnoreDefaultControls(){return this._ignoreDefaultControls||this._ignoreDefaultControlsAsSyncedByNetwork}simulateLeftKey(){this._leftKey=!0}simulateRightKey(){this._rightKey=!0}simulateUpKey(){this._upKey=!0}simulateDownKey(){this._downKey=!0}simulateStick(t,e){this._stickAngle=t%360,this._stickForce=Math.max(0,Math.min(1,e))}isUsingControl(t){return t==="Left"?this._leftKeyPressedDuration>0:t==="Right"?this._rightKeyPressedDuration>0:t==="Up"?this._upKeyPressedDuration>0:t==="Down"?this._downKeyPressedDuration>0:t==="Stick"?this._wasStickUsed:!1}getLastStickInputAngle(){return this._stickAngle}registerHook(t){this._topDownMovementHooks.push(t)}}l.TopDownMovementRuntimeBehavior=p,function(d){class K{constructor(){this.direction=-1}getDirection(){return this.direction}_setDirection(r){this.direction=r}}d.TopDownMovementHookContext=K,d._topDownMovementHookContext=new l.TopDownMovementRuntimeBehavior.TopDownMovementHookContext;class e{constructor(r){if(r<=0||r>=Math.PI/4)throw new RangeError("An isometry angle must be in ]0; pi/4] but was: "+r);const _=Math.asin(Math.tan(r)),s=Math.sin(_),h=Math.cos(Math.PI/4),a=h;this._screen=[[h,-a],[s*a,s*h]]}toScreen(r,_){const s=this._screen[0][0]*r[0]+this._screen[0][1]*r[1],h=this._screen[1][0]*r[0]+this._screen[1][1]*r[1];_[0]=s,_[1]=h}}d.IsometryTransformation=e}(p=l.TopDownMovementRuntimeBehavior||(l.TopDownMovementRuntimeBehavior={})),l.registerBehavior("TopDownMovementBehavior::TopDownMovementBehavior",l.TopDownMovementRuntimeBehavior)})(gdjs||(gdjs={}));
|
|
1
|
+
var gdjs;(function(r){class c extends r.RuntimeBehavior{constructor(e,t,f){super(e,t,f);this._angle=0;this._xVelocity=0;this._yVelocity=0;this._angularSpeed=0;this._leftKey=!1;this._rightKey=!1;this._upKey=!1;this._downKey=!1;this._leftKeyPressedDuration=0;this._rightKeyPressedDuration=0;this._upKeyPressedDuration=0;this._downKeyPressedDuration=0;this._wasStickUsed=!1;this._stickAngle=0;this._stickForce=0;this._dontClearInputsBetweenFrames=!1;this._ignoreDefaultControlsAsSyncedByNetwork=!1;this._wasLeftKeyPressed=!1;this._wasRightKeyPressed=!1;this._wasUpKeyPressed=!1;this._wasDownKeyPressed=!1;this._temporaryPointForTransformations=[0,0];this._topDownMovementHooks=[];this._allowDiagonals=t.allowDiagonals,this._acceleration=t.acceleration,this._deceleration=t.deceleration,this._maxSpeed=t.maxSpeed,this._angularMaxSpeed=t.angularMaxSpeed,this._rotateObject=t.rotateObject,this._angleOffset=t.angleOffset,this._ignoreDefaultControls=t.ignoreDefaultControls,this.setViewpoint(t.viewpoint,t.customIsometryAngle),this._movementAngleOffset=t.movementAngleOffset||0,this._useLegacyTurnBack=t.useLegacyTurnBack===void 0?!0:t.useLegacyTurnBack}getNetworkSyncData(){return this._dontClearInputsBetweenFrames=!1,this._ignoreDefaultControlsAsSyncedByNetwork=!1,{...super.getNetworkSyncData(),props:{a:this._angle,xv:this._xVelocity,yv:this._yVelocity,as:this._angularSpeed,lk:this._wasLeftKeyPressed,rk:this._wasRightKeyPressed,uk:this._wasUpKeyPressed,dk:this._wasDownKeyPressed,wsu:this._wasStickUsed,sa:this._stickAngle,sf:this._stickForce}}}updateFromNetworkSyncData(e){super.updateFromNetworkSyncData(e);const t=e.props;t.a!==void 0&&(this._angle=t.a),t.xv!==void 0&&(this._xVelocity=t.xv),t.yv!==void 0&&(this._yVelocity=t.yv),t.as!==void 0&&(this._angularSpeed=t.as),t.lk!==void 0&&(this._leftKey=t.lk),t.rk!==void 0&&(this._rightKey=t.rk),t.uk!==void 0&&(this._upKey=t.uk),t.dk!==void 0&&(this._downKey=t.dk),t.wsu!==void 0&&(this._wasStickUsed=t.wsu),t.sa!==void 0&&(this._stickAngle=t.sa),t.sf!==void 0&&(this._stickForce=t.sf),this._dontClearInputsBetweenFrames=!0,this._ignoreDefaultControlsAsSyncedByNetwork=!0}updateFromBehaviorData(e,t){return e.allowDiagonals!==t.allowDiagonals&&(this._allowDiagonals=t.allowDiagonals),e.acceleration!==t.acceleration&&(this._acceleration=t.acceleration),e.deceleration!==t.deceleration&&(this._deceleration=t.deceleration),e.maxSpeed!==t.maxSpeed&&(this._maxSpeed=t.maxSpeed),e.angularMaxSpeed!==t.angularMaxSpeed&&(this._angularMaxSpeed=t.angularMaxSpeed),e.rotateObject!==t.rotateObject&&(this._rotateObject=t.rotateObject),e.angleOffset!==t.angleOffset&&(this._angleOffset=t.angleOffset),e.ignoreDefaultControls!==t.ignoreDefaultControls&&(this._ignoreDefaultControls=t.ignoreDefaultControls),(e.platformType!==t.platformType||e.customIsometryAngle!==t.customIsometryAngle)&&this.setViewpoint(t.platformType,t.customIsometryAngle),e.movementAngleOffset!==t.movementAngleOffset&&(this._movementAngleOffset=t.movementAngleOffset),!0}setViewpoint(e,t){e==="PixelIsometry"?this._basisTransformation=new r.TopDownMovementRuntimeBehavior.IsometryTransformation(Math.atan(.5)):e==="TrueIsometry"?this._basisTransformation=new r.TopDownMovementRuntimeBehavior.IsometryTransformation(Math.PI/6):e==="CustomIsometry"?this._basisTransformation=new r.TopDownMovementRuntimeBehavior.IsometryTransformation(t*Math.PI/180):this._basisTransformation=null}setAcceleration(e){this._acceleration=e}getAcceleration(){return this._acceleration}setDeceleration(e){this._deceleration=e}getDeceleration(){return this._deceleration}setMaxSpeed(e){this._maxSpeed=e}getMaxSpeed(){return this._maxSpeed}setAngularMaxSpeed(e){this._angularMaxSpeed=e}getAngularMaxSpeed(){return this._angularMaxSpeed}setAngleOffset(e){this._angleOffset=e}getAngleOffset(){return this._angleOffset}allowDiagonals(e){this._allowDiagonals=e}diagonalsAllowed(){return this._allowDiagonals}setRotateObject(e){this._rotateObject=e}isObjectRotated(){return this._rotateObject}isMoving(){return this._xVelocity!==0||this._yVelocity!==0}getSpeed(){return Math.hypot(this._xVelocity,this._yVelocity)}getXVelocity(){return this._xVelocity}setXVelocity(e){this._xVelocity=e}getYVelocity(){return this._yVelocity}setYVelocity(e){this._yVelocity=e}getAngle(){return this._angle}isMovementAngleAround(e,t){return Math.abs(r.evtTools.common.angleDifference(this._angle,e))<=t}setMovementAngleOffset(e){this._movementAngleOffset=e}getMovementAngleOffset(){return this._movementAngleOffset}doStepPreEvents(e){const t=37,f=38,h=39,i=40;this._leftKey||(this._leftKey=!this.shouldIgnoreDefaultControls()&&e.getGame().getInputManager().isKeyPressed(t)),this._rightKey||(this._rightKey=!this.shouldIgnoreDefaultControls()&&e.getGame().getInputManager().isKeyPressed(h)),this._downKey||(this._downKey=!this.shouldIgnoreDefaultControls()&&e.getGame().getInputManager().isKeyPressed(i)),this._upKey||(this._upKey=!this.shouldIgnoreDefaultControls()&&e.getGame().getInputManager().isKeyPressed(f));const o=this.owner.getElapsedTime();this._leftKey?this._leftKeyPressedDuration+=o:this._leftKeyPressedDuration=0,this._rightKey?this._rightKeyPressedDuration+=o:this._rightKeyPressedDuration=0,this._downKey?this._downKeyPressedDuration+=o:this._downKeyPressedDuration=0,this._upKey?this._upKeyPressedDuration+=o:this._upKeyPressedDuration=0;let s=-1;this._allowDiagonals?this._upKey&&!this._downKey?this._leftKey&&!this._rightKey?s=5:!this._leftKey&&this._rightKey?s=7:s=6:!this._upKey&&this._downKey?this._leftKey&&!this._rightKey?s=3:!this._leftKey&&this._rightKey?s=1:s=2:this._leftKey&&!this._rightKey?s=4:!this._leftKey&&this._rightKey&&(s=0):(this._upKey&&!this._downKey?s=6:!this._upKey&&this._downKey&&(s=2),this._leftKey&&!this._rightKey&&(this._upKey===this._downKey||this._upKey&&this._leftKeyPressedDuration<this._upKeyPressedDuration||this._downKey&&this._leftKeyPressedDuration<this._downKeyPressedDuration)?s=4:this._rightKey&&!this._leftKey&&(this._upKey===this._downKey||this._upKey&&this._rightKeyPressedDuration<this._upKeyPressedDuration||this._downKey&&this._rightKeyPressedDuration<this._downKeyPressedDuration)&&(s=0));const a=r.TopDownMovementRuntimeBehavior._topDownMovementHookContext;for(const n of this._topDownMovementHooks)a._setDirection(s),s=n.overrideDirection(a);a._setDirection(s);for(const n of this._topDownMovementHooks)n.beforeSpeedUpdate(a);const l=this.owner,p=this.owner.getElapsedTime()/1e3,x=this._xVelocity,P=this._yVelocity;this._wasStickUsed=!1;let _=0,y=0,g=!1,m=0;if(s!==-1?(g=!0,_=(s+this._movementAngleOffset/45)*Math.PI/4,y=s*45+this._movementAngleOffset,m=this._maxSpeed):this._stickForce!==0?(g=!0,this._allowDiagonals||(this._stickAngle=90*Math.floor((this._stickAngle+45)/90)),y=this._stickAngle+this._movementAngleOffset,_=y*Math.PI/180,m=this._maxSpeed*this._stickForce,this._wasStickUsed=!0):(this._yVelocity!==0||this._xVelocity!==0)&&(g=!0,_=Math.atan2(this._yVelocity,this._xVelocity),y=_*180/Math.PI),g){let n=Math.cos(_),u=Math.sin(_);(n===-1||n===1)&&(u=0),(u===-1||u===1)&&(n=0);const D=this._useLegacyTurnBack?c.getLegacyAcceleratedSpeed:c.getAcceleratedSpeed;let M=Math.hypot(this._xVelocity,this._yVelocity);const v=this._xVelocity*n+this._yVelocity*u;v<0&&(M=v);const k=D(M,m,this._maxSpeed,this._acceleration,this._deceleration,p);this._xVelocity=k*n,this._yVelocity=k*u}const d=this._xVelocity*this._xVelocity+this._yVelocity*this._yVelocity;if(d>this._maxSpeed*this._maxSpeed){const n=this._maxSpeed/Math.sqrt(d);this._xVelocity*=n,this._yVelocity*=n}this._angularSpeed=this._angularMaxSpeed;for(const n of this._topDownMovementHooks)n.beforePositionUpdate(a);const K=(x+this._xVelocity)/2*p,w=(P+this._yVelocity)/2*p;if(this._basisTransformation===null)l.setX(l.getX()+K),l.setY(l.getY()+w);else{const n=this._temporaryPointForTransformations;n[0]=K,n[1]=w,this._basisTransformation.toScreen(n,n),l.setX(l.getX()+n[0]),l.setY(l.getY()+n[1])}(this._xVelocity!==0||this._yVelocity!==0)&&(this._angle=y,this._rotateObject&&l.rotateTowardAngle(y+this._angleOffset,this._angularSpeed)),this._wasLeftKeyPressed=this._leftKey,this._wasRightKeyPressed=this._rightKey,this._wasUpKeyPressed=this._upKey,this._wasDownKeyPressed=this._downKey,this._dontClearInputsBetweenFrames||(this._leftKey=!1,this._rightKey=!1,this._upKey=!1,this._downKey=!1,this._stickForce=0)}static getAcceleratedSpeed(e,t,f,h,i,o){let s=e;const a=Math.max(h,i);return t<0?e<=t?s=Math.min(t,e+a*o):e<=0?s-=Math.max(-f,h*o):s=Math.max(t,e-a*o):t>0?e>=t?s=Math.max(t,e-a*o):e>=0?s=Math.min(f,e+h*o):s=Math.min(t,e+a*o):(e<0&&(s=Math.min(e+i*o,0)),e>0&&(s=Math.max(e-i*o,0))),s}static getLegacyAcceleratedSpeed(e,t,f,h,i,o){let s=e;return t<0?e<=t?s=Math.min(t,e+i*o):e<=0?s-=Math.max(-f,h*o):s=Math.max(t,e-i*o):t>0?e>=t?s=Math.max(t,e-i*o):e>=0?s=Math.min(f,e+h*o):s=Math.min(t,e+i*o):(e<0&&(s=Math.min(e+i*o,0)),e>0&&(s=Math.max(e-i*o,0))),s}simulateControl(e){e==="Left"?this._leftKey=!0:e==="Right"?this._rightKey=!0:e==="Up"?this._upKey=!0:e==="Down"&&(this._downKey=!0)}ignoreDefaultControls(e){this._ignoreDefaultControls=e}shouldIgnoreDefaultControls(){return this._ignoreDefaultControls||this._ignoreDefaultControlsAsSyncedByNetwork}simulateLeftKey(){this._leftKey=!0}simulateRightKey(){this._rightKey=!0}simulateUpKey(){this._upKey=!0}simulateDownKey(){this._downKey=!0}simulateStick(e,t){this._stickAngle=e%360,this._stickForce=Math.max(0,Math.min(1,t))}isUsingControl(e){return e==="Left"?this._leftKeyPressedDuration>0:e==="Right"?this._rightKeyPressedDuration>0:e==="Up"?this._upKeyPressedDuration>0:e==="Down"?this._downKeyPressedDuration>0:e==="Stick"?this._wasStickUsed:!1}getLastStickInputAngle(){return this._stickAngle}registerHook(e){this._topDownMovementHooks.push(e)}}r.TopDownMovementRuntimeBehavior=c,function(f){class T{constructor(){this.direction=-1}getDirection(){return this.direction}_setDirection(i){this.direction=i}}f.TopDownMovementHookContext=T,f._topDownMovementHookContext=new r.TopDownMovementRuntimeBehavior.TopDownMovementHookContext;class t{constructor(i){if(i<=0||i>=Math.PI/4)throw new RangeError("An isometry angle must be in ]0; pi/4] but was: "+i);const o=Math.asin(Math.tan(i)),s=Math.sin(o),a=Math.cos(Math.PI/4),l=a;this._screen=[[a,-l],[s*l,s*a]]}toScreen(i,o){const s=this._screen[0][0]*i[0]+this._screen[0][1]*i[1],a=this._screen[1][0]*i[0]+this._screen[1][1]*i[1];o[0]=s,o[1]=a}}f.IsometryTransformation=t}(c=r.TopDownMovementRuntimeBehavior||(r.TopDownMovementRuntimeBehavior={})),r.registerBehavior("TopDownMovementBehavior::TopDownMovementBehavior",r.TopDownMovementRuntimeBehavior)})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=topdownmovementruntimebehavior.js.map
|
package/dist/Runtime/Extensions/TopDownMovementBehavior/topdownmovementruntimebehavior.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../GDevelop/Extensions/TopDownMovementBehavior/topdownmovementruntimebehavior.ts"],
|
|
4
|
-
"sourcesContent": ["/*\nGDevelop - Top-down movement Behavior Extension\nCopyright (c) 2010-2016 Florian Rival (Florian.Rival@gmail.com)\n */\n\nnamespace gdjs {\n interface TopDownMovementNetworkSyncDataType {\n a: float;\n xv: float;\n yv: float;\n as: float;\n lk: boolean;\n rk: boolean;\n uk: boolean;\n dk: boolean;\n wsu: boolean;\n sa: float;\n sf: float;\n }\n\n export interface TopDownMovementNetworkSyncData\n extends BehaviorNetworkSyncData {\n props: TopDownMovementNetworkSyncDataType;\n }\n /**\n * Allows an object to move in 4 or 8 directions, with customizable speed, accelerations\n * and rotation.\n */\n export class TopDownMovementRuntimeBehavior extends gdjs.RuntimeBehavior {\n //Behavior configuration:\n private _allowDiagonals: boolean;\n private _acceleration: float;\n private _deceleration: float;\n private _maxSpeed: float;\n private _angularMaxSpeed: float;\n private _rotateObject: boolean;\n private _angleOffset: float;\n private _ignoreDefaultControls: boolean;\n private _movementAngleOffset: float;\n\n /** The latest angle of movement, in degrees. */\n private _angle: float = 0;\n\n //Attributes used when moving\n private _xVelocity: float = 0;\n private _yVelocity: float = 0;\n private _angularSpeed: float = 0;\n\n // Inputs\n private _leftKey: boolean = false;\n private _rightKey: boolean = false;\n private _upKey: boolean = false;\n private _downKey: boolean = false;\n private _leftKeyPressedDuration: float = 0;\n private _rightKeyPressedDuration: float = 0;\n private _upKeyPressedDuration: float = 0;\n private _downKeyPressedDuration: float = 0;\n private _wasStickUsed: boolean = false;\n private _stickAngle: float = 0;\n private _stickForce: float = 0;\n\n // This is useful when the object is synchronized by an external source\n // like in a multiplayer game, and we want to be able to predict the\n // movement of the object, even if the inputs are not updated every frame.\n _dontClearInputsBetweenFrames: boolean = false;\n // This is useful when the object is synchronized over the network,\n // object is controlled by the network and we want to ensure the current player\n // cannot control it.\n _ignoreDefaultControlsAsSyncedByNetwork: boolean = false;\n\n // This is useful for extensions that need to know\n // which keys were pressed and doesn't know the mapping\n // done by the scene events.\n private _wasLeftKeyPressed: boolean = false;\n private _wasRightKeyPressed: boolean = false;\n private _wasUpKeyPressed: boolean = false;\n private _wasDownKeyPressed: boolean = false;\n\n // @ts-ignore The setter \"setViewpoint\" is not detected as an affectation.\n private _basisTransformation: gdjs.TopDownMovementRuntimeBehavior.BasisTransformation | null;\n private _temporaryPointForTransformations: FloatPoint = [0, 0];\n\n private _topDownMovementHooks: Array<gdjs.TopDownMovementRuntimeBehavior.TopDownMovementHook> =\n [];\n\n constructor(\n instanceContainer: gdjs.RuntimeInstanceContainer,\n behaviorData,\n owner: gdjs.RuntimeObject\n ) {\n super(instanceContainer, behaviorData, owner);\n this._allowDiagonals = behaviorData.allowDiagonals;\n this._acceleration = behaviorData.acceleration;\n this._deceleration = behaviorData.deceleration;\n this._maxSpeed = behaviorData.maxSpeed;\n this._angularMaxSpeed = behaviorData.angularMaxSpeed;\n this._rotateObject = behaviorData.rotateObject;\n this._angleOffset = behaviorData.angleOffset;\n this._ignoreDefaultControls = behaviorData.ignoreDefaultControls;\n this.setViewpoint(\n behaviorData.viewpoint,\n behaviorData.customIsometryAngle\n );\n this._movementAngleOffset = behaviorData.movementAngleOffset || 0;\n }\n\n getNetworkSyncData(): TopDownMovementNetworkSyncData {\n // This method is called, so we are synchronizing this object.\n // Let's clear the inputs between frames as we control it.\n this._dontClearInputsBetweenFrames = false;\n this._ignoreDefaultControlsAsSyncedByNetwork = false;\n\n return {\n ...super.getNetworkSyncData(),\n props: {\n a: this._angle,\n xv: this._xVelocity,\n yv: this._yVelocity,\n as: this._angularSpeed,\n lk: this._wasLeftKeyPressed,\n rk: this._wasRightKeyPressed,\n uk: this._wasUpKeyPressed,\n dk: this._wasDownKeyPressed,\n wsu: this._wasStickUsed,\n sa: this._stickAngle,\n sf: this._stickForce,\n },\n };\n }\n\n updateFromNetworkSyncData(\n networkSyncData: TopDownMovementNetworkSyncData\n ): void {\n super.updateFromNetworkSyncData(networkSyncData);\n\n const behaviorSpecificProps = networkSyncData.props;\n if (behaviorSpecificProps.a !== undefined) {\n this._angle = behaviorSpecificProps.a;\n }\n if (behaviorSpecificProps.xv !== undefined) {\n this._xVelocity = behaviorSpecificProps.xv;\n }\n if (behaviorSpecificProps.yv !== undefined) {\n this._yVelocity = behaviorSpecificProps.yv;\n }\n if (behaviorSpecificProps.as !== undefined) {\n this._angularSpeed = behaviorSpecificProps.as;\n }\n if (behaviorSpecificProps.lk !== undefined) {\n this._leftKey = behaviorSpecificProps.lk;\n }\n if (behaviorSpecificProps.rk !== undefined) {\n this._rightKey = behaviorSpecificProps.rk;\n }\n if (behaviorSpecificProps.uk !== undefined) {\n this._upKey = behaviorSpecificProps.uk;\n }\n if (behaviorSpecificProps.dk !== undefined) {\n this._downKey = behaviorSpecificProps.dk;\n }\n if (behaviorSpecificProps.wsu !== undefined) {\n this._wasStickUsed = behaviorSpecificProps.wsu;\n }\n if (behaviorSpecificProps.sa !== undefined) {\n this._stickAngle = behaviorSpecificProps.sa;\n }\n if (behaviorSpecificProps.sf !== undefined) {\n this._stickForce = behaviorSpecificProps.sf;\n }\n\n // When the object is synchronized from the network, the inputs must not be cleared.\n this._dontClearInputsBetweenFrames = true;\n // And we are not using the default controls.\n this._ignoreDefaultControlsAsSyncedByNetwork = true;\n }\n\n updateFromBehaviorData(oldBehaviorData, newBehaviorData): boolean {\n if (oldBehaviorData.allowDiagonals !== newBehaviorData.allowDiagonals) {\n this._allowDiagonals = newBehaviorData.allowDiagonals;\n }\n if (oldBehaviorData.acceleration !== newBehaviorData.acceleration) {\n this._acceleration = newBehaviorData.acceleration;\n }\n if (oldBehaviorData.deceleration !== newBehaviorData.deceleration) {\n this._deceleration = newBehaviorData.deceleration;\n }\n if (oldBehaviorData.maxSpeed !== newBehaviorData.maxSpeed) {\n this._maxSpeed = newBehaviorData.maxSpeed;\n }\n if (oldBehaviorData.angularMaxSpeed !== newBehaviorData.angularMaxSpeed) {\n this._angularMaxSpeed = newBehaviorData.angularMaxSpeed;\n }\n if (oldBehaviorData.rotateObject !== newBehaviorData.rotateObject) {\n this._rotateObject = newBehaviorData.rotateObject;\n }\n if (oldBehaviorData.angleOffset !== newBehaviorData.angleOffset) {\n this._angleOffset = newBehaviorData.angleOffset;\n }\n if (\n oldBehaviorData.ignoreDefaultControls !==\n newBehaviorData.ignoreDefaultControls\n ) {\n this._ignoreDefaultControls = newBehaviorData.ignoreDefaultControls;\n }\n if (\n oldBehaviorData.platformType !== newBehaviorData.platformType ||\n oldBehaviorData.customIsometryAngle !==\n newBehaviorData.customIsometryAngle\n ) {\n this.setViewpoint(\n newBehaviorData.platformType,\n newBehaviorData.customIsometryAngle\n );\n }\n if (\n oldBehaviorData.movementAngleOffset !==\n newBehaviorData.movementAngleOffset\n ) {\n this._movementAngleOffset = newBehaviorData.movementAngleOffset;\n }\n return true;\n }\n\n setViewpoint(viewpoint: string, customIsometryAngle: float): void {\n if (viewpoint === 'PixelIsometry') {\n this._basisTransformation =\n new gdjs.TopDownMovementRuntimeBehavior.IsometryTransformation(\n Math.atan(0.5)\n );\n } else if (viewpoint === 'TrueIsometry') {\n this._basisTransformation =\n new gdjs.TopDownMovementRuntimeBehavior.IsometryTransformation(\n Math.PI / 6\n );\n } else if (viewpoint === 'CustomIsometry') {\n this._basisTransformation =\n new gdjs.TopDownMovementRuntimeBehavior.IsometryTransformation(\n (customIsometryAngle * Math.PI) / 180\n );\n } else {\n this._basisTransformation = null;\n }\n }\n\n setAcceleration(acceleration: float): void {\n this._acceleration = acceleration;\n }\n\n getAcceleration() {\n return this._acceleration;\n }\n\n setDeceleration(deceleration: float): void {\n this._deceleration = deceleration;\n }\n\n getDeceleration() {\n return this._deceleration;\n }\n\n setMaxSpeed(maxSpeed: float): void {\n this._maxSpeed = maxSpeed;\n }\n\n getMaxSpeed() {\n return this._maxSpeed;\n }\n\n setAngularMaxSpeed(angularMaxSpeed: float): void {\n this._angularMaxSpeed = angularMaxSpeed;\n }\n\n getAngularMaxSpeed() {\n return this._angularMaxSpeed;\n }\n\n setAngleOffset(angleOffset: float): void {\n this._angleOffset = angleOffset;\n }\n\n getAngleOffset() {\n return this._angleOffset;\n }\n\n allowDiagonals(allow: boolean) {\n this._allowDiagonals = allow;\n }\n\n diagonalsAllowed() {\n return this._allowDiagonals;\n }\n\n setRotateObject(allow: boolean): void {\n this._rotateObject = allow;\n }\n\n isObjectRotated(): boolean {\n return this._rotateObject;\n }\n\n isMoving(): boolean {\n return this._xVelocity !== 0 || this._yVelocity !== 0;\n }\n\n getSpeed(): float {\n return Math.sqrt(\n this._xVelocity * this._xVelocity + this._yVelocity * this._yVelocity\n );\n }\n\n getXVelocity(): float {\n return this._xVelocity;\n }\n\n setXVelocity(velocityX: float): void {\n this._xVelocity = velocityX;\n }\n\n getYVelocity(): float {\n return this._yVelocity;\n }\n\n setYVelocity(velocityY: float): void {\n this._yVelocity = velocityY;\n }\n\n getAngle(): float {\n return this._angle;\n }\n\n isMovementAngleAround(degreeAngle: float, tolerance: float) {\n return (\n Math.abs(\n gdjs.evtTools.common.angleDifference(this._angle, degreeAngle)\n ) <= tolerance\n );\n }\n\n setMovementAngleOffset(movementAngleOffset: float): void {\n this._movementAngleOffset = movementAngleOffset;\n }\n\n getMovementAngleOffset() {\n return this._movementAngleOffset;\n }\n\n doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {\n const LEFTKEY = 37;\n const UPKEY = 38;\n const RIGHTKEY = 39;\n const DOWNKEY = 40;\n\n //Get the player input:\n this._leftKey ||\n (this._leftKey =\n !this.shouldIgnoreDefaultControls() &&\n instanceContainer.getGame().getInputManager().isKeyPressed(LEFTKEY));\n this._rightKey ||\n (this._rightKey =\n !this.shouldIgnoreDefaultControls() &&\n instanceContainer.getGame().getInputManager().isKeyPressed(RIGHTKEY));\n this._downKey ||\n (this._downKey =\n !this.shouldIgnoreDefaultControls() &&\n instanceContainer.getGame().getInputManager().isKeyPressed(DOWNKEY));\n this._upKey ||\n (this._upKey =\n !this.shouldIgnoreDefaultControls() &&\n instanceContainer.getGame().getInputManager().isKeyPressed(UPKEY));\n\n const elapsedTime = this.owner.getElapsedTime();\n\n if (!this._leftKey) {\n this._leftKeyPressedDuration = 0;\n } else {\n this._leftKeyPressedDuration += elapsedTime;\n }\n if (!this._rightKey) {\n this._rightKeyPressedDuration = 0;\n } else {\n this._rightKeyPressedDuration += elapsedTime;\n }\n if (!this._downKey) {\n this._downKeyPressedDuration = 0;\n } else {\n this._downKeyPressedDuration += elapsedTime;\n }\n if (!this._upKey) {\n this._upKeyPressedDuration = 0;\n } else {\n this._upKeyPressedDuration += elapsedTime;\n }\n\n let direction = -1;\n if (!this._allowDiagonals) {\n if (this._upKey && !this._downKey) {\n direction = 6;\n } else if (!this._upKey && this._downKey) {\n direction = 2;\n }\n // when 2 keys are pressed for diagonals the most recently pressed win\n if (\n this._leftKey &&\n !this._rightKey &&\n (this._upKey === this._downKey ||\n (this._upKey &&\n this._leftKeyPressedDuration < this._upKeyPressedDuration) ||\n (this._downKey &&\n this._leftKeyPressedDuration < this._downKeyPressedDuration))\n ) {\n direction = 4;\n } else if (\n this._rightKey &&\n !this._leftKey &&\n (this._upKey === this._downKey ||\n (this._upKey &&\n this._rightKeyPressedDuration < this._upKeyPressedDuration) ||\n (this._downKey &&\n this._rightKeyPressedDuration < this._downKeyPressedDuration))\n ) {\n direction = 0;\n }\n } else {\n if (this._upKey && !this._downKey) {\n if (this._leftKey && !this._rightKey) {\n direction = 5;\n } else if (!this._leftKey && this._rightKey) {\n direction = 7;\n } else {\n direction = 6;\n }\n } else if (!this._upKey && this._downKey) {\n if (this._leftKey && !this._rightKey) {\n direction = 3;\n } else if (!this._leftKey && this._rightKey) {\n direction = 1;\n } else {\n direction = 2;\n }\n } else {\n if (this._leftKey && !this._rightKey) {\n direction = 4;\n } else if (!this._leftKey && this._rightKey) {\n direction = 0;\n }\n }\n }\n\n const hookContext =\n gdjs.TopDownMovementRuntimeBehavior._topDownMovementHookContext;\n for (const topDownMovementHook of this._topDownMovementHooks) {\n hookContext._setDirection(direction);\n direction = topDownMovementHook.overrideDirection(hookContext);\n }\n hookContext._setDirection(direction);\n for (const topDownMovementHook of this._topDownMovementHooks) {\n topDownMovementHook.beforeSpeedUpdate(hookContext);\n }\n\n const object = this.owner;\n const timeDelta = this.owner.getElapsedTime() / 1000;\n const previousVelocityX = this._xVelocity;\n const previousVelocityY = this._yVelocity;\n this._wasStickUsed = false;\n\n // These 4 values are not actually used.\n // JavaScript doesn't allow to declare\n // variables without assigning them a value.\n let directionInRad = 0;\n let directionInDeg = 0;\n let cos = 1;\n let sin = 0;\n\n // Update the speed of the object:\n if (direction !== -1) {\n directionInRad =\n ((direction + this._movementAngleOffset / 45) * Math.PI) / 4.0;\n directionInDeg = direction * 45 + this._movementAngleOffset;\n // This makes the trigo resilient to rounding errors on directionInRad.\n cos = Math.cos(directionInRad);\n sin = Math.sin(directionInRad);\n if (cos === -1 || cos === 1) {\n sin = 0;\n }\n if (sin === -1 || sin === 1) {\n cos = 0;\n }\n this._xVelocity += this._acceleration * timeDelta * cos;\n this._yVelocity += this._acceleration * timeDelta * sin;\n } else if (this._stickForce !== 0) {\n if (!this._allowDiagonals) {\n this._stickAngle = 90 * Math.floor((this._stickAngle + 45) / 90);\n }\n directionInDeg = this._stickAngle + this._movementAngleOffset;\n directionInRad = (directionInDeg * Math.PI) / 180;\n const norm = this._acceleration * timeDelta * this._stickForce;\n // This makes the trigo resilient to rounding errors on directionInRad.\n cos = Math.cos(directionInRad);\n sin = Math.sin(directionInRad);\n if (cos === -1 || cos === 1) {\n sin = 0;\n }\n if (sin === -1 || sin === 1) {\n cos = 0;\n }\n this._xVelocity += norm * cos;\n this._yVelocity += norm * sin;\n\n this._wasStickUsed = true;\n this._stickForce = 0;\n } else if (this._yVelocity !== 0 || this._xVelocity !== 0) {\n directionInRad = Math.atan2(this._yVelocity, this._xVelocity);\n directionInDeg = (directionInRad * 180.0) / Math.PI;\n const xVelocityWasPositive = this._xVelocity >= 0;\n const yVelocityWasPositive = this._yVelocity >= 0;\n // This makes the trigo resilient to rounding errors on directionInRad.\n cos = Math.cos(directionInRad);\n sin = Math.sin(directionInRad);\n if (cos === -1 || cos === 1) {\n sin = 0;\n }\n if (sin === -1 || sin === 1) {\n cos = 0;\n }\n this._xVelocity -= this._deceleration * timeDelta * cos;\n this._yVelocity -= this._deceleration * timeDelta * sin;\n if (this._xVelocity > 0 !== xVelocityWasPositive) {\n this._xVelocity = 0;\n }\n if (this._yVelocity > 0 !== yVelocityWasPositive) {\n this._yVelocity = 0;\n }\n }\n const squaredSpeed =\n this._xVelocity * this._xVelocity + this._yVelocity * this._yVelocity;\n if (squaredSpeed > this._maxSpeed * this._maxSpeed) {\n this._xVelocity = this._maxSpeed * cos;\n this._yVelocity = this._maxSpeed * sin;\n }\n\n // No acceleration for angular speed for now.\n this._angularSpeed = this._angularMaxSpeed;\n\n for (const topDownMovementHook of this._topDownMovementHooks) {\n topDownMovementHook.beforePositionUpdate(hookContext);\n }\n\n // Position object.\n // This is a Verlet integration considering the acceleration as constant.\n // If you expand deltaX or deltaY, it gives, thanks to the usage of both\n // the old and the new velocity:\n // \"velocity * timeDelta + acceleration * timeDelta^2 / 2\".\n //\n // The acceleration is not actually always constant, particularly with a gamepad,\n // but the error is multiplied by timDelta^3. So, it shouldn't matter much.\n const deltaX = ((previousVelocityX + this._xVelocity) / 2) * timeDelta;\n const deltaY = ((previousVelocityY + this._yVelocity) / 2) * timeDelta;\n if (this._basisTransformation === null) {\n // Top-down viewpoint\n object.setX(object.getX() + deltaX);\n object.setY(object.getY() + deltaY);\n } else {\n // Isometry viewpoint\n const point = this._temporaryPointForTransformations;\n point[0] = deltaX;\n point[1] = deltaY;\n this._basisTransformation.toScreen(point, point);\n object.setX(object.getX() + point[0]);\n object.setY(object.getY() + point[1]);\n }\n\n // Also update angle if needed.\n if (this._xVelocity !== 0 || this._yVelocity !== 0) {\n this._angle = directionInDeg;\n if (this._rotateObject) {\n object.rotateTowardAngle(\n directionInDeg + this._angleOffset,\n this._angularSpeed\n );\n }\n }\n\n this._wasLeftKeyPressed = this._leftKey;\n this._wasRightKeyPressed = this._rightKey;\n this._wasUpKeyPressed = this._upKey;\n this._wasDownKeyPressed = this._downKey;\n if (!this._dontClearInputsBetweenFrames) {\n this._leftKey = false;\n this._rightKey = false;\n this._upKey = false;\n this._downKey = false;\n }\n }\n\n simulateControl(input: string) {\n if (input === 'Left') {\n this._leftKey = true;\n } else if (input === 'Right') {\n this._rightKey = true;\n } else if (input === 'Up') {\n this._upKey = true;\n } else if (input === 'Down') {\n this._downKey = true;\n }\n }\n\n ignoreDefaultControls(ignore: boolean) {\n this._ignoreDefaultControls = ignore;\n }\n\n shouldIgnoreDefaultControls() {\n return (\n this._ignoreDefaultControls ||\n this._ignoreDefaultControlsAsSyncedByNetwork\n );\n }\n\n simulateLeftKey() {\n this._leftKey = true;\n }\n\n simulateRightKey() {\n this._rightKey = true;\n }\n\n simulateUpKey() {\n this._upKey = true;\n }\n\n simulateDownKey() {\n this._downKey = true;\n }\n\n simulateStick(stickAngle: float, stickForce: float) {\n this._stickAngle = stickAngle % 360;\n this._stickForce = Math.max(0, Math.min(1, stickForce));\n }\n\n /**.\n * @param input The control to be tested [Left,Right,Up,Down,Stick].\n * @returns true if the key was used since the last `doStepPreEvents` call.\n */\n isUsingControl(input: string): boolean {\n if (input === 'Left') {\n return this._leftKeyPressedDuration > 0;\n }\n if (input === 'Right') {\n return this._rightKeyPressedDuration > 0;\n }\n if (input === 'Up') {\n return this._upKeyPressedDuration > 0;\n }\n if (input === 'Down') {\n return this._downKeyPressedDuration > 0;\n }\n if (input === 'Stick') {\n return this._wasStickUsed;\n }\n return false;\n }\n\n getLastStickInputAngle() {\n return this._stickAngle;\n }\n\n /**\n * A hook must typically be registered by a behavior that requires this one\n * in its onCreate function.\n * The hook must stay forever to avoid side effects like a hooks order\n * change. To handle deactivated behavior, the hook can check that its\n * behavior is activated before doing anything.\n */\n registerHook(\n hook: gdjs.TopDownMovementRuntimeBehavior.TopDownMovementHook\n ) {\n this._topDownMovementHooks.push(hook);\n }\n }\n\n export namespace TopDownMovementRuntimeBehavior {\n export class TopDownMovementHookContext {\n private direction: integer = -1;\n\n /**\n * @returns The movement direction from 0 for left to 7 for up-left and\n * -1 for no direction.\n */\n getDirection(): integer {\n return this.direction;\n }\n\n /**\n * This method won't change the direction used by the top-down movement\n * behavior.\n */\n _setDirection(direction: integer): void {\n this.direction = direction;\n }\n }\n\n // This should be a static attribute but it's not possible because of\n // declaration order.\n export const _topDownMovementHookContext =\n new gdjs.TopDownMovementRuntimeBehavior.TopDownMovementHookContext();\n\n /**\n * Allow extensions relying on the top-down movement to customize its\n * behavior a bit.\n */\n export interface TopDownMovementHook {\n /**\n * Return the direction to use instead of the direction given in\n * parameter.\n */\n overrideDirection(hookContext: TopDownMovementHookContext): integer;\n /**\n * Called before the acceleration and new direction is applied to the\n * velocity.\n */\n beforeSpeedUpdate(hookContext: TopDownMovementHookContext): void;\n /**\n * Called before the velocity is applied to the object position and\n * angle.\n */\n beforePositionUpdate(hookContext: TopDownMovementHookContext): void;\n }\n\n export interface BasisTransformation {\n toScreen(worldPoint: FloatPoint, screenPoint: FloatPoint): void;\n }\n\n export class IsometryTransformation\n implements gdjs.TopDownMovementRuntimeBehavior.BasisTransformation\n {\n private _screen: float[][];\n\n /**\n * @param angle between the x axis and the projected isometric x axis.\n * @throws if the angle is not in ]0; pi/4[. Note that 0 is a front viewpoint and pi/4 a top-down viewpoint.\n */\n constructor(angle: float) {\n if (angle <= 0 || angle >= Math.PI / 4)\n throw new RangeError(\n 'An isometry angle must be in ]0; pi/4] but was: ' + angle\n );\n\n const alpha = Math.asin(Math.tan(angle));\n const sinA = Math.sin(alpha);\n const cosB = Math.cos(Math.PI / 4);\n const sinB = cosB;\n // https://en.wikipedia.org/wiki/Isometric_projection\n //\n // / 1 0 0 \\ / cosB 0 -sinB \\ / 1 0 0 \\\n // | 0 cosA sinA | | 0 1 0 | | 0 0 -1 |\n // \\ 0 -sinA cosA / \\ sinB 0 cosB / \\ 0 1 0 /\n this._screen = [\n [cosB, -sinB],\n [sinA * sinB, sinA * cosB],\n ];\n }\n\n toScreen(worldPoint: FloatPoint, screenPoint: FloatPoint): void {\n const x =\n this._screen[0][0] * worldPoint[0] +\n this._screen[0][1] * worldPoint[1];\n const y =\n this._screen[1][0] * worldPoint[0] +\n this._screen[1][1] * worldPoint[1];\n screenPoint[0] = x;\n screenPoint[1] = y;\n }\n }\n }\n\n gdjs.registerBehavior(\n 'TopDownMovementBehavior::TopDownMovementBehavior',\n gdjs.TopDownMovementRuntimeBehavior\n );\n}\n"],
|
|
5
|
-
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CAuBS,eAA6C,GAAK,eAAgB,
|
|
4
|
+
"sourcesContent": ["/*\nGDevelop - Top-down movement Behavior Extension\nCopyright (c) 2010-2016 Florian Rival (Florian.Rival@gmail.com)\n */\n\nnamespace gdjs {\n interface TopDownMovementNetworkSyncDataType {\n a: float;\n xv: float;\n yv: float;\n as: float;\n lk: boolean;\n rk: boolean;\n uk: boolean;\n dk: boolean;\n wsu: boolean;\n sa: float;\n sf: float;\n }\n\n export interface TopDownMovementNetworkSyncData\n extends BehaviorNetworkSyncData {\n props: TopDownMovementNetworkSyncDataType;\n }\n /**\n * Allows an object to move in 4 or 8 directions, with customizable speed, accelerations\n * and rotation.\n */\n export class TopDownMovementRuntimeBehavior extends gdjs.RuntimeBehavior {\n //Behavior configuration:\n private _allowDiagonals: boolean;\n private _acceleration: float;\n private _deceleration: float;\n private _maxSpeed: float;\n private _angularMaxSpeed: float;\n private _rotateObject: boolean;\n private _angleOffset: float;\n private _ignoreDefaultControls: boolean;\n private _movementAngleOffset: float;\n private _useLegacyTurnBack: boolean;\n\n /** The latest angle of movement, in degrees. */\n private _angle: float = 0;\n\n //Attributes used when moving\n private _xVelocity: float = 0;\n private _yVelocity: float = 0;\n private _angularSpeed: float = 0;\n\n // Inputs\n private _leftKey: boolean = false;\n private _rightKey: boolean = false;\n private _upKey: boolean = false;\n private _downKey: boolean = false;\n private _leftKeyPressedDuration: float = 0;\n private _rightKeyPressedDuration: float = 0;\n private _upKeyPressedDuration: float = 0;\n private _downKeyPressedDuration: float = 0;\n private _wasStickUsed: boolean = false;\n private _stickAngle: float = 0;\n private _stickForce: float = 0;\n\n // This is useful when the object is synchronized by an external source\n // like in a multiplayer game, and we want to be able to predict the\n // movement of the object, even if the inputs are not updated every frame.\n _dontClearInputsBetweenFrames: boolean = false;\n // This is useful when the object is synchronized over the network,\n // object is controlled by the network and we want to ensure the current player\n // cannot control it.\n _ignoreDefaultControlsAsSyncedByNetwork: boolean = false;\n\n // This is useful for extensions that need to know\n // which keys were pressed and doesn't know the mapping\n // done by the scene events.\n private _wasLeftKeyPressed: boolean = false;\n private _wasRightKeyPressed: boolean = false;\n private _wasUpKeyPressed: boolean = false;\n private _wasDownKeyPressed: boolean = false;\n\n // @ts-ignore The setter \"setViewpoint\" is not detected as an affectation.\n private _basisTransformation: gdjs.TopDownMovementRuntimeBehavior.BasisTransformation | null;\n private _temporaryPointForTransformations: FloatPoint = [0, 0];\n\n private _topDownMovementHooks: Array<gdjs.TopDownMovementRuntimeBehavior.TopDownMovementHook> =\n [];\n\n constructor(\n instanceContainer: gdjs.RuntimeInstanceContainer,\n behaviorData,\n owner: gdjs.RuntimeObject\n ) {\n super(instanceContainer, behaviorData, owner);\n this._allowDiagonals = behaviorData.allowDiagonals;\n this._acceleration = behaviorData.acceleration;\n this._deceleration = behaviorData.deceleration;\n this._maxSpeed = behaviorData.maxSpeed;\n this._angularMaxSpeed = behaviorData.angularMaxSpeed;\n this._rotateObject = behaviorData.rotateObject;\n this._angleOffset = behaviorData.angleOffset;\n this._ignoreDefaultControls = behaviorData.ignoreDefaultControls;\n this.setViewpoint(\n behaviorData.viewpoint,\n behaviorData.customIsometryAngle\n );\n this._movementAngleOffset = behaviorData.movementAngleOffset || 0;\n this._useLegacyTurnBack =\n behaviorData.useLegacyTurnBack === undefined\n ? true\n : behaviorData.useLegacyTurnBack;\n }\n\n getNetworkSyncData(): TopDownMovementNetworkSyncData {\n // This method is called, so we are synchronizing this object.\n // Let's clear the inputs between frames as we control it.\n this._dontClearInputsBetweenFrames = false;\n this._ignoreDefaultControlsAsSyncedByNetwork = false;\n\n return {\n ...super.getNetworkSyncData(),\n props: {\n a: this._angle,\n xv: this._xVelocity,\n yv: this._yVelocity,\n as: this._angularSpeed,\n lk: this._wasLeftKeyPressed,\n rk: this._wasRightKeyPressed,\n uk: this._wasUpKeyPressed,\n dk: this._wasDownKeyPressed,\n wsu: this._wasStickUsed,\n sa: this._stickAngle,\n sf: this._stickForce,\n },\n };\n }\n\n updateFromNetworkSyncData(\n networkSyncData: TopDownMovementNetworkSyncData\n ): void {\n super.updateFromNetworkSyncData(networkSyncData);\n\n const behaviorSpecificProps = networkSyncData.props;\n if (behaviorSpecificProps.a !== undefined) {\n this._angle = behaviorSpecificProps.a;\n }\n if (behaviorSpecificProps.xv !== undefined) {\n this._xVelocity = behaviorSpecificProps.xv;\n }\n if (behaviorSpecificProps.yv !== undefined) {\n this._yVelocity = behaviorSpecificProps.yv;\n }\n if (behaviorSpecificProps.as !== undefined) {\n this._angularSpeed = behaviorSpecificProps.as;\n }\n if (behaviorSpecificProps.lk !== undefined) {\n this._leftKey = behaviorSpecificProps.lk;\n }\n if (behaviorSpecificProps.rk !== undefined) {\n this._rightKey = behaviorSpecificProps.rk;\n }\n if (behaviorSpecificProps.uk !== undefined) {\n this._upKey = behaviorSpecificProps.uk;\n }\n if (behaviorSpecificProps.dk !== undefined) {\n this._downKey = behaviorSpecificProps.dk;\n }\n if (behaviorSpecificProps.wsu !== undefined) {\n this._wasStickUsed = behaviorSpecificProps.wsu;\n }\n if (behaviorSpecificProps.sa !== undefined) {\n this._stickAngle = behaviorSpecificProps.sa;\n }\n if (behaviorSpecificProps.sf !== undefined) {\n this._stickForce = behaviorSpecificProps.sf;\n }\n\n // When the object is synchronized from the network, the inputs must not be cleared.\n this._dontClearInputsBetweenFrames = true;\n // And we are not using the default controls.\n this._ignoreDefaultControlsAsSyncedByNetwork = true;\n }\n\n updateFromBehaviorData(oldBehaviorData, newBehaviorData): boolean {\n if (oldBehaviorData.allowDiagonals !== newBehaviorData.allowDiagonals) {\n this._allowDiagonals = newBehaviorData.allowDiagonals;\n }\n if (oldBehaviorData.acceleration !== newBehaviorData.acceleration) {\n this._acceleration = newBehaviorData.acceleration;\n }\n if (oldBehaviorData.deceleration !== newBehaviorData.deceleration) {\n this._deceleration = newBehaviorData.deceleration;\n }\n if (oldBehaviorData.maxSpeed !== newBehaviorData.maxSpeed) {\n this._maxSpeed = newBehaviorData.maxSpeed;\n }\n if (oldBehaviorData.angularMaxSpeed !== newBehaviorData.angularMaxSpeed) {\n this._angularMaxSpeed = newBehaviorData.angularMaxSpeed;\n }\n if (oldBehaviorData.rotateObject !== newBehaviorData.rotateObject) {\n this._rotateObject = newBehaviorData.rotateObject;\n }\n if (oldBehaviorData.angleOffset !== newBehaviorData.angleOffset) {\n this._angleOffset = newBehaviorData.angleOffset;\n }\n if (\n oldBehaviorData.ignoreDefaultControls !==\n newBehaviorData.ignoreDefaultControls\n ) {\n this._ignoreDefaultControls = newBehaviorData.ignoreDefaultControls;\n }\n if (\n oldBehaviorData.platformType !== newBehaviorData.platformType ||\n oldBehaviorData.customIsometryAngle !==\n newBehaviorData.customIsometryAngle\n ) {\n this.setViewpoint(\n newBehaviorData.platformType,\n newBehaviorData.customIsometryAngle\n );\n }\n if (\n oldBehaviorData.movementAngleOffset !==\n newBehaviorData.movementAngleOffset\n ) {\n this._movementAngleOffset = newBehaviorData.movementAngleOffset;\n }\n return true;\n }\n\n setViewpoint(viewpoint: string, customIsometryAngle: float): void {\n if (viewpoint === 'PixelIsometry') {\n this._basisTransformation =\n new gdjs.TopDownMovementRuntimeBehavior.IsometryTransformation(\n Math.atan(0.5)\n );\n } else if (viewpoint === 'TrueIsometry') {\n this._basisTransformation =\n new gdjs.TopDownMovementRuntimeBehavior.IsometryTransformation(\n Math.PI / 6\n );\n } else if (viewpoint === 'CustomIsometry') {\n this._basisTransformation =\n new gdjs.TopDownMovementRuntimeBehavior.IsometryTransformation(\n (customIsometryAngle * Math.PI) / 180\n );\n } else {\n this._basisTransformation = null;\n }\n }\n\n setAcceleration(acceleration: float): void {\n this._acceleration = acceleration;\n }\n\n getAcceleration() {\n return this._acceleration;\n }\n\n setDeceleration(deceleration: float): void {\n this._deceleration = deceleration;\n }\n\n getDeceleration() {\n return this._deceleration;\n }\n\n setMaxSpeed(maxSpeed: float): void {\n this._maxSpeed = maxSpeed;\n }\n\n getMaxSpeed() {\n return this._maxSpeed;\n }\n\n setAngularMaxSpeed(angularMaxSpeed: float): void {\n this._angularMaxSpeed = angularMaxSpeed;\n }\n\n getAngularMaxSpeed() {\n return this._angularMaxSpeed;\n }\n\n setAngleOffset(angleOffset: float): void {\n this._angleOffset = angleOffset;\n }\n\n getAngleOffset() {\n return this._angleOffset;\n }\n\n allowDiagonals(allow: boolean) {\n this._allowDiagonals = allow;\n }\n\n diagonalsAllowed() {\n return this._allowDiagonals;\n }\n\n setRotateObject(allow: boolean): void {\n this._rotateObject = allow;\n }\n\n isObjectRotated(): boolean {\n return this._rotateObject;\n }\n\n isMoving(): boolean {\n return this._xVelocity !== 0 || this._yVelocity !== 0;\n }\n\n getSpeed(): float {\n return Math.hypot(this._xVelocity, this._yVelocity);\n }\n\n getXVelocity(): float {\n return this._xVelocity;\n }\n\n setXVelocity(velocityX: float): void {\n this._xVelocity = velocityX;\n }\n\n getYVelocity(): float {\n return this._yVelocity;\n }\n\n setYVelocity(velocityY: float): void {\n this._yVelocity = velocityY;\n }\n\n getAngle(): float {\n return this._angle;\n }\n\n isMovementAngleAround(degreeAngle: float, tolerance: float) {\n return (\n Math.abs(\n gdjs.evtTools.common.angleDifference(this._angle, degreeAngle)\n ) <= tolerance\n );\n }\n\n setMovementAngleOffset(movementAngleOffset: float): void {\n this._movementAngleOffset = movementAngleOffset;\n }\n\n getMovementAngleOffset() {\n return this._movementAngleOffset;\n }\n\n doStepPreEvents(instanceContainer: gdjs.RuntimeInstanceContainer) {\n const LEFTKEY = 37;\n const UPKEY = 38;\n const RIGHTKEY = 39;\n const DOWNKEY = 40;\n\n //Get the player input:\n this._leftKey ||\n (this._leftKey =\n !this.shouldIgnoreDefaultControls() &&\n instanceContainer.getGame().getInputManager().isKeyPressed(LEFTKEY));\n this._rightKey ||\n (this._rightKey =\n !this.shouldIgnoreDefaultControls() &&\n instanceContainer.getGame().getInputManager().isKeyPressed(RIGHTKEY));\n this._downKey ||\n (this._downKey =\n !this.shouldIgnoreDefaultControls() &&\n instanceContainer.getGame().getInputManager().isKeyPressed(DOWNKEY));\n this._upKey ||\n (this._upKey =\n !this.shouldIgnoreDefaultControls() &&\n instanceContainer.getGame().getInputManager().isKeyPressed(UPKEY));\n\n const elapsedTime = this.owner.getElapsedTime();\n\n if (!this._leftKey) {\n this._leftKeyPressedDuration = 0;\n } else {\n this._leftKeyPressedDuration += elapsedTime;\n }\n if (!this._rightKey) {\n this._rightKeyPressedDuration = 0;\n } else {\n this._rightKeyPressedDuration += elapsedTime;\n }\n if (!this._downKey) {\n this._downKeyPressedDuration = 0;\n } else {\n this._downKeyPressedDuration += elapsedTime;\n }\n if (!this._upKey) {\n this._upKeyPressedDuration = 0;\n } else {\n this._upKeyPressedDuration += elapsedTime;\n }\n\n let direction = -1;\n if (!this._allowDiagonals) {\n if (this._upKey && !this._downKey) {\n direction = 6;\n } else if (!this._upKey && this._downKey) {\n direction = 2;\n }\n // when 2 keys are pressed for diagonals the most recently pressed win\n if (\n this._leftKey &&\n !this._rightKey &&\n (this._upKey === this._downKey ||\n (this._upKey &&\n this._leftKeyPressedDuration < this._upKeyPressedDuration) ||\n (this._downKey &&\n this._leftKeyPressedDuration < this._downKeyPressedDuration))\n ) {\n direction = 4;\n } else if (\n this._rightKey &&\n !this._leftKey &&\n (this._upKey === this._downKey ||\n (this._upKey &&\n this._rightKeyPressedDuration < this._upKeyPressedDuration) ||\n (this._downKey &&\n this._rightKeyPressedDuration < this._downKeyPressedDuration))\n ) {\n direction = 0;\n }\n } else {\n if (this._upKey && !this._downKey) {\n if (this._leftKey && !this._rightKey) {\n direction = 5;\n } else if (!this._leftKey && this._rightKey) {\n direction = 7;\n } else {\n direction = 6;\n }\n } else if (!this._upKey && this._downKey) {\n if (this._leftKey && !this._rightKey) {\n direction = 3;\n } else if (!this._leftKey && this._rightKey) {\n direction = 1;\n } else {\n direction = 2;\n }\n } else {\n if (this._leftKey && !this._rightKey) {\n direction = 4;\n } else if (!this._leftKey && this._rightKey) {\n direction = 0;\n }\n }\n }\n\n const hookContext =\n gdjs.TopDownMovementRuntimeBehavior._topDownMovementHookContext;\n for (const topDownMovementHook of this._topDownMovementHooks) {\n hookContext._setDirection(direction);\n direction = topDownMovementHook.overrideDirection(hookContext);\n }\n hookContext._setDirection(direction);\n for (const topDownMovementHook of this._topDownMovementHooks) {\n topDownMovementHook.beforeSpeedUpdate(hookContext);\n }\n\n const object = this.owner;\n const timeDelta = this.owner.getElapsedTime() / 1000;\n const previousVelocityX = this._xVelocity;\n const previousVelocityY = this._yVelocity;\n this._wasStickUsed = false;\n\n // These 4 values are not actually used.\n // JavaScript doesn't allow to declare\n // variables without assigning them a value.\n let directionInRad = 0;\n let directionInDeg = 0;\n\n let isMoving = false;\n let targetedSpeed = 0;\n // Update the speed of the object:\n if (direction !== -1) {\n isMoving = true;\n directionInRad =\n ((direction + this._movementAngleOffset / 45) * Math.PI) / 4.0;\n directionInDeg = direction * 45 + this._movementAngleOffset;\n targetedSpeed = this._maxSpeed;\n } else if (this._stickForce !== 0) {\n isMoving = true;\n if (!this._allowDiagonals) {\n this._stickAngle = 90 * Math.floor((this._stickAngle + 45) / 90);\n }\n directionInDeg = this._stickAngle + this._movementAngleOffset;\n directionInRad = (directionInDeg * Math.PI) / 180;\n targetedSpeed = this._maxSpeed * this._stickForce;\n\n this._wasStickUsed = true;\n } else if (this._yVelocity !== 0 || this._xVelocity !== 0) {\n isMoving = true;\n directionInRad = Math.atan2(this._yVelocity, this._xVelocity);\n directionInDeg = (directionInRad * 180.0) / Math.PI;\n }\n if (isMoving) {\n // This makes the trigo resilient to rounding errors on directionInRad.\n let cos = Math.cos(directionInRad);\n let sin = Math.sin(directionInRad);\n if (cos === -1 || cos === 1) {\n sin = 0;\n }\n if (sin === -1 || sin === 1) {\n cos = 0;\n }\n\n const getAcceleratedSpeed = this._useLegacyTurnBack\n ? TopDownMovementRuntimeBehavior.getLegacyAcceleratedSpeed\n : TopDownMovementRuntimeBehavior.getAcceleratedSpeed;\n\n let currentSpeed = Math.hypot(this._xVelocity, this._yVelocity);\n const dotProduct = this._xVelocity * cos + this._yVelocity * sin;\n if (dotProduct < 0) {\n // The object is turning back.\n // Keep the negative velocity projected on the new direction.\n currentSpeed = dotProduct;\n }\n const speed = getAcceleratedSpeed(\n currentSpeed,\n targetedSpeed,\n this._maxSpeed,\n this._acceleration,\n this._deceleration,\n timeDelta\n );\n this._xVelocity = speed * cos;\n this._yVelocity = speed * sin;\n }\n\n const squaredSpeed =\n this._xVelocity * this._xVelocity + this._yVelocity * this._yVelocity;\n if (squaredSpeed > this._maxSpeed * this._maxSpeed) {\n const ratio = this._maxSpeed / Math.sqrt(squaredSpeed);\n this._xVelocity *= ratio;\n this._yVelocity *= ratio;\n }\n\n // No acceleration for angular speed for now.\n this._angularSpeed = this._angularMaxSpeed;\n\n for (const topDownMovementHook of this._topDownMovementHooks) {\n topDownMovementHook.beforePositionUpdate(hookContext);\n }\n\n // Position object.\n // This is a Verlet integration considering the acceleration as constant.\n // If you expand deltaX or deltaY, it gives, thanks to the usage of both\n // the old and the new velocity:\n // \"velocity * timeDelta + acceleration * timeDelta^2 / 2\".\n //\n // The acceleration is not actually always constant, particularly with a gamepad,\n // but the error is multiplied by timDelta^3. So, it shouldn't matter much.\n const deltaX = ((previousVelocityX + this._xVelocity) / 2) * timeDelta;\n const deltaY = ((previousVelocityY + this._yVelocity) / 2) * timeDelta;\n if (this._basisTransformation === null) {\n // Top-down viewpoint\n object.setX(object.getX() + deltaX);\n object.setY(object.getY() + deltaY);\n } else {\n // Isometry viewpoint\n const point = this._temporaryPointForTransformations;\n point[0] = deltaX;\n point[1] = deltaY;\n this._basisTransformation.toScreen(point, point);\n object.setX(object.getX() + point[0]);\n object.setY(object.getY() + point[1]);\n }\n\n // Also update angle if needed.\n if (this._xVelocity !== 0 || this._yVelocity !== 0) {\n this._angle = directionInDeg;\n if (this._rotateObject) {\n object.rotateTowardAngle(\n directionInDeg + this._angleOffset,\n this._angularSpeed\n );\n }\n }\n\n this._wasLeftKeyPressed = this._leftKey;\n this._wasRightKeyPressed = this._rightKey;\n this._wasUpKeyPressed = this._upKey;\n this._wasDownKeyPressed = this._downKey;\n if (!this._dontClearInputsBetweenFrames) {\n this._leftKey = false;\n this._rightKey = false;\n this._upKey = false;\n this._downKey = false;\n this._stickForce = 0;\n }\n }\n\n private static getAcceleratedSpeed(\n currentSpeed: float,\n targetedSpeed: float,\n speedMax: float,\n acceleration: float,\n deceleration: float,\n timeDelta: float\n ): float {\n let newSpeed = currentSpeed;\n const turningBackAcceleration = Math.max(acceleration, deceleration);\n if (targetedSpeed < 0) {\n if (currentSpeed <= targetedSpeed) {\n // Reduce the speed to match the stick force.\n newSpeed = Math.min(\n targetedSpeed,\n currentSpeed + turningBackAcceleration * timeDelta\n );\n } else if (currentSpeed <= 0) {\n // Accelerate\n newSpeed -= Math.max(-speedMax, acceleration * timeDelta);\n } else {\n // Turn back at least as fast as it would stop.\n newSpeed = Math.max(\n targetedSpeed,\n currentSpeed - turningBackAcceleration * timeDelta\n );\n }\n } else if (targetedSpeed > 0) {\n if (currentSpeed >= targetedSpeed) {\n // Reduce the speed to match the stick force.\n newSpeed = Math.max(\n targetedSpeed,\n currentSpeed - turningBackAcceleration * timeDelta\n );\n } else if (currentSpeed >= 0) {\n // Accelerate\n newSpeed = Math.min(\n speedMax,\n currentSpeed + acceleration * timeDelta\n );\n } else {\n // Turn back at least as fast as it would stop.\n newSpeed = Math.min(\n targetedSpeed,\n currentSpeed + turningBackAcceleration * timeDelta\n );\n }\n } else {\n // Decelerate and stop.\n if (currentSpeed < 0) {\n newSpeed = Math.min(currentSpeed + deceleration * timeDelta, 0);\n }\n if (currentSpeed > 0) {\n newSpeed = Math.max(currentSpeed - deceleration * timeDelta, 0);\n }\n }\n return newSpeed;\n }\n\n private static getLegacyAcceleratedSpeed(\n currentSpeed: float,\n targetedSpeed: float,\n speedMax: float,\n acceleration: float,\n deceleration: float,\n timeDelta: float\n ): float {\n let newSpeed = currentSpeed;\n if (targetedSpeed < 0) {\n if (currentSpeed <= targetedSpeed) {\n // Reduce the speed to match the stick force.\n newSpeed = Math.min(\n targetedSpeed,\n currentSpeed + deceleration * timeDelta\n );\n } else if (currentSpeed <= 0) {\n // Accelerate\n newSpeed -= Math.max(-speedMax, acceleration * timeDelta);\n } else {\n newSpeed = Math.max(\n targetedSpeed,\n currentSpeed - deceleration * timeDelta\n );\n }\n } else if (targetedSpeed > 0) {\n if (currentSpeed >= targetedSpeed) {\n // Reduce the speed to match the stick force.\n newSpeed = Math.max(\n targetedSpeed,\n currentSpeed - deceleration * timeDelta\n );\n } else if (currentSpeed >= 0) {\n // Accelerate\n newSpeed = Math.min(\n speedMax,\n currentSpeed + acceleration * timeDelta\n );\n } else {\n newSpeed = Math.min(\n targetedSpeed,\n currentSpeed + deceleration * timeDelta\n );\n }\n } else {\n // Decelerate and stop.\n if (currentSpeed < 0) {\n newSpeed = Math.min(currentSpeed + deceleration * timeDelta, 0);\n }\n if (currentSpeed > 0) {\n newSpeed = Math.max(currentSpeed - deceleration * timeDelta, 0);\n }\n }\n return newSpeed;\n }\n\n simulateControl(input: string) {\n if (input === 'Left') {\n this._leftKey = true;\n } else if (input === 'Right') {\n this._rightKey = true;\n } else if (input === 'Up') {\n this._upKey = true;\n } else if (input === 'Down') {\n this._downKey = true;\n }\n }\n\n ignoreDefaultControls(ignore: boolean) {\n this._ignoreDefaultControls = ignore;\n }\n\n shouldIgnoreDefaultControls() {\n return (\n this._ignoreDefaultControls ||\n this._ignoreDefaultControlsAsSyncedByNetwork\n );\n }\n\n simulateLeftKey() {\n this._leftKey = true;\n }\n\n simulateRightKey() {\n this._rightKey = true;\n }\n\n simulateUpKey() {\n this._upKey = true;\n }\n\n simulateDownKey() {\n this._downKey = true;\n }\n\n simulateStick(stickAngle: float, stickForce: float) {\n this._stickAngle = stickAngle % 360;\n this._stickForce = Math.max(0, Math.min(1, stickForce));\n }\n\n /**.\n * @param input The control to be tested [Left,Right,Up,Down,Stick].\n * @returns true if the key was used since the last `doStepPreEvents` call.\n */\n isUsingControl(input: string): boolean {\n if (input === 'Left') {\n return this._leftKeyPressedDuration > 0;\n }\n if (input === 'Right') {\n return this._rightKeyPressedDuration > 0;\n }\n if (input === 'Up') {\n return this._upKeyPressedDuration > 0;\n }\n if (input === 'Down') {\n return this._downKeyPressedDuration > 0;\n }\n if (input === 'Stick') {\n return this._wasStickUsed;\n }\n return false;\n }\n\n getLastStickInputAngle() {\n return this._stickAngle;\n }\n\n /**\n * A hook must typically be registered by a behavior that requires this one\n * in its onCreate function.\n * The hook must stay forever to avoid side effects like a hooks order\n * change. To handle deactivated behavior, the hook can check that its\n * behavior is activated before doing anything.\n */\n registerHook(\n hook: gdjs.TopDownMovementRuntimeBehavior.TopDownMovementHook\n ) {\n this._topDownMovementHooks.push(hook);\n }\n }\n\n export namespace TopDownMovementRuntimeBehavior {\n export class TopDownMovementHookContext {\n private direction: integer = -1;\n\n /**\n * @returns The movement direction from 0 for left to 7 for up-left and\n * -1 for no direction.\n */\n getDirection(): integer {\n return this.direction;\n }\n\n /**\n * This method won't change the direction used by the top-down movement\n * behavior.\n */\n _setDirection(direction: integer): void {\n this.direction = direction;\n }\n }\n\n // This should be a static attribute but it's not possible because of\n // declaration order.\n export const _topDownMovementHookContext =\n new gdjs.TopDownMovementRuntimeBehavior.TopDownMovementHookContext();\n\n /**\n * Allow extensions relying on the top-down movement to customize its\n * behavior a bit.\n */\n export interface TopDownMovementHook {\n /**\n * Return the direction to use instead of the direction given in\n * parameter.\n */\n overrideDirection(hookContext: TopDownMovementHookContext): integer;\n /**\n * Called before the acceleration and new direction is applied to the\n * velocity.\n */\n beforeSpeedUpdate(hookContext: TopDownMovementHookContext): void;\n /**\n * Called before the velocity is applied to the object position and\n * angle.\n */\n beforePositionUpdate(hookContext: TopDownMovementHookContext): void;\n }\n\n export interface BasisTransformation {\n toScreen(worldPoint: FloatPoint, screenPoint: FloatPoint): void;\n }\n\n export class IsometryTransformation\n implements gdjs.TopDownMovementRuntimeBehavior.BasisTransformation\n {\n private _screen: float[][];\n\n /**\n * @param angle between the x axis and the projected isometric x axis.\n * @throws if the angle is not in ]0; pi/4[. Note that 0 is a front viewpoint and pi/4 a top-down viewpoint.\n */\n constructor(angle: float) {\n if (angle <= 0 || angle >= Math.PI / 4)\n throw new RangeError(\n 'An isometry angle must be in ]0; pi/4] but was: ' + angle\n );\n\n const alpha = Math.asin(Math.tan(angle));\n const sinA = Math.sin(alpha);\n const cosB = Math.cos(Math.PI / 4);\n const sinB = cosB;\n // https://en.wikipedia.org/wiki/Isometric_projection\n //\n // / 1 0 0 \\ / cosB 0 -sinB \\ / 1 0 0 \\\n // | 0 cosA sinA | | 0 1 0 | | 0 0 -1 |\n // \\ 0 -sinA cosA / \\ sinB 0 cosB / \\ 0 1 0 /\n this._screen = [\n [cosB, -sinB],\n [sinA * sinB, sinA * cosB],\n ];\n }\n\n toScreen(worldPoint: FloatPoint, screenPoint: FloatPoint): void {\n const x =\n this._screen[0][0] * worldPoint[0] +\n this._screen[0][1] * worldPoint[1];\n const y =\n this._screen[1][0] * worldPoint[0] +\n this._screen[1][1] * worldPoint[1];\n screenPoint[0] = x;\n screenPoint[1] = y;\n }\n }\n }\n\n gdjs.registerBehavior(\n 'TopDownMovementBehavior::TopDownMovementBehavior',\n gdjs.TopDownMovementRuntimeBehavior\n );\n}\n"],
|
|
5
|
+
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CAuBS,eAA6C,GAAK,eAAgB,CA0DvE,YACE,EACA,EACA,EACA,CACA,MAAM,EAAmB,EAAc,GAjDjC,YAAgB,EAGhB,gBAAoB,EACpB,gBAAoB,EACpB,mBAAuB,EAGvB,cAAoB,GACpB,eAAqB,GACrB,YAAkB,GAClB,cAAoB,GACpB,6BAAiC,EACjC,8BAAkC,EAClC,2BAA+B,EAC/B,6BAAiC,EACjC,mBAAyB,GACzB,iBAAqB,EACrB,iBAAqB,EAK7B,mCAAyC,GAIzC,6CAAmD,GAK3C,wBAA8B,GAC9B,yBAA+B,GAC/B,sBAA4B,GAC5B,wBAA8B,GAI9B,uCAAgD,CAAC,EAAG,GAEpD,2BACN,GAQA,KAAK,gBAAkB,EAAa,eACpC,KAAK,cAAgB,EAAa,aAClC,KAAK,cAAgB,EAAa,aAClC,KAAK,UAAY,EAAa,SAC9B,KAAK,iBAAmB,EAAa,gBACrC,KAAK,cAAgB,EAAa,aAClC,KAAK,aAAe,EAAa,YACjC,KAAK,uBAAyB,EAAa,sBAC3C,KAAK,aACH,EAAa,UACb,EAAa,qBAEf,KAAK,qBAAuB,EAAa,qBAAuB,EAChE,KAAK,mBACH,EAAa,oBAAsB,OAC/B,GACA,EAAa,kBAGrB,oBAAqD,CAGnD,YAAK,8BAAgC,GACrC,KAAK,wCAA0C,GAExC,IACF,MAAM,qBACT,MAAO,CACL,EAAG,KAAK,OACR,GAAI,KAA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B,EAAO,KAAK,IAAI,KAAK,GAAK,GAC1B,EAAO,EAMb,KAAK,QAAU,CACb,CAAC,EAAM,CAAC,GACR,CAAC,EAAO,EAAM,EAAO,IAIzB,SAAS,EAAwB,EAA+B,CAC9D,KAAM,GACJ,KAAK,QAAQ,GAAG,GAAK,EAAW,GAChC,KAAK,QAAQ,GAAG,GAAK,EAAW,GAC5B,EACJ,KAAK,QAAQ,GAAG,GAAK,EAAW,GAChC,KAAK,QAAQ,GAAG,GAAK,EAAW,GAClC,EAAY,GAAK,EACjB,EAAY,GAAK,GAtCd,EAAM,0BApDE,2EA+FjB,EAAK,iBACH,mDACA,EAAK,kCAv3BC",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -60,7 +60,7 @@ module.exports = {
|
|
|
60
60
|
'Tween',
|
|
61
61
|
_('Tweening'),
|
|
62
62
|
_(
|
|
63
|
-
'
|
|
63
|
+
'Smoothly animate object properties over time — such as position, rotation scale, opacity, and more — as well as variables. Ideal for creating fluid transitions and UI animations. While you can use tweens to move objects, other behaviors (like platform, physics, ellipse movement...) or forces are often better suited for dynamic movement. Tween is best used for animating UI elements, static objects that need to move from one point to another, or other values like variables.'
|
|
64
64
|
),
|
|
65
65
|
'Matthias Meike, Florian Rival',
|
|
66
66
|
'Open source (MIT License)'
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(l){const d=new l.Logger("RuntimeInstanceContainer");class u{constructor(){this._allInstancesList=[];this._allInstancesListIsUpToDate=!0;this._instancesRemoved=[];this._layersCameraCoordinates={};this._debugDrawEnabled=!1;this._debugDrawShowHiddenInstances=!1;this._debugDrawShowPointsNames=!1;this._debugDrawShowCustomPoints=!1;this._initialBehaviorSharedData=new Hashtable,this._instances=new Hashtable,this._instancesCache=new Hashtable,this._objects=new Hashtable,this._objectsCtor=new Hashtable,this._layers=new Hashtable,this._orderedLayers=[]}enableDebugDraw(e,t,s,a){this._debugDrawEnabled&&!e&&this.getDebuggerRenderer().clearDebugDraw(),this._debugDrawEnabled=e,this._debugDrawShowHiddenInstances=t,this._debugDrawShowPointsNames=s,this._debugDrawShowCustomPoints=a}isObjectRegistered(e){return this._objects.containsKey(e)&&this._instances.containsKey(e)&&this._objectsCtor.containsKey(e)}registerObject(e){this._objects.put(e.name,e),this._instances.put(e.name,[]);const t=l.getObjectConstructor(e.type);this._objectsCtor.put(e.name,t),t.supportsReinitialization&&this._instancesCache.put(e.name,[])}updateObject(e){this.isObjectRegistered(e.name)||d.warn("Tried to call updateObject for an object that was not registered ("+e.name+"). Call registerObject first."),this._objects.put(e.name,e)}unregisterObject(e){const t=this._instances.get(e);if(t){const s=t.slice();for(let a=0;a<s.length;a++)this.markObjectForDeletion(s[a]);this._cacheOrClearRemovedInstances()}this._objects.remove(e),this._instances.remove(e),this._instancesCache.remove(e),this._objectsCtor.remove(e)}createObjectsFrom(e,t,s,a,n){let i,r;arguments.length===5?(i=a,r=n):(i=0,r=arguments[3]);for(let h=0,g=e.length;h<g;++h){const o=e[h],_=o.name,c=this.createObject(_);c!==null&&(r&&(c.persistentUuid=o.persistentUuid||null),c.setPosition(o.x+t,o.y+s),c.setAngle(o.angle),l.Base3DHandler&&l.Base3DHandler.is3D(c)&&(c.setZ((o.z||0)+i),o.rotationX!==void 0&&c.setRotationX(o.rotationX),o.rotationY!==void 0&&c.setRotationY(o.rotationY)),c.setZOrder(o.zOrder),c.setLayer(o.layer),c.getVariables().initFrom(o.initialVariables,!0),c.extraInitializationFromInitialInstance(o))}}getInitialSharedDataForBehavior(e){return this._initialBehaviorSharedData.get(e)}setInitialSharedDataForBehavior(e,t){this._initialBehaviorSharedData.put(e,t)}_setLayerDefaultZOrders(){if(this.getGame().getGameData().properties.useDeprecatedZeroAsDefaultZOrder)return;const e={},t=this.getAdhocListOfAllInstances();for(let s=0,a=t.length;s<a;++s){const n=t[s];let i=n.getLayer();const r=n.getZOrder();(e[i]===void 0||e[i]<r)&&(e[i]=r)}for(let s in e)this.getLayer(s).setDefaultZOrder(e[s]+1)}_updateLayersCameraCoordinates(e){this._layersCameraCoordinates=this._layersCameraCoordinates||{};for(const t in this._layers.items)if(this._layers.items.hasOwnProperty(t)){const s=this._layers.items[t];this._layersCameraCoordinates[t]=this._layersCameraCoordinates[t]||[0,0,0,0],this._layersCameraCoordinates[t][0]=s.getCameraX()-s.getCameraWidth()/2*e,this._layersCameraCoordinates[t][1]=s.getCameraY()-s.getCameraHeight()/2*e,this._layersCameraCoordinates[t][2]=s.getCameraX()+s.getCameraWidth()/2*e,this._layersCameraCoordinates[t][3]=s.getCameraY()+s.getCameraHeight()/2*e}}_updateLayersPreRender(){for(const e of this._orderedLayers)e.updatePreRender(this)}_updateObjectsPreRender(){const e=this.getAdhocListOfAllInstances();for(let t=0,s=e.length;t<s;++t){const a=e[t],n=a.getRendererObject();n&&(n.visible=!a.isHidden(),n.visible&&this.getGame().getEffectsManager().updatePreRender(a.getRendererEffects(),a)),a.updatePreRender(this)}}_cacheOrClearRemovedInstances(){for(let e=0,t=this._instancesRemoved.length;e<t;++e){const s=this._instancesRemoved[e],a=this._instancesCache.get(s.getName());a&&a.length<128&&a.push(s),s.onDestroyed()}this._instancesRemoved.length=0}_constructListOfAllInstances(){let e=0;for(const t in this._instances.items)if(this._instances.items.hasOwnProperty(t)){const s=this._instances.items[t],a=e;e+=s.length;for(let n=0,i=s.length;n<i;++n)a+n<this._allInstancesList.length?this._allInstancesList[a+n]=s[n]:this._allInstancesList.push(s[n])}this._allInstancesList.length=e,this._allInstancesListIsUpToDate=!0}getInstancesOf(e){return this._instances.items[e]}getAdhocListOfAllInstances(){return this._allInstancesListIsUpToDate||this._constructListOfAllInstances(),this._allInstancesList}_updateObjectsPreEvents(){const e=this.getAdhocListOfAllInstances();for(let t=0,s=e.length;t<s;++t){const a=e[t],n=a.getElapsedTime();if(a.hasNoForces())a.update(this);else{const i=a.getAverageForce(),r=n/1e3;a.setX(a.getX()+i.getX()*r),a.setY(a.getY()+i.getY()*r),a.update(this),a.updateForces(r)}a.updateTimers(n),e[t].stepBehaviorsPreEvents(this)}this._cacheOrClearRemovedInstances()}_updateObjectsPostEvents(){this._cacheOrClearRemovedInstances();const e=this.getAdhocListOfAllInstances();for(let t=0,s=e.length;t<s;++t)e[t].stepBehaviorsPostEvents(this);this._cacheOrClearRemovedInstances()}addObject(e){this._instances.containsKey(e.name)||this._instances.put(e.name,[]),this._instances.get(e.name).push(e),this._allInstancesListIsUpToDate=!1}getObjects(e){return this._instances.containsKey(e)||(d.info('RuntimeScene.getObjects: No instances called "'+e+'"! Adding it.'),this._instances.put(e,[])),this._instances.get(e)}createObject(e){if(!this._objectsCtor.containsKey(e)||!this._objects.containsKey(e))return null;const t=this._instancesCache.get(e),s=this._objectsCtor.get(e);let a;return!t||t.length===0?a=new s(this,this._objects.get(e)):(a=t.pop(),a.reinitialize(this._objects.get(e))),this.addObject(a),a}markObjectForDeletion(e){if(this._instancesRemoved.indexOf(e)===-1&&this._instancesRemoved.push(e),this._instances.containsKey(e.getName())){const t=e.id,s=this._instances.get(e.getName());for(let a=0,n=s.length;a<n;++a)if(s[a].id==t){s.splice(a,1),this._allInstancesListIsUpToDate=!1;break}}e.onDeletedFromScene();for(let t=0;t<l.callbacksObjectDeletedFromScene.length;++t)l.callbacksObjectDeletedFromScene[t](this,e)}getLayer(e){return this._layers.containsKey(e)?this._layers.get(e):this._layers.get("")}hasLayer(e){return this._layers.containsKey(e)}removeLayer(e){const t=this._layers.get(e);if(!t)return;const s=this.getAdhocListOfAllInstances();for(let n=0;n<s.length;++n){const i=s[n];i.getLayer()===e&&i.setLayer("")}this._layers.remove(e);const a=this._orderedLayers.indexOf(t);this._orderedLayers.splice(a,1)}setLayerIndex(e,t){const s=this._layers.get(e);if(!s)return;const a=this._orderedLayers.indexOf(s);a!==t&&(this._orderedLayers.splice(a,1),this._orderedLayers.splice(t,0,s),this.getRenderer().setLayerIndex(s,t))}getAllLayerNames(e){this._layers.keys(e)}getInstancesCountOnScene(e){const t=this._instances.get(e);return t?t.length:0}updateObjectsForces(){for(const e in this._instances.items)if(this._instances.items.hasOwnProperty(e)){const t=this._instances.items[e];for(let s=0,a=t.length;s<a;++s){const n=t[s];if(!n.hasNoForces()){const i=n.getAverageForce(),r=n.getElapsedTime()/1e3;n.setX(n.getX()+i.getX()*r),n.setY(n.getY()+i.getY()*r),n.updateForces(r)}}}}_destroy(){this._layers=new Hashtable,this._orderedLayers=[],this._objects=new Hashtable,this._instances=new Hashtable,this._instancesCache=new Hashtable,this._objectsCtor=new Hashtable,this._allInstancesList=[],this._instancesRemoved=[]}}l.RuntimeInstanceContainer=u})(gdjs||(gdjs={}));
|
|
1
|
+
var gdjs;(function(l){const d=new l.Logger("RuntimeInstanceContainer");class u{constructor(){this._allInstancesList=[];this._allInstancesListIsUpToDate=!0;this._instancesRemoved=[];this._layersCameraCoordinates={};this._debugDrawEnabled=!1;this._debugDrawShowHiddenInstances=!1;this._debugDrawShowPointsNames=!1;this._debugDrawShowCustomPoints=!1;this._initialBehaviorSharedData=new Hashtable,this._instances=new Hashtable,this._instancesCache=new Hashtable,this._objects=new Hashtable,this._objectsCtor=new Hashtable,this._layers=new Hashtable,this._orderedLayers=[]}enableDebugDraw(e,t,s,a){this._debugDrawEnabled&&!e&&this.getDebuggerRenderer().clearDebugDraw(),this._debugDrawEnabled=e,this._debugDrawShowHiddenInstances=t,this._debugDrawShowPointsNames=s,this._debugDrawShowCustomPoints=a}isObjectRegistered(e){return this._objects.containsKey(e)&&this._instances.containsKey(e)&&this._objectsCtor.containsKey(e)}registerObject(e){this._objects.put(e.name,e),this._instances.put(e.name,[]);const t=l.getObjectConstructor(e.type);this._objectsCtor.put(e.name,t),t.supportsReinitialization&&this._instancesCache.put(e.name,[])}updateObject(e){this.isObjectRegistered(e.name)||d.warn("Tried to call updateObject for an object that was not registered ("+e.name+"). Call registerObject first."),this._objects.put(e.name,e)}unregisterObject(e){const t=this._instances.get(e);if(t){const s=t.slice();for(let a=0;a<s.length;a++)this.markObjectForDeletion(s[a]);this._cacheOrClearRemovedInstances()}this._objects.remove(e),this._instances.remove(e),this._instancesCache.remove(e),this._objectsCtor.remove(e)}createObjectsFrom(e,t,s,a,n){let i,r;arguments.length===5?(i=a,r=n):(i=0,r=arguments[3]);for(let h=0,g=e.length;h<g;++h){const o=e[h],_=o.name,c=this.createObject(_);c!==null&&(r&&(c.persistentUuid=o.persistentUuid||null),c.setPosition(o.x+t,o.y+s),c.setAngle(o.angle),l.Base3DHandler&&l.Base3DHandler.is3D(c)&&(c.setZ((o.z||0)+i),o.rotationX!==void 0&&c.setRotationX(o.rotationX),o.rotationY!==void 0&&c.setRotationY(o.rotationY)),c.setZOrder(o.zOrder),c.setLayer(o.layer),c.getVariables().initFrom(o.initialVariables,!0),c.extraInitializationFromInitialInstance(o))}}getInitialSharedDataForBehavior(e){return this._initialBehaviorSharedData.get(e)}setInitialSharedDataForBehavior(e,t){this._initialBehaviorSharedData.put(e,t)}_setLayerDefaultZOrders(){if(this.getGame().getGameData().properties.useDeprecatedZeroAsDefaultZOrder)return;const e={},t=this.getAdhocListOfAllInstances();for(let s=0,a=t.length;s<a;++s){const n=t[s];let i=n.getLayer();const r=n.getZOrder();(e[i]===void 0||e[i]<r)&&(e[i]=r)}for(let s in e)this.getLayer(s).setDefaultZOrder(e[s]+1)}_updateLayersCameraCoordinates(e){this._layersCameraCoordinates=this._layersCameraCoordinates||{};for(const t in this._layers.items)if(this._layers.items.hasOwnProperty(t)){const s=this._layers.items[t];this._layersCameraCoordinates[t]=this._layersCameraCoordinates[t]||[0,0,0,0],this._layersCameraCoordinates[t][0]=s.getCameraX()-s.getCameraWidth()/2*e,this._layersCameraCoordinates[t][1]=s.getCameraY()-s.getCameraHeight()/2*e,this._layersCameraCoordinates[t][2]=s.getCameraX()+s.getCameraWidth()/2*e,this._layersCameraCoordinates[t][3]=s.getCameraY()+s.getCameraHeight()/2*e}}_updateLayersPreRender(){for(const e of this._orderedLayers)e.updatePreRender(this)}_updateObjectsPreRender(){const e=this.getAdhocListOfAllInstances();for(let t=0,s=e.length;t<s;++t){const a=e[t],n=a.getRendererObject();n&&(n.visible=!a.isHidden(),n.visible&&this.getGame().getEffectsManager().updatePreRender(a.getRendererEffects(),a)),a.updatePreRender(this)}}_cacheOrClearRemovedInstances(){for(let e=0,t=this._instancesRemoved.length;e<t;++e){const s=this._instancesRemoved[e],a=this._instancesCache.get(s.getName());a&&a.length<128&&a.push(s),s.onDestroyed()}this._instancesRemoved.length=0}_constructListOfAllInstances(){let e=0;for(const t in this._instances.items)if(this._instances.items.hasOwnProperty(t)){const s=this._instances.items[t],a=e;e+=s.length;for(let n=0,i=s.length;n<i;++n)a+n<this._allInstancesList.length?this._allInstancesList[a+n]=s[n]:this._allInstancesList.push(s[n])}this._allInstancesList.length=e,this._allInstancesListIsUpToDate=!0}getInstancesOf(e){return this._instances.items[e]}getAdhocListOfAllInstances(){return this._allInstancesListIsUpToDate||this._constructListOfAllInstances(),this._allInstancesList}_updateObjectsPreEvents(){const e=this.getAdhocListOfAllInstances();for(let t=0,s=e.length;t<s;++t){const a=e[t],n=a.getElapsedTime();if(a.hasNoForces())a.update(this);else{const i=a.getAverageForce(),r=n/1e3;a.setX(a.getX()+i.getX()*r),a.setY(a.getY()+i.getY()*r),a.update(this),a.updateForces(r)}a.updateTimers(n),e[t].stepBehaviorsPreEvents(this)}this._cacheOrClearRemovedInstances()}_updateObjectsPostEvents(){this._cacheOrClearRemovedInstances();const e=this.getAdhocListOfAllInstances();for(let t=0,s=e.length;t<s;++t)e[t].stepBehaviorsPostEvents(this);this._cacheOrClearRemovedInstances()}addObject(e){this._instances.containsKey(e.name)||this._instances.put(e.name,[]),this._instances.get(e.name).push(e),this._allInstancesListIsUpToDate=!1}getObjects(e){return this._instances.containsKey(e)||(d.info('RuntimeScene.getObjects: No instances called "'+e+'"! Adding it.'),this._instances.put(e,[])),this._instances.get(e)}createObject(e){if(!this._objectsCtor.containsKey(e)||!this._objects.containsKey(e))return null;const t=this._instancesCache.get(e),s=this._objectsCtor.get(e);let a;return!t||t.length===0?a=new s(this,this._objects.get(e)):(a=t.pop(),a.reinitialize(this._objects.get(e))),this.addObject(a),a}markObjectForDeletion(e){if(this._instancesRemoved.indexOf(e)===-1&&this._instancesRemoved.push(e),this._instances.containsKey(e.getName())){const t=e.id,s=this._instances.get(e.getName());for(let a=0,n=s.length;a<n;++a)if(s[a].id==t){s.splice(a,1),this._allInstancesListIsUpToDate=!1;break}}e.onDeletedFromScene();for(let t=0;t<l.callbacksObjectDeletedFromScene.length;++t)l.callbacksObjectDeletedFromScene[t](this,e)}getLayer(e){return this._layers.containsKey(e)?this._layers.get(e):this._layers.get("")}hasLayer(e){return this._layers.containsKey(e)}removeLayer(e){const t=this._layers.get(e);if(!t)return;const s=this.getAdhocListOfAllInstances();for(let n=0;n<s.length;++n){const i=s[n];i.getLayer()===e&&i.setLayer("")}this._layers.remove(e);const a=this._orderedLayers.indexOf(t);this._orderedLayers.splice(a,1)}setLayerIndex(e,t){const s=this._layers.get(e);if(!s)return;const a=this._orderedLayers.indexOf(s);a!==t&&(this._orderedLayers.splice(a,1),this._orderedLayers.splice(t,0,s),this.getRenderer().setLayerIndex(s,t))}getAllLayerNames(e){this._layers.keys(e)}getInstancesCountOnScene(e){const t=this._instances.get(e);return t?t.length:0}updateObjectsForces(){for(const e in this._instances.items)if(this._instances.items.hasOwnProperty(e)){const t=this._instances.items[e];for(let s=0,a=t.length;s<a;++s){const n=t[s];if(!n.hasNoForces()){const i=n.getAverageForce(),r=n.getElapsedTime()/1e3;n.setX(n.getX()+i.getX()*r),n.setY(n.getY()+i.getY()*r),n.updateForces(r)}}}}_destroy(){this._layers=new Hashtable,this._orderedLayers=[],this._objects=new Hashtable,this._instances=new Hashtable,this._instancesCache=new Hashtable,this._objectsCtor=new Hashtable,this._allInstancesList=[],this._instancesRemoved=[],this._layersCameraCoordinates={},this._initialBehaviorSharedData=new Hashtable}}l.RuntimeInstanceContainer=u})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=RuntimeInstanceContainer.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../GDevelop/GDJS/Runtime/RuntimeInstanceContainer.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * GDevelop JS Platform\n * Copyright 2013-2016 Florian Rival (Florian.Rival@gmail.com). All rights reserved.\n * This project is released under the MIT License.\n */\nnamespace gdjs {\n const logger = new gdjs.Logger('RuntimeInstanceContainer');\n\n /**\n * A container of object instances rendered on screen.\n */\n export abstract class RuntimeInstanceContainer {\n _initialBehaviorSharedData: Hashtable<BehaviorSharedData | null>;\n\n /** Contains the instances living on the container */\n _instances: Hashtable<RuntimeObject[]>;\n\n /**\n * An array used to create a list of all instance when necessary.\n * @see gdjs.RuntimeInstanceContainer#_constructListOfAllInstances}\n */\n private _allInstancesList: gdjs.RuntimeObject[] = [];\n _allInstancesListIsUpToDate = true;\n\n /** Used to recycle destroyed instance instead of creating new ones. */\n _instancesCache: Hashtable<RuntimeObject[]>;\n\n /** The instances removed from the container and waiting to be sent to the cache. */\n _instancesRemoved: gdjs.RuntimeObject[] = [];\n\n /** Contains the objects data stored in the project */\n _objects: Hashtable<ObjectData>;\n _objectsCtor: Hashtable<typeof RuntimeObject>;\n\n _layers: Hashtable<RuntimeLayer>;\n _orderedLayers: RuntimeLayer[]; // TODO: should this be a single structure with _layers, to enforce its usage?\n _layersCameraCoordinates: Record<string, [float, float, float, float]> = {};\n\n // Options for the debug draw:\n _debugDrawEnabled: boolean = false;\n _debugDrawShowHiddenInstances: boolean = false;\n _debugDrawShowPointsNames: boolean = false;\n _debugDrawShowCustomPoints: boolean = false;\n\n constructor() {\n this._initialBehaviorSharedData = new Hashtable();\n this._instances = new Hashtable();\n this._instancesCache = new Hashtable();\n this._objects = new Hashtable();\n this._objectsCtor = new Hashtable();\n this._layers = new Hashtable();\n this._orderedLayers = [];\n }\n\n /**\n * Return the time elapsed since the last frame,\n * in milliseconds, for objects on the layer.\n */\n abstract getElapsedTime(): float;\n\n /**\n * Get the renderer associated to the container.\n */\n abstract getRenderer(): gdjs.RuntimeInstanceContainerRenderer;\n\n /**\n * Get the renderer for visual debugging associated to the container.\n */\n abstract getDebuggerRenderer(): gdjs.DebuggerRenderer;\n\n /**\n * Get the {@link gdjs.RuntimeGame} associated to this.\n */\n abstract getGame(): gdjs.RuntimeGame;\n\n /**\n * Get the {@link gdjs.RuntimeScene} associated to this.\n */\n abstract getScene(): gdjs.RuntimeScene;\n\n abstract getAsyncTasksManager(): gdjs.AsyncTasksManager;\n\n /**\n * Convert a point from the canvas coordinates (for example,\n * the mouse position) to the container coordinates.\n *\n * @param x The x position, in container coordinates.\n * @param y The y position, in container coordinates.\n * @param result The point instance that is used to return the result.\n */\n abstract convertCoords(x: float, y: float, result?: FloatPoint): FloatPoint;\n\n /**\n * Convert a point from the container coordinates (for example,\n * an object position) to the canvas coordinates.\n *\n * @param sceneX The x position, in container coordinates.\n * @param sceneY The y position, in container coordinates.\n * @param result The point instance that is used to return the result.\n */\n abstract convertInverseCoords(\n sceneX: float,\n sceneY: float,\n result: FloatPoint\n ): FloatPoint;\n\n /**\n * @return the left bound of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getUnrotatedViewportMinX(): float;\n\n /**\n * @return the top bound of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getUnrotatedViewportMinY(): float;\n\n /**\n * @return the right bound of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getUnrotatedViewportMaxX(): float;\n\n /**\n * @return the bottom bound of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getUnrotatedViewportMaxY(): float;\n\n /**\n * @return the left bound of:\n * - the initial game resolution for a {@link gdjs.RuntimeScene}\n * - the initial default dimensions (inner area) set in the editor for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getInitialUnrotatedViewportMinX(): float;\n\n /**\n * @return the top bound of:\n * - the initial game resolution for a {@link gdjs.RuntimeScene}\n * - the initial default dimensions (inner area) set in the editor for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getInitialUnrotatedViewportMinY(): float;\n\n /**\n * @return the right bound of:\n * - the initial game resolution for a {@link gdjs.RuntimeScene}\n * - the initial default dimensions (inner area) set in the editor for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getInitialUnrotatedViewportMaxX(): float;\n\n /**\n * @return the bottom bound of:\n * - the initial game resolution for a {@link gdjs.RuntimeScene}\n * - the initial default dimensions (inner area) set in the editor for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getInitialUnrotatedViewportMaxY(): float;\n\n /**\n * @return the width of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getViewportWidth(): float;\n\n /**\n * @return the height of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getViewportHeight(): float;\n\n /**\n * @return the center X of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getViewportOriginX(): float;\n\n /**\n * @return the center Y of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getViewportOriginY(): float;\n\n /**\n * Triggered when the AABB of a child of the container could have changed.\n */\n abstract onChildrenLocationChanged(): void;\n\n /**\n * Activate or deactivate the debug visualization for collisions and points.\n */\n enableDebugDraw(\n enableDebugDraw: boolean,\n showHiddenInstances: boolean,\n showPointsNames: boolean,\n showCustomPoints: boolean\n ): void {\n if (this._debugDrawEnabled && !enableDebugDraw) {\n this.getDebuggerRenderer().clearDebugDraw();\n }\n\n this._debugDrawEnabled = enableDebugDraw;\n this._debugDrawShowHiddenInstances = showHiddenInstances;\n this._debugDrawShowPointsNames = showPointsNames;\n this._debugDrawShowCustomPoints = showCustomPoints;\n }\n\n /**\n * Check if an object is registered, meaning that instances of it can be\n * created and lives in the container.\n * @see gdjs.RuntimeInstanceContainer#registerObject\n */\n isObjectRegistered(objectName: string): boolean {\n return (\n this._objects.containsKey(objectName) &&\n this._instances.containsKey(objectName) &&\n this._objectsCtor.containsKey(objectName)\n );\n }\n\n /**\n * Register a {@link gdjs.RuntimeObject} so that instances of it can be\n * used in the container.\n * @param objectData The data for the object to register.\n */\n registerObject(objectData: ObjectData) {\n this._objects.put(objectData.name, objectData);\n this._instances.put(objectData.name, []);\n\n // Cache the constructor\n const Ctor = gdjs.getObjectConstructor(objectData.type);\n this._objectsCtor.put(objectData.name, Ctor);\n\n // Also prepare a cache for recycled instances, if the object supports it.\n if (Ctor.supportsReinitialization) {\n this._instancesCache.put(objectData.name, []);\n }\n }\n\n /**\n * Update the data of a {@link gdjs.RuntimeObject} so that instances use\n * this when constructed.\n * @param objectData The data for the object to register.\n */\n updateObject(objectData: ObjectData): void {\n if (!this.isObjectRegistered(objectData.name)) {\n logger.warn(\n 'Tried to call updateObject for an object that was not registered (' +\n objectData.name +\n '). Call registerObject first.'\n );\n }\n this._objects.put(objectData.name, objectData);\n }\n\n // Don't erase instances, nor instances cache, or objectsCtor cache.\n /**\n * Unregister a {@link gdjs.RuntimeObject}. Instances will be destroyed.\n * @param objectName The name of the object to unregister.\n */\n unregisterObject(objectName: string) {\n const instances = this._instances.get(objectName);\n if (instances) {\n // This is sub-optimal: markObjectForDeletion will search the instance to\n // remove in instances, so cost is O(n^2), n being the number of instances.\n // As we're unregistering an object which only happen during a hot-reloading,\n // this is fine.\n const instancesToRemove = instances.slice();\n for (let i = 0; i < instancesToRemove.length; i++) {\n this.markObjectForDeletion(instancesToRemove[i]);\n }\n this._cacheOrClearRemovedInstances();\n }\n this._objects.remove(objectName);\n this._instances.remove(objectName);\n this._instancesCache.remove(objectName);\n this._objectsCtor.remove(objectName);\n }\n\n /**\n * Create objects from initial instances data (for example, the initial instances\n * of the scene or the instances of an external layout).\n *\n * @param data The instances data\n * @param xPos The offset on X axis\n * @param yPos The offset on Y axis\n * @param zPos The offset on Z axis\n * @param trackByPersistentUuid If true, objects are tracked by setting their `persistentUuid`\n * to the same as the associated instance. Useful for hot-reloading when instances are changed.\n */\n createObjectsFrom(\n data: InstanceData[],\n xPos: float,\n yPos: float,\n zPos: float,\n trackByPersistentUuid: boolean\n ): void {\n let zOffset: number;\n let shouldTrackByPersistentUuid: boolean;\n\n if (arguments.length === 5) {\n zOffset = zPos;\n shouldTrackByPersistentUuid = trackByPersistentUuid;\n } else {\n /**\n * Support for the previous signature (before 3D was introduced):\n * createObjectsFrom(data, xPos, yPos, trackByPersistentUuid)\n */\n zOffset = 0;\n shouldTrackByPersistentUuid = arguments[3];\n }\n\n for (let i = 0, len = data.length; i < len; ++i) {\n const instanceData = data[i];\n const objectName = instanceData.name;\n const newObject = this.createObject(objectName);\n if (newObject !== null) {\n if (shouldTrackByPersistentUuid) {\n // Give the object the same persistentUuid as the instance, so that\n // it can be hot-reloaded.\n newObject.persistentUuid = instanceData.persistentUuid || null;\n }\n newObject.setPosition(instanceData.x + xPos, instanceData.y + yPos);\n newObject.setAngle(instanceData.angle);\n if (gdjs.Base3DHandler && gdjs.Base3DHandler.is3D(newObject)) {\n newObject.setZ((instanceData.z || 0) + zOffset);\n if (instanceData.rotationX !== undefined)\n newObject.setRotationX(instanceData.rotationX);\n if (instanceData.rotationY !== undefined)\n newObject.setRotationY(instanceData.rotationY);\n }\n\n newObject.setZOrder(instanceData.zOrder);\n newObject.setLayer(instanceData.layer);\n newObject\n .getVariables()\n .initFrom(instanceData.initialVariables, true);\n newObject.extraInitializationFromInitialInstance(instanceData);\n }\n }\n }\n\n /**\n * Get the data representing the initial shared data of the scene for the specified behavior.\n * @param name The name of the behavior\n * @returns The shared data for the behavior, if any.\n */\n getInitialSharedDataForBehavior(name: string): BehaviorSharedData | null {\n return this._initialBehaviorSharedData.get(name);\n }\n\n /**\n * Set the data representing the initial shared data of the scene for the specified behavior.\n * @param name The name of the behavior\n * @param sharedData The shared data for the behavior, or null to remove it.\n */\n setInitialSharedDataForBehavior(\n name: string,\n sharedData: BehaviorSharedData | null\n ): void {\n this._initialBehaviorSharedData.put(name, sharedData);\n }\n\n /**\n * Set the default Z order for each layer, which is the highest Z order found on each layer.\n * Useful as it ensures that instances created from events are, by default, shown in front\n * of other instances.\n */\n _setLayerDefaultZOrders() {\n if (\n this.getGame().getGameData().properties.useDeprecatedZeroAsDefaultZOrder\n ) {\n // Deprecated option to still support games that were made considered 0 as the\n // default Z order for all layers.\n return;\n }\n const layerHighestZOrders: Record<string, number> = {};\n const allInstances = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstances.length; i < len; ++i) {\n const object = allInstances[i];\n let layerName = object.getLayer();\n const zOrder = object.getZOrder();\n if (\n layerHighestZOrders[layerName] === undefined ||\n layerHighestZOrders[layerName] < zOrder\n ) {\n layerHighestZOrders[layerName] = zOrder;\n }\n }\n for (let layerName in layerHighestZOrders) {\n this.getLayer(layerName).setDefaultZOrder(\n layerHighestZOrders[layerName] + 1\n );\n }\n }\n\n _updateLayersCameraCoordinates(scale: float) {\n this._layersCameraCoordinates = this._layersCameraCoordinates || {};\n for (const name in this._layers.items) {\n if (this._layers.items.hasOwnProperty(name)) {\n const theLayer = this._layers.items[name];\n this._layersCameraCoordinates[name] = this._layersCameraCoordinates[\n name\n ] || [0, 0, 0, 0];\n this._layersCameraCoordinates[name][0] =\n theLayer.getCameraX() - (theLayer.getCameraWidth() / 2) * scale;\n this._layersCameraCoordinates[name][1] =\n theLayer.getCameraY() - (theLayer.getCameraHeight() / 2) * scale;\n this._layersCameraCoordinates[name][2] =\n theLayer.getCameraX() + (theLayer.getCameraWidth() / 2) * scale;\n this._layersCameraCoordinates[name][3] =\n theLayer.getCameraY() + (theLayer.getCameraHeight() / 2) * scale;\n }\n }\n }\n\n /**\n * Called to update effects of layers before rendering.\n */\n _updateLayersPreRender() {\n for (const layer of this._orderedLayers) {\n layer.updatePreRender(this);\n }\n }\n\n /**\n * Called to update visibility of the renderers of objects\n * rendered on the scene (\"culling\"), update effects (of visible objects)\n * and give a last chance for objects to update before rendering.\n *\n * Visibility is set to false if object is hidden, or if\n * object is too far from the camera of its layer (\"culling\").\n */\n _updateObjectsPreRender() {\n const allInstancesList = this.getAdhocListOfAllInstances();\n // TODO (3D) culling - add support for 3D object culling?\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const object = allInstancesList[i];\n const rendererObject = object.getRendererObject();\n if (rendererObject) {\n rendererObject.visible = !object.isHidden();\n\n // Update effects, only for visible objects.\n if (rendererObject.visible) {\n this.getGame()\n .getEffectsManager()\n .updatePreRender(object.getRendererEffects(), object);\n }\n }\n\n // Perform pre-render update.\n object.updatePreRender(this);\n }\n return;\n }\n\n /**\n * Empty the list of the removed objects:\n *\n * When an object is removed from the container, it is still kept in\n * {@link gdjs.RuntimeInstanceContainer#_instancesRemoved}.\n *\n * This method should be called regularly (after events or behaviors steps) so as to clear this list\n * and allows the removed objects to be cached (or destroyed if the cache is full).\n *\n * The removed objects could not be sent directly to the cache, as events may still be using them after\n * removing them from the scene for example.\n */\n _cacheOrClearRemovedInstances() {\n for (let k = 0, lenk = this._instancesRemoved.length; k < lenk; ++k) {\n const instance = this._instancesRemoved[k];\n // Cache the instance to recycle it into a new instance later.\n // If the object does not support recycling, the cache won't be defined.\n const cache = this._instancesCache.get(instance.getName());\n if (cache) {\n if (cache.length < 128) {\n cache.push(instance);\n }\n }\n instance.onDestroyed();\n }\n this._instancesRemoved.length = 0;\n }\n\n /**\n * Tool function filling _allInstancesList member with all the living object instances.\n */\n private _constructListOfAllInstances() {\n let currentListSize = 0;\n for (const name in this._instances.items) {\n if (this._instances.items.hasOwnProperty(name)) {\n const list = this._instances.items[name];\n const oldSize = currentListSize;\n currentListSize += list.length;\n for (let j = 0, lenj = list.length; j < lenj; ++j) {\n if (oldSize + j < this._allInstancesList.length) {\n this._allInstancesList[oldSize + j] = list[j];\n } else {\n this._allInstancesList.push(list[j]);\n }\n }\n }\n }\n this._allInstancesList.length = currentListSize;\n this._allInstancesListIsUpToDate = true;\n }\n\n /**\n * @param objectName The name of the object\n * @returns the instances of a given object in the container.\n */\n getInstancesOf(objectName: string): gdjs.RuntimeObject[] {\n return this._instances.items[objectName];\n }\n\n /**\n * Get a list of all {@link gdjs.RuntimeObject} living in the container.\n * You should not, normally, need this method at all. It's only to be used\n * in exceptional use cases where you need to loop through all objects,\n * and it won't be performant.\n *\n * @returns The list of all runtime objects in the container\n */\n getAdhocListOfAllInstances(): gdjs.RuntimeObject[] {\n if (!this._allInstancesListIsUpToDate) {\n this._constructListOfAllInstances();\n }\n return this._allInstancesList;\n }\n\n /**\n * Update the objects before launching the events.\n */\n _updateObjectsPreEvents() {\n // It is *mandatory* to create and iterate on a external list of all objects, as the behaviors\n // may delete the objects.\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const obj = allInstancesList[i];\n const elapsedTime = obj.getElapsedTime();\n if (!obj.hasNoForces()) {\n const averageForce = obj.getAverageForce();\n const elapsedTimeInSeconds = elapsedTime / 1000;\n obj.setX(obj.getX() + averageForce.getX() * elapsedTimeInSeconds);\n obj.setY(obj.getY() + averageForce.getY() * elapsedTimeInSeconds);\n obj.update(this);\n obj.updateForces(elapsedTimeInSeconds);\n } else {\n obj.update(this);\n }\n obj.updateTimers(elapsedTime);\n allInstancesList[i].stepBehaviorsPreEvents(this);\n }\n\n // Some behaviors may have request objects to be deleted.\n this._cacheOrClearRemovedInstances();\n }\n\n /**\n * Update the objects (update positions, time management...)\n */\n _updateObjectsPostEvents() {\n this._cacheOrClearRemovedInstances();\n\n // It is *mandatory* to create and iterate on a external list of all objects, as the behaviors\n // may delete the objects.\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n allInstancesList[i].stepBehaviorsPostEvents(this);\n }\n\n // Some behaviors may have request objects to be deleted.\n this._cacheOrClearRemovedInstances();\n }\n\n /**\n * Add an object to the instances living in the container.\n * @param obj The object to be added.\n */\n addObject(obj: gdjs.RuntimeObject) {\n if (!this._instances.containsKey(obj.name)) {\n this._instances.put(obj.name, []);\n }\n this._instances.get(obj.name).push(obj);\n this._allInstancesListIsUpToDate = false;\n }\n\n /**\n * Get all the instances of the object called name.\n * @param name Name of the object for which the instances must be returned.\n * @return The list of objects with the given name\n */\n getObjects(name: string): gdjs.RuntimeObject[] | undefined {\n if (!this._instances.containsKey(name)) {\n logger.info(\n 'RuntimeScene.getObjects: No instances called \"' +\n name +\n '\"! Adding it.'\n );\n this._instances.put(name, []);\n }\n return this._instances.get(name);\n }\n\n /**\n * Create a new object from its name. The object is also added to the instances\n * living in the container (No need to call {@link gdjs.RuntimeScene.addObject})\n * @param objectName The name of the object to be created\n * @return The created object\n */\n createObject(objectName: string): gdjs.RuntimeObject | null {\n if (\n !this._objectsCtor.containsKey(objectName) ||\n !this._objects.containsKey(objectName)\n ) {\n // There is no such object in this container.\n return null;\n }\n\n // Create a new object using the object constructor (cached during loading)\n // and the stored object's data:\n const cache = this._instancesCache.get(objectName);\n const ctor = this._objectsCtor.get(objectName);\n let obj;\n if (!cache || cache.length === 0) {\n obj = new ctor(this, this._objects.get(objectName));\n } else {\n // Reuse an objet destroyed before. If there is an object in the cache,\n // then it means it does support reinitialization.\n obj = cache.pop();\n obj.reinitialize(this._objects.get(objectName));\n }\n this.addObject(obj);\n return obj;\n }\n\n /**\n * Must be called whenever an object must be removed from the container.\n * @param obj The object to be removed.\n */\n markObjectForDeletion(obj: gdjs.RuntimeObject) {\n // Add to the objects removed list.\n // The objects will be sent to the instances cache or really deleted from memory later.\n if (this._instancesRemoved.indexOf(obj) === -1) {\n this._instancesRemoved.push(obj);\n }\n\n // Delete from the living instances.\n if (this._instances.containsKey(obj.getName())) {\n const objId = obj.id;\n const allInstances = this._instances.get(obj.getName());\n for (let i = 0, len = allInstances.length; i < len; ++i) {\n if (allInstances[i].id == objId) {\n allInstances.splice(i, 1);\n this._allInstancesListIsUpToDate = false;\n break;\n }\n }\n }\n\n // Notify the object it was removed from the container\n obj.onDeletedFromScene();\n\n // Notify the global callbacks\n for (let j = 0; j < gdjs.callbacksObjectDeletedFromScene.length; ++j) {\n gdjs.callbacksObjectDeletedFromScene[j](this, obj);\n }\n return;\n }\n\n /**\n * Get the layer with the given name\n * @param name The name of the layer\n * @returns The layer, or the base layer if not found\n */\n getLayer(name: string): gdjs.RuntimeLayer {\n if (this._layers.containsKey(name)) {\n return this._layers.get(name);\n }\n return this._layers.get('');\n }\n\n /**\n * Check if a layer exists\n * @param name The name of the layer\n */\n hasLayer(name: string): boolean {\n return this._layers.containsKey(name);\n }\n\n /**\n * Add a layer.\n * @param layerData The data to construct the layer\n */\n abstract addLayer(layerData: LayerData);\n\n /**\n * Remove a layer. All {@link gdjs.RuntimeObject} on this layer will\n * be moved back to the base layer.\n * @param layerName The name of the layer to remove\n */\n removeLayer(layerName: string) {\n const existingLayer = this._layers.get(layerName);\n if (!existingLayer) return;\n\n const allInstances = this.getAdhocListOfAllInstances();\n for (let i = 0; i < allInstances.length; ++i) {\n const runtimeObject = allInstances[i];\n if (runtimeObject.getLayer() === layerName) {\n runtimeObject.setLayer('');\n }\n }\n this._layers.remove(layerName);\n const layerIndex = this._orderedLayers.indexOf(existingLayer);\n this._orderedLayers.splice(layerIndex, 1);\n }\n\n /**\n * Change the position of a layer.\n *\n * @param layerName The name of the layer to reorder\n * @param newIndex The new position in the list of layers\n */\n setLayerIndex(layerName: string, newIndex: integer): void {\n const layer: gdjs.RuntimeLayer = this._layers.get(layerName);\n if (!layer) {\n return;\n }\n const layerIndex = this._orderedLayers.indexOf(layer);\n if (layerIndex === newIndex) return;\n\n this._orderedLayers.splice(layerIndex, 1);\n this._orderedLayers.splice(newIndex, 0, layer);\n\n this.getRenderer().setLayerIndex(layer, newIndex);\n }\n\n /**\n * Fill the array passed as argument with the names of all layers\n * @param result The array where to put the layer names\n */\n getAllLayerNames(result: string[]) {\n this._layers.keys(result);\n }\n\n /**\n * Return the number of instances of the specified object living in the container.\n * @param objectName The object name for which instances must be counted.\n */\n getInstancesCountOnScene(objectName: string): integer {\n const instances = this._instances.get(objectName);\n if (instances) {\n return instances.length;\n }\n\n return 0;\n }\n\n /**\n * Update the objects positions according to their forces\n */\n updateObjectsForces(): void {\n for (const name in this._instances.items) {\n if (this._instances.items.hasOwnProperty(name)) {\n const list = this._instances.items[name];\n for (let j = 0, listLen = list.length; j < listLen; ++j) {\n const obj = list[j];\n if (!obj.hasNoForces()) {\n const averageForce = obj.getAverageForce();\n const elapsedTimeInSeconds = obj.getElapsedTime() / 1000;\n obj.setX(obj.getX() + averageForce.getX() * elapsedTimeInSeconds);\n obj.setY(obj.getY() + averageForce.getY() * elapsedTimeInSeconds);\n obj.updateForces(elapsedTimeInSeconds);\n }\n }\n }\n }\n }\n\n /**\n * Clear any data structures to make sure memory is freed as soon as\n * possible.\n */\n _destroy() {\n // It should not be necessary to reset these variables, but this help\n // ensuring that all memory related to the container is released immediately.\n this._layers = new Hashtable();\n this._orderedLayers = [];\n this._objects = new Hashtable();\n this._instances = new Hashtable();\n this._instancesCache = new Hashtable();\n this._objectsCtor = new Hashtable();\n this._allInstancesList = [];\n this._instancesRemoved = [];\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,4BAKxB,OAAwC,CAiC7C,aAAc,CAvBN,uBAA0C,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QAAQ,IAAI,GAClD,GAAI,CAAC,EACH,OAEF,KAAM,GAAa,KAAK,eAAe,QAAQ,GAC/C,AAAI,IAAe,GAEnB,MAAK,eAAe,OAAO,EAAY,GACvC,KAAK,eAAe,OAAO,EAAU,EAAG,GAExC,KAAK,cAAc,cAAc,EAAO,IAO1C,iBAAiB,EAAkB,CACjC,KAAK,QAAQ,KAAK,GAOpB,yBAAyB,EAA6B,CACpD,KAAM,GAAY,KAAK,WAAW,IAAI,GACtC,MAAI,GACK,EAAU,OAGZ,EAMT,qBAA4B,CAC1B,SAAW,KAAQ,MAAK,WAAW,MACjC,GAAI,KAAK,WAAW,MAAM,eAAe,GAAO,CAC9C,KAAM,GAAO,KAAK,WAAW,MAAM,GACnC,OAAS,GAAI,EAAG,EAAU,EAAK,OAAQ,EAAI,EAAS,EAAE,EAAG,CACvD,KAAM,GAAM,EAAK,GACjB,GAAI,CAAC,EAAI,cAAe,CACtB,KAAM,GAAe,EAAI,kBACnB,EAAuB,EAAI,iBAAmB,IACpD,EAAI,KAAK,EAAI,OAAS,EAAa,OAAS,GAC5C,EAAI,KAAK,EAAI,OAAS,EAAa,OAAS,GAC5C,EAAI,aAAa,MAW3B,UAAW,CAGT,KAAK,QAAU,GAAI,WACnB,KAAK,eAAiB,GACtB,KAAK,SAAW,GAAI,WACpB,KAAK,WAAa,GAAI,WACtB,KAAK,gBAAkB,GAAI,WAC3B,KAAK,aAAe,GAAI,WACxB,KAAK,kBAAoB,GACzB,KAAK,kBAAoB,
|
|
4
|
+
"sourcesContent": ["/*\n * GDevelop JS Platform\n * Copyright 2013-2016 Florian Rival (Florian.Rival@gmail.com). All rights reserved.\n * This project is released under the MIT License.\n */\nnamespace gdjs {\n const logger = new gdjs.Logger('RuntimeInstanceContainer');\n\n /**\n * A container of object instances rendered on screen.\n */\n export abstract class RuntimeInstanceContainer {\n _initialBehaviorSharedData: Hashtable<BehaviorSharedData | null>;\n\n /** Contains the instances living on the container */\n _instances: Hashtable<RuntimeObject[]>;\n\n /**\n * An array used to create a list of all instance when necessary.\n * @see gdjs.RuntimeInstanceContainer#_constructListOfAllInstances}\n */\n private _allInstancesList: gdjs.RuntimeObject[] = [];\n _allInstancesListIsUpToDate = true;\n\n /** Used to recycle destroyed instance instead of creating new ones. */\n _instancesCache: Hashtable<RuntimeObject[]>;\n\n /** The instances removed from the container and waiting to be sent to the cache. */\n _instancesRemoved: gdjs.RuntimeObject[] = [];\n\n /** Contains the objects data stored in the project */\n _objects: Hashtable<ObjectData>;\n _objectsCtor: Hashtable<typeof RuntimeObject>;\n\n _layers: Hashtable<RuntimeLayer>;\n _orderedLayers: RuntimeLayer[]; // TODO: should this be a single structure with _layers, to enforce its usage?\n _layersCameraCoordinates: Record<string, [float, float, float, float]> = {};\n\n // Options for the debug draw:\n _debugDrawEnabled: boolean = false;\n _debugDrawShowHiddenInstances: boolean = false;\n _debugDrawShowPointsNames: boolean = false;\n _debugDrawShowCustomPoints: boolean = false;\n\n constructor() {\n this._initialBehaviorSharedData = new Hashtable();\n this._instances = new Hashtable();\n this._instancesCache = new Hashtable();\n this._objects = new Hashtable();\n this._objectsCtor = new Hashtable();\n this._layers = new Hashtable();\n this._orderedLayers = [];\n }\n\n /**\n * Return the time elapsed since the last frame,\n * in milliseconds, for objects on the layer.\n */\n abstract getElapsedTime(): float;\n\n /**\n * Get the renderer associated to the container.\n */\n abstract getRenderer(): gdjs.RuntimeInstanceContainerRenderer;\n\n /**\n * Get the renderer for visual debugging associated to the container.\n */\n abstract getDebuggerRenderer(): gdjs.DebuggerRenderer;\n\n /**\n * Get the {@link gdjs.RuntimeGame} associated to this.\n */\n abstract getGame(): gdjs.RuntimeGame;\n\n /**\n * Get the {@link gdjs.RuntimeScene} associated to this.\n */\n abstract getScene(): gdjs.RuntimeScene;\n\n abstract getAsyncTasksManager(): gdjs.AsyncTasksManager;\n\n /**\n * Convert a point from the canvas coordinates (for example,\n * the mouse position) to the container coordinates.\n *\n * @param x The x position, in container coordinates.\n * @param y The y position, in container coordinates.\n * @param result The point instance that is used to return the result.\n */\n abstract convertCoords(x: float, y: float, result?: FloatPoint): FloatPoint;\n\n /**\n * Convert a point from the container coordinates (for example,\n * an object position) to the canvas coordinates.\n *\n * @param sceneX The x position, in container coordinates.\n * @param sceneY The y position, in container coordinates.\n * @param result The point instance that is used to return the result.\n */\n abstract convertInverseCoords(\n sceneX: float,\n sceneY: float,\n result: FloatPoint\n ): FloatPoint;\n\n /**\n * @return the left bound of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getUnrotatedViewportMinX(): float;\n\n /**\n * @return the top bound of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getUnrotatedViewportMinY(): float;\n\n /**\n * @return the right bound of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getUnrotatedViewportMaxX(): float;\n\n /**\n * @return the bottom bound of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getUnrotatedViewportMaxY(): float;\n\n /**\n * @return the left bound of:\n * - the initial game resolution for a {@link gdjs.RuntimeScene}\n * - the initial default dimensions (inner area) set in the editor for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getInitialUnrotatedViewportMinX(): float;\n\n /**\n * @return the top bound of:\n * - the initial game resolution for a {@link gdjs.RuntimeScene}\n * - the initial default dimensions (inner area) set in the editor for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getInitialUnrotatedViewportMinY(): float;\n\n /**\n * @return the right bound of:\n * - the initial game resolution for a {@link gdjs.RuntimeScene}\n * - the initial default dimensions (inner area) set in the editor for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getInitialUnrotatedViewportMaxX(): float;\n\n /**\n * @return the bottom bound of:\n * - the initial game resolution for a {@link gdjs.RuntimeScene}\n * - the initial default dimensions (inner area) set in the editor for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getInitialUnrotatedViewportMaxY(): float;\n\n /**\n * @return the width of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getViewportWidth(): float;\n\n /**\n * @return the height of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getViewportHeight(): float;\n\n /**\n * @return the center X of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getViewportOriginX(): float;\n\n /**\n * @return the center Y of:\n * - the game resolution for a {@link gdjs.RuntimeScene}\n * - the default dimensions (the AABB of all its children) for a\n * {@link gdjs.CustomRuntimeObject}.\n */\n abstract getViewportOriginY(): float;\n\n /**\n * Triggered when the AABB of a child of the container could have changed.\n */\n abstract onChildrenLocationChanged(): void;\n\n /**\n * Activate or deactivate the debug visualization for collisions and points.\n */\n enableDebugDraw(\n enableDebugDraw: boolean,\n showHiddenInstances: boolean,\n showPointsNames: boolean,\n showCustomPoints: boolean\n ): void {\n if (this._debugDrawEnabled && !enableDebugDraw) {\n this.getDebuggerRenderer().clearDebugDraw();\n }\n\n this._debugDrawEnabled = enableDebugDraw;\n this._debugDrawShowHiddenInstances = showHiddenInstances;\n this._debugDrawShowPointsNames = showPointsNames;\n this._debugDrawShowCustomPoints = showCustomPoints;\n }\n\n /**\n * Check if an object is registered, meaning that instances of it can be\n * created and lives in the container.\n * @see gdjs.RuntimeInstanceContainer#registerObject\n */\n isObjectRegistered(objectName: string): boolean {\n return (\n this._objects.containsKey(objectName) &&\n this._instances.containsKey(objectName) &&\n this._objectsCtor.containsKey(objectName)\n );\n }\n\n /**\n * Register a {@link gdjs.RuntimeObject} so that instances of it can be\n * used in the container.\n * @param objectData The data for the object to register.\n */\n registerObject(objectData: ObjectData) {\n this._objects.put(objectData.name, objectData);\n this._instances.put(objectData.name, []);\n\n // Cache the constructor\n const Ctor = gdjs.getObjectConstructor(objectData.type);\n this._objectsCtor.put(objectData.name, Ctor);\n\n // Also prepare a cache for recycled instances, if the object supports it.\n if (Ctor.supportsReinitialization) {\n this._instancesCache.put(objectData.name, []);\n }\n }\n\n /**\n * Update the data of a {@link gdjs.RuntimeObject} so that instances use\n * this when constructed.\n * @param objectData The data for the object to register.\n */\n updateObject(objectData: ObjectData): void {\n if (!this.isObjectRegistered(objectData.name)) {\n logger.warn(\n 'Tried to call updateObject for an object that was not registered (' +\n objectData.name +\n '). Call registerObject first.'\n );\n }\n this._objects.put(objectData.name, objectData);\n }\n\n // Don't erase instances, nor instances cache, or objectsCtor cache.\n /**\n * Unregister a {@link gdjs.RuntimeObject}. Instances will be destroyed.\n * @param objectName The name of the object to unregister.\n */\n unregisterObject(objectName: string) {\n const instances = this._instances.get(objectName);\n if (instances) {\n // This is sub-optimal: markObjectForDeletion will search the instance to\n // remove in instances, so cost is O(n^2), n being the number of instances.\n // As we're unregistering an object which only happen during a hot-reloading,\n // this is fine.\n const instancesToRemove = instances.slice();\n for (let i = 0; i < instancesToRemove.length; i++) {\n this.markObjectForDeletion(instancesToRemove[i]);\n }\n this._cacheOrClearRemovedInstances();\n }\n this._objects.remove(objectName);\n this._instances.remove(objectName);\n this._instancesCache.remove(objectName);\n this._objectsCtor.remove(objectName);\n }\n\n /**\n * Create objects from initial instances data (for example, the initial instances\n * of the scene or the instances of an external layout).\n *\n * @param data The instances data\n * @param xPos The offset on X axis\n * @param yPos The offset on Y axis\n * @param zPos The offset on Z axis\n * @param trackByPersistentUuid If true, objects are tracked by setting their `persistentUuid`\n * to the same as the associated instance. Useful for hot-reloading when instances are changed.\n */\n createObjectsFrom(\n data: InstanceData[],\n xPos: float,\n yPos: float,\n zPos: float,\n trackByPersistentUuid: boolean\n ): void {\n let zOffset: number;\n let shouldTrackByPersistentUuid: boolean;\n\n if (arguments.length === 5) {\n zOffset = zPos;\n shouldTrackByPersistentUuid = trackByPersistentUuid;\n } else {\n /**\n * Support for the previous signature (before 3D was introduced):\n * createObjectsFrom(data, xPos, yPos, trackByPersistentUuid)\n */\n zOffset = 0;\n shouldTrackByPersistentUuid = arguments[3];\n }\n\n for (let i = 0, len = data.length; i < len; ++i) {\n const instanceData = data[i];\n const objectName = instanceData.name;\n const newObject = this.createObject(objectName);\n if (newObject !== null) {\n if (shouldTrackByPersistentUuid) {\n // Give the object the same persistentUuid as the instance, so that\n // it can be hot-reloaded.\n newObject.persistentUuid = instanceData.persistentUuid || null;\n }\n newObject.setPosition(instanceData.x + xPos, instanceData.y + yPos);\n newObject.setAngle(instanceData.angle);\n if (gdjs.Base3DHandler && gdjs.Base3DHandler.is3D(newObject)) {\n newObject.setZ((instanceData.z || 0) + zOffset);\n if (instanceData.rotationX !== undefined)\n newObject.setRotationX(instanceData.rotationX);\n if (instanceData.rotationY !== undefined)\n newObject.setRotationY(instanceData.rotationY);\n }\n\n newObject.setZOrder(instanceData.zOrder);\n newObject.setLayer(instanceData.layer);\n newObject\n .getVariables()\n .initFrom(instanceData.initialVariables, true);\n newObject.extraInitializationFromInitialInstance(instanceData);\n }\n }\n }\n\n /**\n * Get the data representing the initial shared data of the scene for the specified behavior.\n * @param name The name of the behavior\n * @returns The shared data for the behavior, if any.\n */\n getInitialSharedDataForBehavior(name: string): BehaviorSharedData | null {\n return this._initialBehaviorSharedData.get(name);\n }\n\n /**\n * Set the data representing the initial shared data of the scene for the specified behavior.\n * @param name The name of the behavior\n * @param sharedData The shared data for the behavior, or null to remove it.\n */\n setInitialSharedDataForBehavior(\n name: string,\n sharedData: BehaviorSharedData | null\n ): void {\n this._initialBehaviorSharedData.put(name, sharedData);\n }\n\n /**\n * Set the default Z order for each layer, which is the highest Z order found on each layer.\n * Useful as it ensures that instances created from events are, by default, shown in front\n * of other instances.\n */\n _setLayerDefaultZOrders() {\n if (\n this.getGame().getGameData().properties.useDeprecatedZeroAsDefaultZOrder\n ) {\n // Deprecated option to still support games that were made considered 0 as the\n // default Z order for all layers.\n return;\n }\n const layerHighestZOrders: Record<string, number> = {};\n const allInstances = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstances.length; i < len; ++i) {\n const object = allInstances[i];\n let layerName = object.getLayer();\n const zOrder = object.getZOrder();\n if (\n layerHighestZOrders[layerName] === undefined ||\n layerHighestZOrders[layerName] < zOrder\n ) {\n layerHighestZOrders[layerName] = zOrder;\n }\n }\n for (let layerName in layerHighestZOrders) {\n this.getLayer(layerName).setDefaultZOrder(\n layerHighestZOrders[layerName] + 1\n );\n }\n }\n\n _updateLayersCameraCoordinates(scale: float) {\n this._layersCameraCoordinates = this._layersCameraCoordinates || {};\n for (const name in this._layers.items) {\n if (this._layers.items.hasOwnProperty(name)) {\n const theLayer = this._layers.items[name];\n this._layersCameraCoordinates[name] = this._layersCameraCoordinates[\n name\n ] || [0, 0, 0, 0];\n this._layersCameraCoordinates[name][0] =\n theLayer.getCameraX() - (theLayer.getCameraWidth() / 2) * scale;\n this._layersCameraCoordinates[name][1] =\n theLayer.getCameraY() - (theLayer.getCameraHeight() / 2) * scale;\n this._layersCameraCoordinates[name][2] =\n theLayer.getCameraX() + (theLayer.getCameraWidth() / 2) * scale;\n this._layersCameraCoordinates[name][3] =\n theLayer.getCameraY() + (theLayer.getCameraHeight() / 2) * scale;\n }\n }\n }\n\n /**\n * Called to update effects of layers before rendering.\n */\n _updateLayersPreRender() {\n for (const layer of this._orderedLayers) {\n layer.updatePreRender(this);\n }\n }\n\n /**\n * Called to update visibility of the renderers of objects\n * rendered on the scene (\"culling\"), update effects (of visible objects)\n * and give a last chance for objects to update before rendering.\n *\n * Visibility is set to false if object is hidden, or if\n * object is too far from the camera of its layer (\"culling\").\n */\n _updateObjectsPreRender() {\n const allInstancesList = this.getAdhocListOfAllInstances();\n // TODO (3D) culling - add support for 3D object culling?\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const object = allInstancesList[i];\n const rendererObject = object.getRendererObject();\n if (rendererObject) {\n rendererObject.visible = !object.isHidden();\n\n // Update effects, only for visible objects.\n if (rendererObject.visible) {\n this.getGame()\n .getEffectsManager()\n .updatePreRender(object.getRendererEffects(), object);\n }\n }\n\n // Perform pre-render update.\n object.updatePreRender(this);\n }\n return;\n }\n\n /**\n * Empty the list of the removed objects:\n *\n * When an object is removed from the container, it is still kept in\n * {@link gdjs.RuntimeInstanceContainer#_instancesRemoved}.\n *\n * This method should be called regularly (after events or behaviors steps) so as to clear this list\n * and allows the removed objects to be cached (or destroyed if the cache is full).\n *\n * The removed objects could not be sent directly to the cache, as events may still be using them after\n * removing them from the scene for example.\n */\n _cacheOrClearRemovedInstances() {\n for (let k = 0, lenk = this._instancesRemoved.length; k < lenk; ++k) {\n const instance = this._instancesRemoved[k];\n // Cache the instance to recycle it into a new instance later.\n // If the object does not support recycling, the cache won't be defined.\n const cache = this._instancesCache.get(instance.getName());\n if (cache) {\n if (cache.length < 128) {\n cache.push(instance);\n }\n }\n instance.onDestroyed();\n }\n this._instancesRemoved.length = 0;\n }\n\n /**\n * Tool function filling _allInstancesList member with all the living object instances.\n */\n private _constructListOfAllInstances() {\n let currentListSize = 0;\n for (const name in this._instances.items) {\n if (this._instances.items.hasOwnProperty(name)) {\n const list = this._instances.items[name];\n const oldSize = currentListSize;\n currentListSize += list.length;\n for (let j = 0, lenj = list.length; j < lenj; ++j) {\n if (oldSize + j < this._allInstancesList.length) {\n this._allInstancesList[oldSize + j] = list[j];\n } else {\n this._allInstancesList.push(list[j]);\n }\n }\n }\n }\n this._allInstancesList.length = currentListSize;\n this._allInstancesListIsUpToDate = true;\n }\n\n /**\n * @param objectName The name of the object\n * @returns the instances of a given object in the container.\n */\n getInstancesOf(objectName: string): gdjs.RuntimeObject[] {\n return this._instances.items[objectName];\n }\n\n /**\n * Get a list of all {@link gdjs.RuntimeObject} living in the container.\n * You should not, normally, need this method at all. It's only to be used\n * in exceptional use cases where you need to loop through all objects,\n * and it won't be performant.\n *\n * @returns The list of all runtime objects in the container\n */\n getAdhocListOfAllInstances(): gdjs.RuntimeObject[] {\n if (!this._allInstancesListIsUpToDate) {\n this._constructListOfAllInstances();\n }\n return this._allInstancesList;\n }\n\n /**\n * Update the objects before launching the events.\n */\n _updateObjectsPreEvents() {\n // It is *mandatory* to create and iterate on a external list of all objects, as the behaviors\n // may delete the objects.\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n const obj = allInstancesList[i];\n const elapsedTime = obj.getElapsedTime();\n if (!obj.hasNoForces()) {\n const averageForce = obj.getAverageForce();\n const elapsedTimeInSeconds = elapsedTime / 1000;\n obj.setX(obj.getX() + averageForce.getX() * elapsedTimeInSeconds);\n obj.setY(obj.getY() + averageForce.getY() * elapsedTimeInSeconds);\n obj.update(this);\n obj.updateForces(elapsedTimeInSeconds);\n } else {\n obj.update(this);\n }\n obj.updateTimers(elapsedTime);\n allInstancesList[i].stepBehaviorsPreEvents(this);\n }\n\n // Some behaviors may have request objects to be deleted.\n this._cacheOrClearRemovedInstances();\n }\n\n /**\n * Update the objects (update positions, time management...)\n */\n _updateObjectsPostEvents() {\n this._cacheOrClearRemovedInstances();\n\n // It is *mandatory* to create and iterate on a external list of all objects, as the behaviors\n // may delete the objects.\n const allInstancesList = this.getAdhocListOfAllInstances();\n for (let i = 0, len = allInstancesList.length; i < len; ++i) {\n allInstancesList[i].stepBehaviorsPostEvents(this);\n }\n\n // Some behaviors may have request objects to be deleted.\n this._cacheOrClearRemovedInstances();\n }\n\n /**\n * Add an object to the instances living in the container.\n * @param obj The object to be added.\n */\n addObject(obj: gdjs.RuntimeObject) {\n if (!this._instances.containsKey(obj.name)) {\n this._instances.put(obj.name, []);\n }\n this._instances.get(obj.name).push(obj);\n this._allInstancesListIsUpToDate = false;\n }\n\n /**\n * Get all the instances of the object called name.\n * @param name Name of the object for which the instances must be returned.\n * @return The list of objects with the given name\n */\n getObjects(name: string): gdjs.RuntimeObject[] | undefined {\n if (!this._instances.containsKey(name)) {\n logger.info(\n 'RuntimeScene.getObjects: No instances called \"' +\n name +\n '\"! Adding it.'\n );\n this._instances.put(name, []);\n }\n return this._instances.get(name);\n }\n\n /**\n * Create a new object from its name. The object is also added to the instances\n * living in the container (No need to call {@link gdjs.RuntimeScene.addObject})\n * @param objectName The name of the object to be created\n * @return The created object\n */\n createObject(objectName: string): gdjs.RuntimeObject | null {\n if (\n !this._objectsCtor.containsKey(objectName) ||\n !this._objects.containsKey(objectName)\n ) {\n // There is no such object in this container.\n return null;\n }\n\n // Create a new object using the object constructor (cached during loading)\n // and the stored object's data:\n const cache = this._instancesCache.get(objectName);\n const ctor = this._objectsCtor.get(objectName);\n let obj;\n if (!cache || cache.length === 0) {\n obj = new ctor(this, this._objects.get(objectName));\n } else {\n // Reuse an objet destroyed before. If there is an object in the cache,\n // then it means it does support reinitialization.\n obj = cache.pop();\n obj.reinitialize(this._objects.get(objectName));\n }\n this.addObject(obj);\n return obj;\n }\n\n /**\n * Must be called whenever an object must be removed from the container.\n * @param obj The object to be removed.\n */\n markObjectForDeletion(obj: gdjs.RuntimeObject) {\n // Add to the objects removed list.\n // The objects will be sent to the instances cache or really deleted from memory later.\n if (this._instancesRemoved.indexOf(obj) === -1) {\n this._instancesRemoved.push(obj);\n }\n\n // Delete from the living instances.\n if (this._instances.containsKey(obj.getName())) {\n const objId = obj.id;\n const allInstances = this._instances.get(obj.getName());\n for (let i = 0, len = allInstances.length; i < len; ++i) {\n if (allInstances[i].id == objId) {\n allInstances.splice(i, 1);\n this._allInstancesListIsUpToDate = false;\n break;\n }\n }\n }\n\n // Notify the object it was removed from the container\n obj.onDeletedFromScene();\n\n // Notify the global callbacks\n for (let j = 0; j < gdjs.callbacksObjectDeletedFromScene.length; ++j) {\n gdjs.callbacksObjectDeletedFromScene[j](this, obj);\n }\n return;\n }\n\n /**\n * Get the layer with the given name\n * @param name The name of the layer\n * @returns The layer, or the base layer if not found\n */\n getLayer(name: string): gdjs.RuntimeLayer {\n if (this._layers.containsKey(name)) {\n return this._layers.get(name);\n }\n return this._layers.get('');\n }\n\n /**\n * Check if a layer exists\n * @param name The name of the layer\n */\n hasLayer(name: string): boolean {\n return this._layers.containsKey(name);\n }\n\n /**\n * Add a layer.\n * @param layerData The data to construct the layer\n */\n abstract addLayer(layerData: LayerData);\n\n /**\n * Remove a layer. All {@link gdjs.RuntimeObject} on this layer will\n * be moved back to the base layer.\n * @param layerName The name of the layer to remove\n */\n removeLayer(layerName: string) {\n const existingLayer = this._layers.get(layerName);\n if (!existingLayer) return;\n\n const allInstances = this.getAdhocListOfAllInstances();\n for (let i = 0; i < allInstances.length; ++i) {\n const runtimeObject = allInstances[i];\n if (runtimeObject.getLayer() === layerName) {\n runtimeObject.setLayer('');\n }\n }\n this._layers.remove(layerName);\n const layerIndex = this._orderedLayers.indexOf(existingLayer);\n this._orderedLayers.splice(layerIndex, 1);\n }\n\n /**\n * Change the position of a layer.\n *\n * @param layerName The name of the layer to reorder\n * @param newIndex The new position in the list of layers\n */\n setLayerIndex(layerName: string, newIndex: integer): void {\n const layer: gdjs.RuntimeLayer = this._layers.get(layerName);\n if (!layer) {\n return;\n }\n const layerIndex = this._orderedLayers.indexOf(layer);\n if (layerIndex === newIndex) return;\n\n this._orderedLayers.splice(layerIndex, 1);\n this._orderedLayers.splice(newIndex, 0, layer);\n\n this.getRenderer().setLayerIndex(layer, newIndex);\n }\n\n /**\n * Fill the array passed as argument with the names of all layers\n * @param result The array where to put the layer names\n */\n getAllLayerNames(result: string[]) {\n this._layers.keys(result);\n }\n\n /**\n * Return the number of instances of the specified object living in the container.\n * @param objectName The object name for which instances must be counted.\n */\n getInstancesCountOnScene(objectName: string): integer {\n const instances = this._instances.get(objectName);\n if (instances) {\n return instances.length;\n }\n\n return 0;\n }\n\n /**\n * Update the objects positions according to their forces\n */\n updateObjectsForces(): void {\n for (const name in this._instances.items) {\n if (this._instances.items.hasOwnProperty(name)) {\n const list = this._instances.items[name];\n for (let j = 0, listLen = list.length; j < listLen; ++j) {\n const obj = list[j];\n if (!obj.hasNoForces()) {\n const averageForce = obj.getAverageForce();\n const elapsedTimeInSeconds = obj.getElapsedTime() / 1000;\n obj.setX(obj.getX() + averageForce.getX() * elapsedTimeInSeconds);\n obj.setY(obj.getY() + averageForce.getY() * elapsedTimeInSeconds);\n obj.updateForces(elapsedTimeInSeconds);\n }\n }\n }\n }\n }\n\n /**\n * Clear any data structures to make sure memory is freed as soon as\n * possible.\n */\n _destroy() {\n // It should not be necessary to reset these variables, but this help\n // ensuring that all memory related to the container is released immediately.\n this._layers = new Hashtable();\n this._orderedLayers = [];\n this._objects = new Hashtable();\n this._instances = new Hashtable();\n this._instancesCache = new Hashtable();\n this._objectsCtor = new Hashtable();\n this._allInstancesList = [];\n this._instancesRemoved = [];\n this._layersCameraCoordinates = {};\n this._initialBehaviorSharedData = new Hashtable();\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,4BAKxB,OAAwC,CAiC7C,aAAc,CAvBN,uBAA0C,GAClD,iCAA8B,GAM9B,uBAA0C,GAQ1C,8BAAyE,GAGzE,uBAA6B,GAC7B,mCAAyC,GACzC,+BAAqC,GACrC,gCAAsC,GAGpC,KAAK,2BAA6B,GAAI,WACtC,KAAK,WAAa,GAAI,WACtB,KAAK,gBAAkB,GAAI,WAC3B,KAAK,SAAW,GAAI,WACpB,KAAK,aAAe,GAAI,WACxB,KAAK,QAAU,GAAI,WACnB,KAAK,eAAiB,GA+JxB,gBACE,EACA,EACA,EACA,EACM,CACN,AAAI,KAAK,mBAAqB,CAAC,GAC7B,KAAK,sBAAsB,iBAG7B,KAAK,kBAAoB,EACzB,KAAK,8BAA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eAAe,GAAO,CAC9C,KAAM,GAAO,KAAK,WAAW,MAAM,GACnC,OAAS,GAAI,EAAG,EAAU,EAAK,OAAQ,EAAI,EAAS,EAAE,EAAG,CACvD,KAAM,GAAM,EAAK,GACjB,GAAI,CAAC,EAAI,cAAe,CACtB,KAAM,GAAe,EAAI,kBACnB,EAAuB,EAAI,iBAAmB,IACpD,EAAI,KAAK,EAAI,OAAS,EAAa,OAAS,GAC5C,EAAI,KAAK,EAAI,OAAS,EAAa,OAAS,GAC5C,EAAI,aAAa,MAW3B,UAAW,CAGT,KAAK,QAAU,GAAI,WACnB,KAAK,eAAiB,GACtB,KAAK,SAAW,GAAI,WACpB,KAAK,WAAa,GAAI,WACtB,KAAK,gBAAkB,GAAI,WAC3B,KAAK,aAAe,GAAI,WACxB,KAAK,kBAAoB,GACzB,KAAK,kBAAoB,GACzB,KAAK,yBAA2B,GAChC,KAAK,2BAA6B,GAAI,YAnyBnC,EAAe,6BANd",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
var gdjs;(function(d){const y=new d.Logger("Hot reloader");class
|
|
2
|
-
`+n.kind+": "+n.message)),this._runtimeGame.pause(!1),this._logs))})}_computeChangedRuntimeBehaviors(r,t){const o=[];for(let e in r){const a=r[e],i=t[e];i?a!==i&&(this._logs.push({kind:"info",message:"Behavior with type "+e+" was changed, and will be re-instantiated in gdjs.RuntimeObjects using it."}),o.push({oldBehaviorConstructor:a,newBehaviorConstructor:i,behaviorTypeName:e})):this._logs.push({kind:"warning",message:"Behavior with type "+e+" was removed from the registered behaviors in gdjs."})}return o}reloadScriptFiles(r,t,o,e){const a=[];e||r.layouts.forEach((i,s)=>{a.push(this._reloadScript("code"+s+".js"))});for(let i=0;i<o.length;++i){const s=o[i],n=t.filter(l=>l.path===s.path)[0];n?s.hash!==n.hash&&(this._logs.push({kind:"info",message:"Reloading "+s.path+" because it was changed."}),a.push(this._reloadScript(s.path))):(this._logs.push({kind:"info",message:"Loading "+s.path+" as it was added to the list of scripts."}),a.push(this._reloadScript(s.path)))}for(let i=0;i<t.length;++i){const s=t[i];!o.filter(l=>l.path===s.path)[0]&&!e&&this._logs.push({kind:"warning",message:"Script file "+s.path+" was removed."})}return Promise.all(a)}async _hotReloadRuntimeGame(r,t,o,e){const a=e.getSceneStack(),i=a.getCurrentScene();if(!i){this._logs.push({kind:"error",message:"Can't hot-reload as no scene are opened."});return}e.setProjectData(t),await e.loadFirstAssetsAndStartBackgroundLoading(i.getName(),()=>{}),this._hotReloadVariablesContainer(r.variables,t.variables,e.getVariables());for(const l of t.eventsFunctionsExtensions){const h=r.eventsFunctionsExtensions.find(u=>u.name===l.name),f=h?h.globalVariables:[],g=l.globalVariables;if(f.length>0||g.length>0){const u=e.getVariablesForExtension(l.name);u?this._hotReloadVariablesContainer(f,g,u):e._variablesByExtensionName.set(l.name,new d.VariablesContainer(g))}}const s=p.indexByName(r.layouts),n=p.indexByName(t.layouts);a._stack.forEach(l=>{const h=s.get(l.getName()),f=n.get(l.getName());if(h&&f){this._hotReloadRuntimeScene(r,t,h,f,o,l);for(const g of t.eventsFunctionsExtensions){const u=r.eventsFunctionsExtensions.find(m=>m.name===g.name),b=u?u.sceneVariables:[],c=g.sceneVariables;if(b.length>0||c.length>0){const m=l.getVariablesForExtension(g.name);m?this._hotReloadVariablesContainer(b,c,m):l._variablesByExtensionName.set(g.name,new d.VariablesContainer(c))}}}else this._logs.push({kind:"error",message:"Scene "+(h&&h.name)+" was removed. A fresh preview should be launched."})}),t.externalLayouts.forEach(l=>{const h=r.externalLayouts.filter(f=>f.name===l.name)[0];if(h&&!p.deepEqual(h,l)){const f=s.get(h.associatedLayout),g=n.get(l.associatedLayout);a._stack.forEach(u=>{this._hotReloadRuntimeSceneInstances(r,t,o,f?f.objects:[],g?g.objects:[],h.instances,l.instances,u)})}})}_hotReloadVariablesContainer(r,t,o){t.forEach(e=>{const a=e.name,i=r.find(n=>n.name===a),s=o.get(e.name);i?d.Variable.isPrimitive(e.type||"number")&&(i.value!==e.value||!d.Variable.isPrimitive(i.type||"number"))?(o.remove(a),o.add(a,new d.Variable(e))):d.Variable.isPrimitive(e.type||"number")||(e.type==="structure"?this._hotReloadStructureVariable(i.children,e.children,s):(o.remove(a),o.add(a,new d.Variable(e)))):o.add(a,new d.Variable(e))}),r.forEach(e=>{t.find(i=>i.name===e.name)||o.remove(e.name)}),o.rebuildIndexFrom(t)}_hotReloadStructureVariable(r,t,o){r?(r.forEach(e=>{const a=t.find(i=>i.name===e.name);a?d.Variable.isPrimitive(a.type||"number")&&(e.value!==a.value||!d.Variable.isPrimitive(e.type||"number"))?o.addChild(a.name,new d.Variable(a)):d.Variable.isPrimitive(a.type||"number")||(a.type==="structure"?this._hotReloadStructureVariable(e.children,a.children,o.getChild(a.name)):o.addChild(a.name,new d.Variable(a))):o.removeChild(e.name)}),t.forEach(e=>{r.find(i=>i.name===e.name)||o.addChild(e.name,new d.Variable(e))})):t.forEach(e=>{o.addChild(e.name,new d.Variable(e))})}_hotReloadRuntimeScene(r,t,o,e,a,i){i.setBackgroundColor(e.r,e.v,e.b),o.title!==e.title&&i.getGame().getRenderer().setWindowTitle(e.title),this._hotReloadVariablesContainer(o.variables,e.variables,i.getVariables()),this._hotReloadRuntimeSceneBehaviorsSharedData(o.behaviorsSharedData,e.behaviorsSharedData,i),this._hotReloadRuntimeInstanceContainer(r,t,o,e,a,i),i.setEventsGeneratedCodeFunction(e)}static resolveCustomObjectConfigurations(r,t){return t.map(o=>{const[e,a]=o.type.split("::"),i=r.eventsFunctionsExtensions.find(f=>f.name===e);if(!i)return o;const s=i&&i.eventsBasedObjects.find(f=>f.name===a);if(!s)return o;const n=o,l=n.childrenContent?s.objects.map(f=>({...f,...n.childrenContent[f.name]})):s.objects;return{...s,...o,objects:l,childrenContent:l}})}_hotReloadRuntimeInstanceContainer(r,t,o,e,a,i){const s=p.resolveCustomObjectConfigurations(r,o.objects),n=p.resolveCustomObjectConfigurations(t,e.objects);this._reinstantiateRuntimeSceneRuntimeBehaviors(a,n,i),this._hotReloadRuntimeSceneObjects(s,n,i),this._hotReloadRuntimeSceneInstances(r,t,a,s,n,o.instances,e.instances,i),this._hotReloadRuntimeSceneLayers(o.layers,e.layers,i)}_hotReloadRuntimeSceneBehaviorsSharedData(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];i?p.deepEqual(e,i)||o.setInitialSharedDataForBehavior(i.name,i):o.setInitialSharedDataForBehavior(e.name,null)}),t.forEach(e=>{const a=e.name;r.filter(s=>s.name===a)[0]||o.setInitialSharedDataForBehavior(e.name,e)})}_reinstantiateRuntimeSceneRuntimeBehaviors(r,t,o){t.forEach(e=>{const a=e.name,i=e.behaviors,s=o.getObjects(a);r.forEach(n=>{const l=n.behaviorTypeName;i.filter(h=>h.type===l).forEach(h=>{const f=h.name;this._logs.push({kind:"info",message:'Re-instantiating behavior named "'+f+'" for instances of object "'+a+'".'}),s.forEach(g=>{this._reinstantiateRuntimeObjectRuntimeBehavior(h,g)})})})})}_reinstantiateRuntimeObjectRuntimeBehavior(r,t){const o=r.name,e=t.getBehavior(o);if(!e)return;t.removeBehavior(o),t.addNewBehavior(r);const a=t.getBehavior(o);if(!a){this._logs.push({kind:"error",message:"Could not create behavior "+o+" (type: "+r.type+") for object "+t.getName()});return}for(let i in e)if(!!e.hasOwnProperty(i))if(i==="_behaviorData"){a[i]=a[i]||{};for(let s in e[i])a[i][s]=e[i][s]}else a[i]=e[i]}_hotReloadRuntimeSceneObjects(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];!i||e.type!==i.type?o.unregisterObject(a):o.isObjectRegistered(a)&&this._hotReloadRuntimeSceneObject(e,i,o)}),t.forEach(e=>{const a=e.name,i=r.filter(s=>s.name===a)[0];(!i||i.type!==e.type)&&!o.isObjectRegistered(a)&&o.registerObject(e)})}_hotReloadRuntimeSceneObject(r,t,o){let e=!0;if(!p.deepEqual(r,t)){this._logs.push({kind:"info",message:'Object "'+t.name+'" was modified and is hot-reloaded.'}),o.updateObject(t);const a=o.getObjects(t.name);a.forEach(i=>{e=i.updateFromObjectData(r,t)&&e}),this._hotReloadRuntimeObjectsBehaviors(r.behaviors,t.behaviors,a),this._hotReloadRuntimeObjectsEffects(r.effects,t.effects,a)}e||this._logs.push({kind:"error",message:'Object "'+t.name+'" could not be hot-reloaded. A fresh preview should be run.'})}_hotReloadRuntimeObjectsBehaviors(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];if(!i)o.forEach(s=>{s.hasBehavior(a)&&(s.removeBehavior(a)||this._logs.push({kind:"error",message:"Behavior "+a+" could not be removed from object"+s.getName()}))});else if(!p.deepEqual(e,i)){let s=!0;o.forEach(n=>{const l=n.getBehavior(i.name);l&&(s=this._hotReloadRuntimeBehavior(e,i,l)&&s)}),s||this._logs.push({kind:"error",message:i.name+" behavior could not be hot-reloaded."})}}),t.forEach(e=>{const a=e.name;if(!r.filter(s=>s.name===a)[0]){let s=!0;o.forEach(n=>{s=n.addNewBehavior(e)&&s}),s||this._logs.push({kind:"error",message:e.name+" behavior could not be added during hot-reload."})}})}_hotReloadRuntimeObjectsEffects(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];if(!i)o.forEach(s=>{s.hasEffect(a)&&(s.removeEffect(a)||this._logs.push({kind:"error",message:"Effect "+a+" could not be removed from object"+s.getName()}))});else if(!p.deepEqual(e,i)){let s=!0;o.forEach(n=>{e.effectType===i.effectType?s=n.updateAllEffectParameters(i)&&s:(n.removeEffect(e.name),n.addEffect(i))}),s||this._logs.push({kind:"error",message:i.name+" effect could not be hot-reloaded."})}}),t.forEach(e=>{const a=e.name;if(!r.filter(s=>s.name===a)[0]){let s=!0;o.forEach(n=>{s=n.addEffect(e)&&s}),s||this._logs.push({kind:"error",message:e.name+" effect could not be added during hot-reload."})}})}_hotReloadRuntimeBehavior(r,t,o){return o.updateFromBehaviorData(r,t)}_hotReloadRuntimeSceneLayers(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];if(!i)o.removeLayer(a);else if(o.hasLayer(a)){const s=o.getLayer(a);this._hotReloadRuntimeLayer(e,i,s)}}),t.forEach(e=>{const a=e.name;!r.filter(s=>s.name===a)[0]&&!o.hasLayer(a)&&o.addLayer(e)}),t.forEach((e,a)=>{o.setLayerIndex(e.name,a)})}_hotReloadRuntimeLayer(r,t,o){r.visibility!==t.visibility&&o.show(t.visibility),t.isLightingLayer&&((r.ambientLightColorR!==t.ambientLightColorR||r.ambientLightColorG!==t.ambientLightColorG||r.ambientLightColorB!==t.ambientLightColorB)&&o.setClearColor(t.ambientLightColorR,t.ambientLightColorG,t.ambientLightColorB),r.followBaseLayerCamera!==t.followBaseLayerCamera&&o.setFollowBaseLayerCamera(t.followBaseLayerCamera)),r.renderingType!==t.renderingType&&this._logs.push({kind:"error",message:`Could not change the rendering type (2D, 3D...) layer at runtime (for layer "${t.name}").`}),t.isLightingLayer!==r.isLightingLayer&&this._logs.push({kind:"error",message:`Could not add/remove a lighting layer at runtime (for layer "${t.name}").`}),this._hotReloadRuntimeLayerEffects(r.effects,t.effects,o)}_hotReloadRuntimeLayerEffects(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];i?o.hasEffect(a)&&(e.effectType!==i.effectType?(o.removeEffect(a),o.addEffect(i)):this._hotReloadRuntimeLayerEffect(e,i,o,a)):o.removeEffect(a)}),t.forEach(e=>{const a=e.name;!r.filter(s=>s.name===a)[0]&&!o.hasEffect(a)&&o.addEffect(e)})}_hotReloadRuntimeLayerEffect(r,t,o,e){for(let a in t.booleanParameters){const i=t.booleanParameters[a];i!==r.booleanParameters[a]&&o.setEffectBooleanParameter(e,a,i)}for(let a in t.doubleParameters){const i=t.doubleParameters[a];i!==r.doubleParameters[a]&&o.setEffectDoubleParameter(e,a,i)}for(let a in t.stringParameters){const i=t.stringParameters[a];i!==r.stringParameters[a]&&o.setEffectStringParameter(e,a,i)}}_hotReloadRuntimeSceneInstances(r,t,o,e,a,i,s,n){const l=n.getAdhocListOfAllInstances(),h=p.indexByPersistentUuid(i),f=p.indexByPersistentUuid(s),g=p.indexByPersistentUuid(l),u=p.indexByName(e),b=p.indexByName(a);for(const c of h.keys()){const m=h.get(c),v=f.get(c),R=g.get(c);m&&(!v||m.name!==v.name)&&R&&R.deleteFromScene()}for(const c of l){const m=u.get(c.getName()),v=b.get(c.getName());if(!c||!m||!v)continue;const R=h.get(c.persistentUuid),E=f.get(c.persistentUuid);if(R&&E)this._hotReloadRuntimeInstance(r,t,o,m,v,R,E,c);else if(this._hotReloadVariablesContainer(m.variables,v.variables,c.getVariables()),c instanceof d.CustomRuntimeObject){const _=c.getChildrenContainer(),C=m,B=v;this._hotReloadRuntimeInstanceContainer(r,t,C,B,o,_)}}for(const c of f.keys()){const m=h.get(c),v=f.get(c),R=g.get(c);v&&(!m||m.name!==v.name)&&!R&&n.createObjectsFrom([v],0,0,0,!0)}}_hotReloadRuntimeInstance(r,t,o,e,a,i,s,n){let l=!1;i.x!==s.x&&(n.setX(s.x),l=!0),i.y!==s.y&&(n.setY(s.y),l=!0),i.angle!==s.angle&&(n.setAngle(s.angle),l=!0),i.zOrder!==s.zOrder&&(n.setZOrder(s.zOrder),l=!0),i.layer!==s.layer&&(n.setLayer(s.layer),l=!0),d.Base3DHandler&&d.Base3DHandler.is3D(n)&&(i.z!==s.z&&s.z!==void 0&&(n.setZ(s.z),l=!0),i.rotationX!==s.rotationX&&s.rotationX!==void 0&&(n.setRotationX(s.rotationX),l=!0),i.rotationY!==s.rotationY&&s.rotationY!==void 0&&(n.setRotationY(s.rotationY),l=!0));let h=!1;if(s.customSize?i.customSize?(i.width!==s.width&&(n.setWidth(s.width),l=!0,h=!0),i.height!==s.height&&(n.setHeight(s.height),l=!0,h=!0)):(n.setWidth(s.width),n.setHeight(s.height),l=!0,h=!0):!s.customSize&&i.customSize&&(h=!0),d.Base3DHandler&&d.Base3DHandler.is3D(n)&&(i.depth!==s.depth&&s.depth!==void 0?(n.setDepth(s.depth),l=!0,h=!0):s.depth===void 0&&i.depth!==void 0&&(h=!0)),n instanceof d.CustomRuntimeObject){const u=n.getChildrenContainer(),b=e,c=a;this._hotReloadRuntimeInstanceContainer(r,t,b,c,o,u)}this._hotReloadVariablesContainer(this._mergeObjectVariablesData(e.variables,i.initialVariables),this._mergeObjectVariablesData(a.variables,s.initialVariables),n.getVariables());const f=s.numberProperties.some(u=>{const b=u.name,c=u.value,m=i.numberProperties.filter(v=>v.name===b)[0];return!m||m.value!==c}),g=s.stringProperties.some(u=>{const b=u.name,c=u.value,m=i.stringProperties.filter(v=>v.name===b)[0];return!m||m.value!==c});(f||g||h)&&(n.extraInitializationFromInitialInstance(s),l=!0),l&&n.notifyBehaviorsObjectHotReloaded()}_mergeObjectVariablesData(r,t){if(t.length===0)return r;const o=[...r];for(const e of t){const a=o.indexOf(i=>i.name===e.name);a>=0&&(o[a]=e)}return o}static deepEqual(r,t){if(r===t)return!0;if(r&&t&&typeof r=="object"&&typeof t=="object"){if(r.constructor!==t.constructor)return!1;let o,e,a;if(Array.isArray(r)){if(o=r.length,o!=t.length)return!1;for(e=o;e--!=0;)if(!p.deepEqual(r[e],t[e]))return!1;return!0}if(r.valueOf!==Object.prototype.valueOf)return r.valueOf()===t.valueOf();if(r.toString!==Object.prototype.toString)return r.toString()===t.toString();if(a=Object.keys(r),o=a.length,o!==Object.keys(t).length)return!1;for(e=o;e--!=0;)if(!Object.prototype.hasOwnProperty.call(t,a[e]))return!1;for(e=o;e--!=0;){const i=a[e];if(!p.deepEqual(r[i],t[i]))return!1}return!0}return r!==r&&t!==t}}d.HotReloader=p})(gdjs||(gdjs={}));
|
|
1
|
+
var gdjs;(function(d){const y=new d.Logger("Hot reloader");class u{constructor(r){this._reloadedScriptElement={};this._logs=[];this._alreadyLoadedScriptFiles={};this._runtimeGame=r}static indexByPersistentUuid(r){return r.reduce(function(t,o){return o.persistentUuid&&t.set(o.persistentUuid,o),t},new Map)}static indexByName(r){return r.reduce(function(t,o){return o.name&&t.set(o.name,o),t},new Map)}_canReloadScriptFile(r){function t(o,e){const a=o.indexOf(e);return a!==-1&&a===o.length-e.length}return!(t(r,".h")||this._alreadyLoadedScriptFiles[r]&&(t(r,"box2d.js")||t(r,"sha256.js")||t(r,"shopify-buy.umd.polyfilled.min.js")||t(r,"pixi-multistyle-text.umd.js")||t(r,"pixi-tilemap.umd.js")||t(r,"bondage.min.js")||t(r,"pixi-particles-pixi-renderer.min.js")||t(r,"pixi-tilemap.umd.js")||t(r,"pixi-tilemap-helper.js")||t(r,"pako/dist/pako.min")))}_reloadScript(r){function t(e,a){const i=e.indexOf(a);return i!==-1&&i===e.length-a.length}if(!this._canReloadScriptFile(r))return this._logs.push({kind:"info",message:"Not reloading "+r+" as it is blocked for hot-reloading."}),Promise.resolve();const o=document.getElementsByTagName("head")[0];return o?new Promise((e,a)=>{const i=this._reloadedScriptElement[r];if(i)o.removeChild(i);else{const n=o.getElementsByTagName("script");for(let l=0;l<n.length;++l){const h=n[l];t(h.src,r)&&o.removeChild(h)}}const s=document.createElement("script");s.src=r+"?timestamp="+Date.now(),s.onload=()=>{e()},s.onerror=n=>{a(n)},o.appendChild(s),this._reloadedScriptElement[r]=s}):Promise.reject(new Error("No head element found, are you in a navigator?"))}hotReload(){y.info("Hot reload started"),this._runtimeGame.pause(!0),this._logs=[];const r=d.projectData,t=d.runtimeGameOptions.scriptFiles;t.forEach(e=>{this._alreadyLoadedScriptFiles[e.path]=!0});const o={};for(let e in d.behaviorsTypes.items)o[e]=d.behaviorsTypes.items[e];return this._reloadScript("data.js").then(()=>{const e=d.projectData,a=d.runtimeGameOptions;d.inAppTutorialMessage&&d.inAppTutorialMessage.displayInAppTutorialMessage(this._runtimeGame,a.inAppTutorialMessageInPreview,a.inAppTutorialMessagePositionInPreview||"");const i=a.scriptFiles,s=!!a.projectDataOnlyExport;return this.reloadScriptFiles(e,t,i,s).then(()=>{const n=this._computeChangedRuntimeBehaviors(o,d.behaviorsTypes.items);return this._hotReloadRuntimeGame(r,e,n,this._runtimeGame)}).catch(n=>{const l=n.target;l instanceof HTMLScriptElement?this._logs.push({kind:"fatal",message:"Unable to reload script: "+l.src}):this._logs.push({kind:"fatal",message:"Unexpected error happened while hot-reloading: "+n.message+`
|
|
2
|
+
`+n.stack})}).then(()=>(y.info("Hot reload finished with logs:",this._logs.map(n=>`
|
|
3
|
+
`+n.kind+": "+n.message)),this._runtimeGame.pause(!1),this._logs))})}_computeChangedRuntimeBehaviors(r,t){const o=[];for(let e in r){const a=r[e],i=t[e];i?a!==i&&(this._logs.push({kind:"info",message:"Behavior with type "+e+" was changed, and will be re-instantiated in gdjs.RuntimeObjects using it."}),o.push({oldBehaviorConstructor:a,newBehaviorConstructor:i,behaviorTypeName:e})):this._logs.push({kind:"warning",message:"Behavior with type "+e+" was removed from the registered behaviors in gdjs."})}return o}reloadScriptFiles(r,t,o,e){const a=[];e||r.layouts.forEach((i,s)=>{a.push(this._reloadScript("code"+s+".js"))});for(let i=0;i<o.length;++i){const s=o[i],n=t.filter(l=>l.path===s.path)[0];n?s.hash!==n.hash&&(this._logs.push({kind:"info",message:"Reloading "+s.path+" because it was changed."}),a.push(this._reloadScript(s.path))):(this._logs.push({kind:"info",message:"Loading "+s.path+" as it was added to the list of scripts."}),a.push(this._reloadScript(s.path)))}for(let i=0;i<t.length;++i){const s=t[i];!o.filter(l=>l.path===s.path)[0]&&!e&&this._logs.push({kind:"warning",message:"Script file "+s.path+" was removed."})}return Promise.all(a)}async _hotReloadRuntimeGame(r,t,o,e){const a=e.getSceneStack(),i=a.getCurrentScene();if(!i){this._logs.push({kind:"error",message:"Can't hot-reload as no scene are opened."});return}e.setProjectData(t),await e.loadFirstAssetsAndStartBackgroundLoading(i.getName(),()=>{}),this._hotReloadVariablesContainer(r.variables,t.variables,e.getVariables());for(const l of t.eventsFunctionsExtensions){const h=r.eventsFunctionsExtensions.find(g=>g.name===l.name),f=h?h.globalVariables:[],p=l.globalVariables;if(f.length>0||p.length>0){const g=e.getVariablesForExtension(l.name);g?this._hotReloadVariablesContainer(f,p,g):e._variablesByExtensionName.set(l.name,new d.VariablesContainer(p))}}const s=u.indexByName(r.layouts),n=u.indexByName(t.layouts);a._stack.forEach(l=>{const h=s.get(l.getName()),f=n.get(l.getName());if(h&&f){this._hotReloadRuntimeScene(r,t,h,f,o,l);for(const p of t.eventsFunctionsExtensions){const g=r.eventsFunctionsExtensions.find(m=>m.name===p.name),v=g?g.sceneVariables:[],c=p.sceneVariables;if(v.length>0||c.length>0){const m=l.getVariablesForExtension(p.name);m?this._hotReloadVariablesContainer(v,c,m):l._variablesByExtensionName.set(p.name,new d.VariablesContainer(c))}}}else this._logs.push({kind:"error",message:"Scene "+(h&&h.name)+" was removed. A fresh preview should be launched."})}),t.externalLayouts.forEach(l=>{const h=r.externalLayouts.filter(f=>f.name===l.name)[0];if(h&&!u.deepEqual(h,l)){const f=s.get(h.associatedLayout),p=n.get(l.associatedLayout),g=u.resolveCustomObjectConfigurations(r,f?f.objects:[]),v=u.resolveCustomObjectConfigurations(t,p?p.objects:[]);a._stack.forEach(c=>{this._hotReloadRuntimeSceneInstances(r,t,o,g,v,h.instances,l.instances,c)})}})}_hotReloadVariablesContainer(r,t,o){t.forEach(e=>{const a=e.name,i=r.find(n=>n.name===a),s=o.get(e.name);i?d.Variable.isPrimitive(e.type||"number")&&(i.value!==e.value||!d.Variable.isPrimitive(i.type||"number"))?(o.remove(a),o.add(a,new d.Variable(e))):d.Variable.isPrimitive(e.type||"number")||(e.type==="structure"?this._hotReloadStructureVariable(i.children,e.children,s):(o.remove(a),o.add(a,new d.Variable(e)))):o.add(a,new d.Variable(e))}),r.forEach(e=>{t.find(i=>i.name===e.name)||o.remove(e.name)}),o.rebuildIndexFrom(t)}_hotReloadStructureVariable(r,t,o){r?(r.forEach(e=>{const a=t.find(i=>i.name===e.name);a?d.Variable.isPrimitive(a.type||"number")&&(e.value!==a.value||!d.Variable.isPrimitive(e.type||"number"))?o.addChild(a.name,new d.Variable(a)):d.Variable.isPrimitive(a.type||"number")||(a.type==="structure"?this._hotReloadStructureVariable(e.children,a.children,o.getChild(a.name)):o.addChild(a.name,new d.Variable(a))):o.removeChild(e.name)}),t.forEach(e=>{r.find(i=>i.name===e.name)||o.addChild(e.name,new d.Variable(e))})):t.forEach(e=>{o.addChild(e.name,new d.Variable(e))})}_hotReloadRuntimeScene(r,t,o,e,a,i){i.setBackgroundColor(e.r,e.v,e.b),o.title!==e.title&&i.getGame().getRenderer().setWindowTitle(e.title),this._hotReloadVariablesContainer(o.variables,e.variables,i.getVariables()),this._hotReloadRuntimeSceneBehaviorsSharedData(o.behaviorsSharedData,e.behaviorsSharedData,i),this._hotReloadRuntimeInstanceContainer(r,t,o,e,a,i),i.setEventsGeneratedCodeFunction(e)}static resolveCustomObjectConfigurations(r,t){return t.map(o=>{const[e,a]=o.type.split("::"),i=r.eventsFunctionsExtensions.find(f=>f.name===e);if(!i)return o;const s=i&&i.eventsBasedObjects.find(f=>f.name===a);if(!s)return o;const n=o,l=n.childrenContent?s.objects.map(f=>({...f,...n.childrenContent[f.name]})):s.objects;return{...s,...o,objects:l,childrenContent:l}})}_hotReloadRuntimeInstanceContainer(r,t,o,e,a,i){const s=u.resolveCustomObjectConfigurations(r,o.objects),n=u.resolveCustomObjectConfigurations(t,e.objects);this._reinstantiateRuntimeSceneRuntimeBehaviors(a,n,i),this._hotReloadRuntimeSceneObjects(s,n,i),this._hotReloadRuntimeSceneInstances(r,t,a,s,n,o.instances,e.instances,i),this._hotReloadRuntimeSceneLayers(o.layers,e.layers,i)}_hotReloadRuntimeSceneBehaviorsSharedData(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];i?u.deepEqual(e,i)||o.setInitialSharedDataForBehavior(i.name,i):o.setInitialSharedDataForBehavior(e.name,null)}),t.forEach(e=>{const a=e.name;r.filter(s=>s.name===a)[0]||o.setInitialSharedDataForBehavior(e.name,e)})}_reinstantiateRuntimeSceneRuntimeBehaviors(r,t,o){t.forEach(e=>{const a=e.name,i=e.behaviors,s=o.getObjects(a);r.forEach(n=>{const l=n.behaviorTypeName;i.filter(h=>h.type===l).forEach(h=>{const f=h.name;this._logs.push({kind:"info",message:'Re-instantiating behavior named "'+f+'" for instances of object "'+a+'".'}),s.forEach(p=>{this._reinstantiateRuntimeObjectRuntimeBehavior(h,p)})})})})}_reinstantiateRuntimeObjectRuntimeBehavior(r,t){const o=r.name,e=t.getBehavior(o);if(!e)return;t.removeBehavior(o),t.addNewBehavior(r);const a=t.getBehavior(o);if(!a){this._logs.push({kind:"error",message:"Could not create behavior "+o+" (type: "+r.type+") for object "+t.getName()});return}for(let i in e)if(!!e.hasOwnProperty(i))if(i==="_behaviorData"){a[i]=a[i]||{};for(let s in e[i])a[i][s]=e[i][s]}else a[i]=e[i]}_hotReloadRuntimeSceneObjects(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];!i||e.type!==i.type?o.unregisterObject(a):o.isObjectRegistered(a)&&this._hotReloadRuntimeSceneObject(e,i,o)}),t.forEach(e=>{const a=e.name,i=r.filter(s=>s.name===a)[0];(!i||i.type!==e.type)&&!o.isObjectRegistered(a)&&o.registerObject(e)})}_hotReloadRuntimeSceneObject(r,t,o){let e=!0;if(!u.deepEqual(r,t)){this._logs.push({kind:"info",message:'Object "'+t.name+'" was modified and is hot-reloaded.'}),o.updateObject(t);const a=o.getObjects(t.name);a.forEach(i=>{e=i.updateFromObjectData(r,t)&&e}),this._hotReloadRuntimeObjectsBehaviors(r.behaviors,t.behaviors,a),this._hotReloadRuntimeObjectsEffects(r.effects,t.effects,a)}e||this._logs.push({kind:"error",message:'Object "'+t.name+'" could not be hot-reloaded. A fresh preview should be run.'})}_hotReloadRuntimeObjectsBehaviors(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];if(!i)o.forEach(s=>{s.hasBehavior(a)&&(s.removeBehavior(a)||this._logs.push({kind:"error",message:"Behavior "+a+" could not be removed from object"+s.getName()}))});else if(!u.deepEqual(e,i)){let s=!0;o.forEach(n=>{const l=n.getBehavior(i.name);l&&(s=this._hotReloadRuntimeBehavior(e,i,l)&&s)}),s||this._logs.push({kind:"error",message:i.name+" behavior could not be hot-reloaded."})}}),t.forEach(e=>{const a=e.name;if(!r.filter(s=>s.name===a)[0]){let s=!0;o.forEach(n=>{s=n.addNewBehavior(e)&&s}),s||this._logs.push({kind:"error",message:e.name+" behavior could not be added during hot-reload."})}})}_hotReloadRuntimeObjectsEffects(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];if(!i)o.forEach(s=>{s.hasEffect(a)&&(s.removeEffect(a)||this._logs.push({kind:"error",message:"Effect "+a+" could not be removed from object"+s.getName()}))});else if(!u.deepEqual(e,i)){let s=!0;o.forEach(n=>{e.effectType===i.effectType?s=n.updateAllEffectParameters(i)&&s:(n.removeEffect(e.name),n.addEffect(i))}),s||this._logs.push({kind:"error",message:i.name+" effect could not be hot-reloaded."})}}),t.forEach(e=>{const a=e.name;if(!r.filter(s=>s.name===a)[0]){let s=!0;o.forEach(n=>{s=n.addEffect(e)&&s}),s||this._logs.push({kind:"error",message:e.name+" effect could not be added during hot-reload."})}})}_hotReloadRuntimeBehavior(r,t,o){return o.updateFromBehaviorData(r,t)}_hotReloadRuntimeSceneLayers(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];if(!i)o.removeLayer(a);else if(o.hasLayer(a)){const s=o.getLayer(a);this._hotReloadRuntimeLayer(e,i,s)}}),t.forEach(e=>{const a=e.name;!r.filter(s=>s.name===a)[0]&&!o.hasLayer(a)&&o.addLayer(e)}),t.forEach((e,a)=>{o.setLayerIndex(e.name,a)})}_hotReloadRuntimeLayer(r,t,o){r.visibility!==t.visibility&&o.show(t.visibility),t.isLightingLayer&&((r.ambientLightColorR!==t.ambientLightColorR||r.ambientLightColorG!==t.ambientLightColorG||r.ambientLightColorB!==t.ambientLightColorB)&&o.setClearColor(t.ambientLightColorR,t.ambientLightColorG,t.ambientLightColorB),r.followBaseLayerCamera!==t.followBaseLayerCamera&&o.setFollowBaseLayerCamera(t.followBaseLayerCamera)),r.renderingType!==t.renderingType&&this._logs.push({kind:"error",message:`Could not change the rendering type (2D, 3D...) layer at runtime (for layer "${t.name}").`}),t.isLightingLayer!==r.isLightingLayer&&this._logs.push({kind:"error",message:`Could not add/remove a lighting layer at runtime (for layer "${t.name}").`}),this._hotReloadRuntimeLayerEffects(r.effects,t.effects,o)}_hotReloadRuntimeLayerEffects(r,t,o){r.forEach(e=>{const a=e.name,i=t.filter(s=>s.name===a)[0];i?o.hasEffect(a)&&(e.effectType!==i.effectType?(o.removeEffect(a),o.addEffect(i)):this._hotReloadRuntimeLayerEffect(e,i,o,a)):o.removeEffect(a)}),t.forEach(e=>{const a=e.name;!r.filter(s=>s.name===a)[0]&&!o.hasEffect(a)&&o.addEffect(e)})}_hotReloadRuntimeLayerEffect(r,t,o,e){for(let a in t.booleanParameters){const i=t.booleanParameters[a];i!==r.booleanParameters[a]&&o.setEffectBooleanParameter(e,a,i)}for(let a in t.doubleParameters){const i=t.doubleParameters[a];i!==r.doubleParameters[a]&&o.setEffectDoubleParameter(e,a,i)}for(let a in t.stringParameters){const i=t.stringParameters[a];i!==r.stringParameters[a]&&o.setEffectStringParameter(e,a,i)}}_hotReloadRuntimeSceneInstances(r,t,o,e,a,i,s,n){const l=n.getAdhocListOfAllInstances(),h=u.indexByPersistentUuid(i),f=u.indexByPersistentUuid(s),p=u.indexByPersistentUuid(l),g=u.indexByName(e),v=u.indexByName(a);for(const c of h.keys()){const m=h.get(c),b=f.get(c),R=p.get(c);m&&(!b||m.name!==b.name)&&R&&R.deleteFromScene()}for(const c of l){const m=g.get(c.getName()),b=v.get(c.getName());if(!c||!m||!b)continue;const R=h.get(c.persistentUuid),E=f.get(c.persistentUuid);if(R&&E)this._hotReloadRuntimeInstance(r,t,o,m,b,R,E,c);else if(this._hotReloadVariablesContainer(m.variables,b.variables,c.getVariables()),c instanceof d.CustomRuntimeObject){const C=c.getChildrenContainer(),_=m,j=b;this._hotReloadRuntimeInstanceContainer(r,t,_,j,o,C)}}for(const c of f.keys()){const m=h.get(c),b=f.get(c),R=p.get(c);b&&(!m||m.name!==b.name)&&!R&&n.createObjectsFrom([b],0,0,0,!0)}}_hotReloadRuntimeInstance(r,t,o,e,a,i,s,n){let l=!1;i.x!==s.x&&(n.setX(s.x),l=!0),i.y!==s.y&&(n.setY(s.y),l=!0),i.angle!==s.angle&&(n.setAngle(s.angle),l=!0),i.zOrder!==s.zOrder&&(n.setZOrder(s.zOrder),l=!0),i.layer!==s.layer&&(n.setLayer(s.layer),l=!0),d.Base3DHandler&&d.Base3DHandler.is3D(n)&&(i.z!==s.z&&s.z!==void 0&&(n.setZ(s.z),l=!0),i.rotationX!==s.rotationX&&s.rotationX!==void 0&&(n.setRotationX(s.rotationX),l=!0),i.rotationY!==s.rotationY&&s.rotationY!==void 0&&(n.setRotationY(s.rotationY),l=!0));let h=!1;if(s.customSize?i.customSize?(i.width!==s.width&&(n.setWidth(s.width),l=!0,h=!0),i.height!==s.height&&(n.setHeight(s.height),l=!0,h=!0)):(n.setWidth(s.width),n.setHeight(s.height),l=!0,h=!0):!s.customSize&&i.customSize&&(h=!0),d.Base3DHandler&&d.Base3DHandler.is3D(n)&&(i.depth!==s.depth&&s.depth!==void 0?(n.setDepth(s.depth),l=!0,h=!0):s.depth===void 0&&i.depth!==void 0&&(h=!0)),n instanceof d.CustomRuntimeObject){const g=n.getChildrenContainer(),v=e,c=a;this._hotReloadRuntimeInstanceContainer(r,t,v,c,o,g)}this._hotReloadVariablesContainer(this._mergeObjectVariablesData(e.variables,i.initialVariables),this._mergeObjectVariablesData(a.variables,s.initialVariables),n.getVariables());const f=s.numberProperties.some(g=>{const v=g.name,c=g.value,m=i.numberProperties.filter(b=>b.name===v)[0];return!m||m.value!==c}),p=s.stringProperties.some(g=>{const v=g.name,c=g.value,m=i.stringProperties.filter(b=>b.name===v)[0];return!m||m.value!==c});(f||p||h)&&(n.extraInitializationFromInitialInstance(s),l=!0),l&&n.notifyBehaviorsObjectHotReloaded()}_mergeObjectVariablesData(r,t){if(t.length===0)return r;const o=[...r];for(const e of t){const a=o.indexOf(i=>i.name===e.name);a>=0&&(o[a]=e)}return o}static deepEqual(r,t){if(r===t)return!0;if(r&&t&&typeof r=="object"&&typeof t=="object"){if(r.constructor!==t.constructor)return!1;let o,e,a;if(Array.isArray(r)){if(o=r.length,o!=t.length)return!1;for(e=o;e--!=0;)if(!u.deepEqual(r[e],t[e]))return!1;return!0}if(r.valueOf!==Object.prototype.valueOf)return r.valueOf()===t.valueOf();if(r.toString!==Object.prototype.toString)return r.toString()===t.toString();if(a=Object.keys(r),o=a.length,o!==Object.keys(t).length)return!1;for(e=o;e--!=0;)if(!Object.prototype.hasOwnProperty.call(t,a[e]))return!1;for(e=o;e--!=0;){const i=a[e];if(!u.deepEqual(r[i],t[i]))return!1}return!0}return r!==r&&t!==t}}d.HotReloader=u})(gdjs||(gdjs={}));
|
|
3
4
|
//# sourceMappingURL=hot-reloader.js.map
|