gdcore-tools 2.0.0-gd-v5.5.232-autobuild → 2.0.0-gd-v5.5.234-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/Extensions/3D/Cube3DRuntimeObject.js +1 -1
- package/dist/Runtime/Extensions/3D/Cube3DRuntimeObject.js.map +2 -2
- package/dist/Runtime/Extensions/3D/Cube3DRuntimeObjectPixiRenderer.js +1 -1
- package/dist/Runtime/Extensions/3D/Cube3DRuntimeObjectPixiRenderer.js.map +2 -2
- package/dist/Runtime/Extensions/3D/DirectionalLight.js +1 -1
- package/dist/Runtime/Extensions/3D/DirectionalLight.js.map +2 -2
- package/dist/Runtime/Extensions/3D/JsExtension.js +60 -9
- package/dist/Runtime/Extensions/3D/Model3DRuntimeObject.js +1 -1
- package/dist/Runtime/Extensions/3D/Model3DRuntimeObject.js.map +2 -2
- package/dist/Runtime/Extensions/3D/Model3DRuntimeObject3DRenderer.js +1 -1
- package/dist/Runtime/Extensions/3D/Model3DRuntimeObject3DRenderer.js.map +2 -2
- package/dist/Runtime/Extensions/BBText/JsExtension.js +6 -6
- package/dist/Runtime/Extensions/BitmapText/JsExtension.js +6 -6
- package/dist/Runtime/Extensions/Physics2Behavior/JsExtension.js +10 -10
- package/dist/Runtime/Extensions/Physics3DBehavior/JsExtension.js +20 -7
- package/dist/Runtime/Extensions/Physics3DBehavior/Physics3DRuntimeBehavior.js +1 -1
- package/dist/Runtime/Extensions/Physics3DBehavior/Physics3DRuntimeBehavior.js.map +2 -2
- package/dist/Runtime/Extensions/Physics3DBehavior/PhysicsCar3DRuntimeBehavior.js +1 -1
- package/dist/Runtime/Extensions/Physics3DBehavior/PhysicsCar3DRuntimeBehavior.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/Spine/managers/pixi-spine-atlas-manager.js +1 -1
- package/dist/Runtime/Extensions/Spine/managers/pixi-spine-atlas-manager.js.map +2 -2
- package/dist/Runtime/Extensions/Spine/managers/pixi-spine-manager.js +1 -1
- package/dist/Runtime/Extensions/Spine/managers/pixi-spine-manager.js.map +2 -2
- package/dist/Runtime/Extensions/TextInput/JsExtension.js +11 -11
- package/dist/Runtime/Extensions/TileMap/JsExtension.js +3 -3
- package/dist/Runtime/Model3DManager.js +1 -1
- package/dist/Runtime/Model3DManager.js.map +2 -2
- package/dist/Runtime/ResourceLoader.js +1 -1
- package/dist/Runtime/ResourceLoader.js.map +2 -2
- package/dist/Runtime/RuntimeLayer.js +1 -1
- package/dist/Runtime/RuntimeLayer.js.map +2 -2
- package/dist/Runtime/events-tools/objecttools.js +1 -1
- package/dist/Runtime/events-tools/objecttools.js.map +2 -2
- package/dist/Runtime/fontfaceobserver-font-manager/fontfaceobserver-font-manager.js +1 -1
- package/dist/Runtime/fontfaceobserver-font-manager/fontfaceobserver-font-manager.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/jsonmanager.js +1 -1
- package/dist/Runtime/jsonmanager.js.map +2 -2
- package/dist/Runtime/logger.js +1 -1
- package/dist/Runtime/logger.js.map +2 -2
- package/dist/Runtime/pixi-renderers/pixi-bitmapfont-manager.js +1 -1
- package/dist/Runtime/pixi-renderers/pixi-bitmapfont-manager.js.map +2 -2
- package/dist/Runtime/pixi-renderers/pixi-effects-manager.js.map +2 -2
- package/dist/Runtime/pixi-renderers/pixi-image-manager.js +1 -1
- package/dist/Runtime/pixi-renderers/pixi-image-manager.js.map +2 -2
- package/dist/Runtime/pixi-renderers/runtimegame-pixi-renderer.js +1 -1
- package/dist/Runtime/pixi-renderers/runtimegame-pixi-renderer.js.map +2 -2
- package/dist/Runtime/runtimegame.js +1 -1
- package/dist/Runtime/runtimegame.js.map +2 -2
- package/dist/Runtime/runtimescene.js +1 -1
- package/dist/Runtime/runtimescene.js.map +2 -2
- package/dist/Runtime/scenestack.js +1 -1
- package/dist/Runtime/scenestack.js.map +2 -2
- package/dist/Runtime/types/project-data.d.ts +6 -1
- package/dist/lib/libGD.cjs +1 -1
- package/dist/lib/libGD.wasm +0 -0
- package/gd.d.ts +21 -0
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(o){let y;(function(O){let w;(function(g){g.pickOnly=function(e,t){for(const s in e.items)if(e.items.hasOwnProperty(s)){const n=e.items[s];n.indexOf(t)===-1?n.length=0:(n.length=0,n.push(t))}},g.twoListsTest=function(e,t,s,n,i){let f=!1;const r=o.staticArray(o.evtTools.object.twoListsTest);t.values(r);const u=o.staticArray2(o.evtTools.object.twoListsTest);s.values(u);for(let a=0,j=r.length;a<j;++a){let c=r[a];for(let l=0,b=c.length;l<b;++l)c[l].pick=!1}for(let a=0,j=u.length;a<j;++a){let c=u[a];for(let l=0,b=c.length;l<b;++l)c[l].pick=!1}for(let a=0,j=r.length;a<j;++a){const c=r[a];for(let l=0,b=c.length;l<b;++l){let d=!1;for(let T=0,L=u.length;T<L;++T){const k=u[T];for(let p=0,R=k.length;p<R;++p)c[l].pick&&k[p].pick||c[l].id!==k[p].id&&e(c[l],k[p],i)&&(n||(f=!0,c[l].pick=!0,k[p].pick=!0),d=!0)}!d&&n&&(f=!0,c[l].pick=!0)}}for(let a=0,j=r.length;a<j;++a){let c=r[a],l=0;for(let b=0,d=c.length;b<d;++b){let T=c[b];c[b].pick&&(c[l]=T,l++)}c.length=l}if(!n)for(let a=0,j=u.length;a<j;++a){let c=u[a],l=0;for(let b=0,d=c.length;b<d;++b){let T=c[b];c[b].pick&&(c[l]=T,l++)}c.length=l}return f},g.pickObjectsIf=function(e,t,s,n){let i=!1;const f=o.staticArray(o.evtTools.object.pickObjectsIf);t.values(f);for(let r=0,u=f.length;r<u;++r){const a=f[r];for(let j=0,c=a.length;j<c;++j){const l=a[j];s^e(l,n)?(i=!0,l.pick=!0):l.pick=!1}}for(let r=0,u=f.length;r<u;++r)o.evtTools.object.filterPickedObjectsList(f[r]);return i},g.filterPickedObjectsList=function(e){let t=0;for(let s=0,n=e.length;s<n;++s){const i=e[s];i.pick&&(e[t]=i,t++)}e.length=t},g.hitBoxesCollisionTest=function(e,t,s,n,i){return o.evtTools.object.twoListsTest(o.RuntimeObject.collisionTest,e,t,s,i)},g._distanceBetweenObjects=function(e,t,s){return e.getSqDistanceToObject(t)<=s},g.distanceTest=function(e,t,s,n){return o.evtTools.object.twoListsTest(o.evtTools.object._distanceBetweenObjects,e,t,n,s*s)},g._movesToward=function(e,t,s){if(e.hasNoForces())return!1;let n=Math.atan2(t.getDrawableY()+t.getCenterY()-(e.getDrawableY()+e.getCenterY()),t.getDrawableX()+t.getCenterX()-(e.getDrawableX()+e.getCenterX()));return n*=180/3.14159,Math.abs(o.evtTools.common.angleDifference(e.getAverageForce().getAngle(),n))<=s/2},g.movesTowardTest=function(e,t,s,n){return o.evtTools.object.twoListsTest(o.evtTools.object._movesToward,e,t,n,s)},g._turnedToward=function(e,t,s){let n=Math.atan2(t.getDrawableY()+t.getCenterY()-(e.getDrawableY()+e.getCenterY()),t.getDrawableX()+t.getCenterX()-(e.getDrawableX()+e.getCenterX()));return n*=180/3.14159,Math.abs(o.evtTools.common.angleDifference(e.getAngle(),n))<=s/2},g.turnedTowardTest=function(e,t,s,n){return o.evtTools.object.twoListsTest(o.evtTools.object._turnedToward,e,t,n,s)},g._isTurnedTowardObject=function(e,t,s){return Math.abs(o.evtTools.common.angleDifference(e.getAngle(),e.getAngleToObject(t)))<=s},g.isTurnedTowardObject=function(e,t,s,n){return o.evtTools.object.twoListsTest(o.evtTools.object._isTurnedTowardObject,e,t,n,s)},g.pickAllObjects=function(e,t){for(const s in t.items)if(t.items.hasOwnProperty(s)){const n=e.getObjects(s),i=t.items[s];
|
|
1
|
+
var gdjs;(function(o){let y;(function(O){let w;(function(g){g.pickOnly=function(e,t){for(const s in e.items)if(e.items.hasOwnProperty(s)){const n=e.items[s];n.indexOf(t)===-1?n.length=0:(n.length=0,n.push(t))}},g.twoListsTest=function(e,t,s,n,i){let f=!1;const r=o.staticArray(o.evtTools.object.twoListsTest);t.values(r);const u=o.staticArray2(o.evtTools.object.twoListsTest);s.values(u);for(let a=0,j=r.length;a<j;++a){let c=r[a];for(let l=0,b=c.length;l<b;++l)c[l].pick=!1}for(let a=0,j=u.length;a<j;++a){let c=u[a];for(let l=0,b=c.length;l<b;++l)c[l].pick=!1}for(let a=0,j=r.length;a<j;++a){const c=r[a];for(let l=0,b=c.length;l<b;++l){let d=!1;for(let T=0,L=u.length;T<L;++T){const k=u[T];for(let p=0,R=k.length;p<R;++p)c[l].pick&&k[p].pick||c[l].id!==k[p].id&&e(c[l],k[p],i)&&(n||(f=!0,c[l].pick=!0,k[p].pick=!0),d=!0)}!d&&n&&(f=!0,c[l].pick=!0)}}for(let a=0,j=r.length;a<j;++a){let c=r[a],l=0;for(let b=0,d=c.length;b<d;++b){let T=c[b];c[b].pick&&(c[l]=T,l++)}c.length=l}if(!n)for(let a=0,j=u.length;a<j;++a){let c=u[a],l=0;for(let b=0,d=c.length;b<d;++b){let T=c[b];c[b].pick&&(c[l]=T,l++)}c.length=l}return f},g.pickObjectsIf=function(e,t,s,n){let i=!1;const f=o.staticArray(o.evtTools.object.pickObjectsIf);t.values(f);for(let r=0,u=f.length;r<u;++r){const a=f[r];for(let j=0,c=a.length;j<c;++j){const l=a[j];s^e(l,n)?(i=!0,l.pick=!0):l.pick=!1}}for(let r=0,u=f.length;r<u;++r)o.evtTools.object.filterPickedObjectsList(f[r]);return i},g.filterPickedObjectsList=function(e){let t=0;for(let s=0,n=e.length;s<n;++s){const i=e[s];i.pick&&(e[t]=i,t++)}e.length=t},g.hitBoxesCollisionTest=function(e,t,s,n,i){return o.evtTools.object.twoListsTest(o.RuntimeObject.collisionTest,e,t,s,i)},g._distanceBetweenObjects=function(e,t,s){return e.getSqDistanceToObject(t)<=s},g.distanceTest=function(e,t,s,n){return o.evtTools.object.twoListsTest(o.evtTools.object._distanceBetweenObjects,e,t,n,s*s)},g._movesToward=function(e,t,s){if(e.hasNoForces())return!1;let n=Math.atan2(t.getDrawableY()+t.getCenterY()-(e.getDrawableY()+e.getCenterY()),t.getDrawableX()+t.getCenterX()-(e.getDrawableX()+e.getCenterX()));return n*=180/3.14159,Math.abs(o.evtTools.common.angleDifference(e.getAverageForce().getAngle(),n))<=s/2},g.movesTowardTest=function(e,t,s,n){return o.evtTools.object.twoListsTest(o.evtTools.object._movesToward,e,t,n,s)},g._turnedToward=function(e,t,s){let n=Math.atan2(t.getDrawableY()+t.getCenterY()-(e.getDrawableY()+e.getCenterY()),t.getDrawableX()+t.getCenterX()-(e.getDrawableX()+e.getCenterX()));return n*=180/3.14159,Math.abs(o.evtTools.common.angleDifference(e.getAngle(),n))<=s/2},g.turnedTowardTest=function(e,t,s,n){return o.evtTools.object.twoListsTest(o.evtTools.object._turnedToward,e,t,n,s)},g._isTurnedTowardObject=function(e,t,s){return Math.abs(o.evtTools.common.angleDifference(e.getAngle(),e.getAngleToObject(t)))<=s},g.isTurnedTowardObject=function(e,t,s,n){return o.evtTools.object.twoListsTest(o.evtTools.object._isTurnedTowardObject,e,t,n,s)},g.pickAllObjects=function(e,t){for(const s in t.items)if(t.items.hasOwnProperty(s)){const n=e.getObjects(s),i=t.items[s];o.copyArray(n,i)}return!0},g.pickRandomObject=function(e,t){let s=0;for(let r in t.items)t.items.hasOwnProperty(r)&&(s+=t.items[r].length);if(s===0)return!1;let n=Math.floor(Math.random()*s);n>=s&&(n=s-1);let i=0,f=null;for(let r in t.items)if(t.items.hasOwnProperty(r)){let u=t.items[r];if(n-i<u.length){f=u[n-i];break}i+=u.length}return o.evtTools.object.pickOnly(t,f),!0},g.pickNearestObject=function(e,t,s,n){let i=null,f=0,r=!0;const u=o.staticArray(o.evtTools.object.pickNearestObject);e.values(u);for(let a=0,j=u.length;a<j;++a){const c=u[a];for(let l=0;l<c.length;++l){const b=c[l],d=b.getSqDistanceToPosition(t,s);(r||d<f^n)&&(f=d,i=b),r=!1}}return i?(o.evtTools.object.pickOnly(e,i),!0):!1},g.raycastObject=function(e,t,s,n,i,f,r,u){return o.evtTools.object.raycastObjectToPosition(e,t,s,t+i*Math.cos(n*Math.PI/180),s+i*Math.sin(n*Math.PI/180),f,r,u)},g.raycastObjectToPosition=function(e,t,s,n,i,f,r,u){let a=null,j=u?0:(n-t)*(n-t)+(i-s)*(i-s),c=0,l=0;const b=o.staticArray(o.evtTools.object.raycastObjectToPosition);e.values(b);for(let d=0;d<b.length;d++){const T=b[d];for(let L=0;L<T.length;L++){const k=T[L],p=k.raycastTest(t,s,n,i,!u);p.collision&&(!u&&p.closeSqDist<=j?(j=p.closeSqDist,a=k,c=p.closeX,l=p.closeY):u&&p.farSqDist>=j&&(j=p.farSqDist,a=k,c=p.farX,l=p.farY))}}return a?(o.evtTools.object.pickOnly(e,a),f.setNumber(c),r.setNumber(l),!0):!1},g.doCreateObjectOnScene=function(e,t,s,n,i,f){const r=e.createObject(t),u=e.getLayer(f);return r!==null&&(r.setPosition(n,i),r.setLayer(f),r.setZOrder(u.getDefaultZOrder()),s.containsKey(t)&&s.get(t).push(r)),r},g.createObjectOnScene=function(e,t,s,n,i){return o.evtTools.object.doCreateObjectOnScene(e,t.firstKey(),t,s,n,i)},g.createObjectFromGroupOnScene=function(e,t,s,n,i,f){o.evtTools.object.doCreateObjectOnScene(e,s,t,n,i,f)},g.getPickedInstancesCount=e=>{let t=0;const s=o.staticArray(o.evtTools.object.getPickedInstancesCount);e.values(s);for(let n=0,i=s.length;n<i;++n)t+=s[n].length;return t},g.getSceneInstancesCount=(e,t)=>{let s=0;const n=o.staticArray(o.evtTools.object.getSceneInstancesCount);t.keys(n);const i=new Set(n);for(const f of i)s+=e.getInstancesCountOnScene(f);return s},g.pickedObjectsCount=g.getPickedInstancesCount})(w=O.object||(O.object={}))})(y=o.evtTools||(o.evtTools={}));class C{constructor(){this.objectsLists=new Map;this.localVariablesContainers=[];this.callbacks=new Map;this.parent=null}static from(O){const h=new C;return h.parent=O,h}getOrCreateList(O){return this.objectsLists.has(O)||this.objectsLists.set(O,[]),this.objectsLists.get(O)}getObjects(O){return!this.objectsLists.has(O)&&this.parent?this.parent.getObjects(O):this.objectsLists.get(O)||[]}addObject(O,h){const m=this.getOrCreateList(O);if(m.includes(h))return;m.push(h);const v=()=>this.removeObject(O,h);this.callbacks.set(h,v),h.registerDestroyCallback(v)}removeObject(O,h){const m=this.getOrCreateList(O),v=m.indexOf(h);v!==-1&&(m.splice(v,1),h.unregisterDestroyCallback(this.callbacks.get(h)),this.callbacks.delete(h))}restoreLocalVariablesContainers(O){o.copyArray(this.localVariablesContainers,O)}backupLocalVariablesContainers(O){o.copyArray(O,this.localVariablesContainers)}}o.LongLivedObjectsList=C})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=objecttools.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../GDevelop/GDJS/Runtime/events-tools/objecttools.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 export namespace evtTools {\n export namespace object {\n /**\n * Keep only the specified object in the lists of picked objects.\n *\n * @param objectsLists The lists of objects to trim\n * @param runtimeObject The object to keep in the lists\n */\n export const pickOnly = function (\n objectsLists: ObjectsLists,\n runtimeObject: gdjs.RuntimeObject\n ) {\n for (const listName in objectsLists.items) {\n if (objectsLists.items.hasOwnProperty(listName)) {\n const list = objectsLists.items[listName];\n\n //Be sure not to lose the reference to the original array\n if (list.indexOf(runtimeObject) === -1) {\n list.length = 0;\n } else {\n list.length = 0;\n\n //Be sure not to lose the reference to the original array\n list.push(runtimeObject);\n }\n }\n }\n };\n\n /**\n * Do a test on two tables of objects so as to pick only the pair of objects for which the test is true.\n *\n * Note that the predicate method is not called strictly for each pair: When considering a pair of objects, if\n * these objects have already been marked as picked, the predicate method won't be called again.\n *\n * Cost (Worst case, predicate being always false):\n * Cost(Setting property 'picked' of NbObjList1+NbObjList2 objects to false)\n * + Cost(predicate)*NbObjList1*NbObjList2\n * + Cost(Testing NbObjList1+NbObjList2 booleans)\n * + Cost(Removing NbObjList1+NbObjList2 objects from all the lists)\n *\n * Cost (Best case, predicate being always true):\n * Cost(Setting property 'picked' of NbObjList1+NbObjList2 objects to false)\n * + Cost(predicate)*(NbObjList1+NbObjList2)\n * + Cost(Testing NbObjList1+NbObjList2 booleans)\n *\n *\n * @param predicate The predicate function is called with the two objects to compare, and an optional argument `extraArg`\n * @param objectsLists1 The first lists of objects\n * @param objectsLists2 The second lists of objects\n * @param inverted If `inverted` == true, only the objects of the first table are filtered.\n * @param extraArg (optional) This argument should be used to avoid declaring the predicate as a closure that would be created and destroyed at each call to twoListsTest (potentially multiple time per frame).\n */\n export const twoListsTest = function (\n predicate: (\n object1: gdjs.RuntimeObject,\n object2: gdjs.RuntimeObject,\n extraArg: any\n ) => boolean,\n objectsLists1: ObjectsLists,\n objectsLists2: ObjectsLists,\n inverted: boolean,\n extraArg: any\n ) {\n let isTrue = false;\n const objects1Lists = gdjs.staticArray(\n gdjs.evtTools.object.twoListsTest\n );\n objectsLists1.values(objects1Lists);\n const objects2Lists = gdjs.staticArray2(\n gdjs.evtTools.object.twoListsTest\n );\n objectsLists2.values(objects2Lists);\n for (let i = 0, leni = objects1Lists.length; i < leni; ++i) {\n let arr = objects1Lists[i];\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n arr[k].pick = false;\n }\n }\n for (let i = 0, leni = objects2Lists.length; i < leni; ++i) {\n let arr = objects2Lists[i];\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n arr[k].pick = false;\n }\n }\n\n //Launch the function for each object of the first list with each object\n //of the second list.\n for (let i = 0, leni = objects1Lists.length; i < leni; ++i) {\n const arr1 = objects1Lists[i];\n for (let k = 0, lenk = arr1.length; k < lenk; ++k) {\n let atLeastOneObject = false;\n for (let j = 0, lenj = objects2Lists.length; j < lenj; ++j) {\n const arr2 = objects2Lists[j];\n for (let l = 0, lenl = arr2.length; l < lenl; ++l) {\n if (arr1[k].pick && arr2[l].pick) {\n continue;\n }\n\n //Avoid unnecessary costly call to predicate.\n if (\n arr1[k].id !== arr2[l].id &&\n predicate(arr1[k], arr2[l], extraArg)\n ) {\n if (!inverted) {\n isTrue = true;\n\n //Pick the objects\n arr1[k].pick = true;\n arr2[l].pick = true;\n }\n atLeastOneObject = true;\n }\n }\n }\n if (!atLeastOneObject && inverted) {\n //For example, the object is not overlapping any other object.\n isTrue = true;\n arr1[k].pick = true;\n }\n }\n }\n\n //Trim not picked objects from lists.\n for (let i = 0, leni = objects1Lists.length; i < leni; ++i) {\n let arr = objects1Lists[i];\n let finalSize = 0;\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n let obj = arr[k];\n if (arr[k].pick) {\n arr[finalSize] = obj;\n finalSize++;\n }\n }\n arr.length = finalSize;\n }\n if (!inverted) {\n for (let i = 0, leni = objects2Lists.length; i < leni; ++i) {\n let arr = objects2Lists[i];\n let finalSize = 0;\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n let obj = arr[k];\n if (arr[k].pick) {\n arr[finalSize] = obj;\n finalSize++;\n }\n }\n arr.length = finalSize;\n }\n }\n return isTrue;\n };\n\n /**\n * Filter objects to keep only the one that fullfil the predicate\n *\n * Objects that do not fullfil the predicate are removed from objects lists.\n *\n * @param predicate The function applied to each object: must return true if the object fulfill the predicate.\n * @param objectsLists The lists of objects to trim\n * @param negatePredicate If set to true, the result of the predicate is negated.\n * @param extraArg Argument passed to the predicate (along with the object). Useful for avoiding relying on temporary closures.\n * @return true if at least one object fulfill the predicate.\n */\n export const pickObjectsIf = function (\n predicate: Function,\n objectsLists: ObjectsLists,\n negatePredicate: boolean,\n extraArg: any\n ): boolean {\n let isTrue = false;\n const lists = gdjs.staticArray(gdjs.evtTools.object.pickObjectsIf);\n objectsLists.values(lists);\n\n // Pick only objects that are fulfilling the predicate.\n for (let i = 0, leni = lists.length; i < leni; ++i) {\n const arr = lists[i];\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n const object = arr[k];\n // @ts-ignore\n if (negatePredicate ^ predicate(object, extraArg)) {\n isTrue = true;\n object.pick = true;\n } else {\n object.pick = false;\n }\n }\n }\n\n // Trim not picked objects from lists.\n for (let i = 0, leni = lists.length; i < leni; ++i) {\n gdjs.evtTools.object.filterPickedObjectsList(lists[i]);\n }\n return isTrue;\n };\n\n /**\n * Filter in-place the specified array to remove objects for which\n * `pick` property is set to false.\n */\n export const filterPickedObjectsList = function (\n arr: gdjs.RuntimeObject[]\n ) {\n let finalSize = 0;\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n const obj = arr[k];\n if (obj.pick) {\n arr[finalSize] = obj;\n finalSize++;\n }\n }\n arr.length = finalSize;\n };\n\n export const hitBoxesCollisionTest = function (\n objectsLists1: ObjectsLists,\n objectsLists2: ObjectsLists,\n inverted: boolean,\n instanceContainer: gdjs.RuntimeInstanceContainer,\n ignoreTouchingEdges: boolean\n ) {\n return gdjs.evtTools.object.twoListsTest(\n gdjs.RuntimeObject.collisionTest,\n objectsLists1,\n objectsLists2,\n inverted,\n ignoreTouchingEdges\n );\n };\n\n export const _distanceBetweenObjects = function (obj1, obj2, distance) {\n return obj1.getSqDistanceToObject(obj2) <= distance;\n };\n\n export const distanceTest = function (\n objectsLists1: ObjectsLists,\n objectsLists2: ObjectsLists,\n distance: float,\n inverted: boolean\n ) {\n return gdjs.evtTools.object.twoListsTest(\n gdjs.evtTools.object._distanceBetweenObjects,\n objectsLists1,\n objectsLists2,\n inverted,\n distance * distance\n );\n };\n\n export const _movesToward = function (obj1, obj2, tolerance) {\n if (obj1.hasNoForces()) {\n return false;\n }\n let objAngle = Math.atan2(\n obj2.getDrawableY() +\n obj2.getCenterY() -\n (obj1.getDrawableY() + obj1.getCenterY()),\n obj2.getDrawableX() +\n obj2.getCenterX() -\n (obj1.getDrawableX() + obj1.getCenterX())\n );\n objAngle *= 180 / 3.14159;\n return (\n Math.abs(\n gdjs.evtTools.common.angleDifference(\n obj1.getAverageForce().getAngle(),\n objAngle\n )\n ) <=\n tolerance / 2\n );\n };\n\n export const movesTowardTest = function (\n objectsLists1: ObjectsLists,\n objectsLists2: ObjectsLists,\n tolerance: float,\n inverted: boolean\n ) {\n return gdjs.evtTools.object.twoListsTest(\n gdjs.evtTools.object._movesToward,\n objectsLists1,\n objectsLists2,\n inverted,\n tolerance\n );\n };\n\n // Deprecated\n export const _turnedToward = function (obj1, obj2, tolerance) {\n let objAngle = Math.atan2(\n obj2.getDrawableY() +\n obj2.getCenterY() -\n (obj1.getDrawableY() + obj1.getCenterY()),\n obj2.getDrawableX() +\n obj2.getCenterX() -\n (obj1.getDrawableX() + obj1.getCenterX())\n );\n objAngle *= 180 / 3.14159;\n return (\n Math.abs(\n gdjs.evtTools.common.angleDifference(obj1.getAngle(), objAngle)\n ) <=\n tolerance / 2\n );\n };\n\n // Deprecated\n export const turnedTowardTest = function (\n objectsLists1,\n objectsLists2,\n tolerance,\n inverted\n ) {\n return gdjs.evtTools.object.twoListsTest(\n gdjs.evtTools.object._turnedToward,\n objectsLists1,\n objectsLists2,\n inverted,\n tolerance\n );\n };\n\n export const _isTurnedTowardObject = function (\n obj1: gdjs.RuntimeObject,\n obj2: gdjs.RuntimeObject,\n tolerance: float\n ) {\n return (\n Math.abs(\n gdjs.evtTools.common.angleDifference(\n obj1.getAngle(),\n obj1.getAngleToObject(obj2)\n )\n ) <= tolerance\n );\n };\n\n export const isTurnedTowardObject = function (\n objectsLists1: ObjectsLists,\n objectsLists2: ObjectsLists,\n tolerance: float,\n inverted: boolean\n ) {\n return gdjs.evtTools.object.twoListsTest(\n gdjs.evtTools.object._isTurnedTowardObject,\n objectsLists1,\n objectsLists2,\n inverted,\n tolerance\n );\n };\n\n export const pickAllObjects = function (objectsContext, objectsLists) {\n for (const name in objectsLists.items) {\n if (objectsLists.items.hasOwnProperty(name)) {\n const allObjects = objectsContext.getObjects(name);\n const objectsList = objectsLists.items[name];\n objectsList.length = 0;\n objectsList.push.apply(objectsList, allObjects);\n }\n }\n return true;\n };\n\n export const pickRandomObject = function (\n instanceContainer: gdjs.RuntimeInstanceContainer,\n objectsLists: ObjectsLists\n ) {\n // Compute one many objects we have\n let objectsCount = 0;\n for (let listName in objectsLists.items) {\n if (objectsLists.items.hasOwnProperty(listName)) {\n let list = objectsLists.items[listName];\n objectsCount += list.length;\n }\n }\n if (objectsCount === 0) {\n return false;\n }\n\n // Pick one random object\n let index = Math.floor(Math.random() * objectsCount);\n if (index >= objectsCount) {\n index = objectsCount - 1;\n }\n\n //Should never happen.\n\n // Find the object\n let startIndex = 0;\n let theChosenOne: gdjs.RuntimeObject | null = null;\n for (let listName in objectsLists.items) {\n if (objectsLists.items.hasOwnProperty(listName)) {\n let list = objectsLists.items[listName];\n if (index - startIndex < list.length) {\n theChosenOne = list[index - startIndex];\n break;\n }\n startIndex += list.length;\n }\n }\n // @ts-ignore\n gdjs.evtTools.object.pickOnly(objectsLists, theChosenOne);\n return true;\n };\n\n export const pickNearestObject = function (objectsLists, x, y, inverted) {\n let bestObject = null;\n let best = 0;\n let first = true;\n const lists = gdjs.staticArray(gdjs.evtTools.object.pickNearestObject);\n objectsLists.values(lists);\n for (let i = 0, len = lists.length; i < len; ++i) {\n const list = lists[i];\n for (let j = 0; j < list.length; ++j) {\n const object = list[j];\n const distance = object.getSqDistanceToPosition(x, y);\n // @ts-ignore\n if (first || (distance < best) ^ inverted) {\n best = distance;\n bestObject = object;\n }\n first = false;\n }\n }\n if (!bestObject) {\n return false;\n }\n gdjs.evtTools.object.pickOnly(objectsLists, bestObject);\n return true;\n };\n\n export const raycastObject = function (\n objectsLists: ObjectsLists,\n x: float,\n y: float,\n angle: float,\n dist: float,\n varX: gdjs.Variable,\n varY: gdjs.Variable,\n inverted: boolean\n ) {\n return gdjs.evtTools.object.raycastObjectToPosition(\n objectsLists,\n x,\n y,\n x + dist * Math.cos((angle * Math.PI) / 180.0),\n y + dist * Math.sin((angle * Math.PI) / 180.0),\n varX,\n varY,\n inverted\n );\n };\n\n export const raycastObjectToPosition = function (\n objectsLists: ObjectsLists,\n x: float,\n y: float,\n endX: float,\n endY: float,\n varX: gdjs.Variable,\n varY: gdjs.Variable,\n inverted: boolean\n ) {\n let matchObject: gdjs.RuntimeObject | null = null;\n let testSqDist = inverted\n ? 0\n : (endX - x) * (endX - x) + (endY - y) * (endY - y);\n let resultX = 0;\n let resultY = 0;\n const lists: RuntimeObject[][] = gdjs.staticArray(\n gdjs.evtTools.object.raycastObjectToPosition\n );\n objectsLists.values(lists);\n for (let i = 0; i < lists.length; i++) {\n const list = lists[i];\n for (let j = 0; j < list.length; j++) {\n const object = list[j];\n const result = object.raycastTest(x, y, endX, endY, !inverted);\n if (result.collision) {\n if (!inverted && result.closeSqDist <= testSqDist) {\n testSqDist = result.closeSqDist;\n matchObject = object;\n resultX = result.closeX;\n resultY = result.closeY;\n } else {\n if (inverted && result.farSqDist >= testSqDist) {\n testSqDist = result.farSqDist;\n matchObject = object;\n resultX = result.farX;\n resultY = result.farY;\n }\n }\n }\n }\n }\n if (!matchObject) {\n return false;\n }\n gdjs.evtTools.object.pickOnly(objectsLists, matchObject);\n varX.setNumber(resultX);\n varY.setNumber(resultY);\n return true;\n };\n\n /**\n * Do the work of creating a new object\n */\n export const doCreateObjectOnScene = function (\n objectsContext: EventsFunctionContext | gdjs.RuntimeScene,\n objectName: string,\n objectsLists: ObjectsLists,\n x: float,\n y: float,\n layerName: string\n ): gdjs.RuntimeObject | null {\n // objectsContext will either be the gdjs.RuntimeScene or, in an events function, the\n // eventsFunctionContext. We can't directly use runtimeScene because the object name could\n // be different than the real object name (this is the case in a function. The eventsFunctionContext\n // will take care of this in createObject).\n const obj = objectsContext.createObject(objectName);\n const layer = objectsContext.getLayer(layerName);\n if (obj !== null) {\n //Do some extra setup\n obj.setPosition(x, y);\n obj.setLayer(layerName);\n obj.setZOrder(layer.getDefaultZOrder());\n\n //Let the new object be picked by next actions/conditions.\n if (objectsLists.containsKey(objectName)) {\n objectsLists.get(objectName).push(obj);\n }\n }\n return obj;\n };\n\n /**\n * Allows events to create a new object on a scene.\n */\n export const createObjectOnScene = function (\n objectsContext: EventsFunctionContext | gdjs.RuntimeScene,\n objectsLists: ObjectsLists,\n x: float,\n y: float,\n layerName: string\n ): gdjs.RuntimeObject | null {\n return gdjs.evtTools.object.doCreateObjectOnScene(\n objectsContext,\n objectsLists.firstKey() as string,\n objectsLists,\n x,\n y,\n layerName\n );\n };\n\n /**\n * Allows events to create a new object on a scene.\n */\n export const createObjectFromGroupOnScene = function (\n objectsContext: EventsFunctionContext | gdjs.RuntimeScene,\n objectsLists: ObjectsLists,\n objectName: string,\n x: float,\n y: float,\n layerName: string\n ) {\n gdjs.evtTools.object.doCreateObjectOnScene(\n objectsContext,\n objectName,\n objectsLists,\n x,\n y,\n layerName\n );\n };\n\n /**\n * Return the number of instances in the specified lists of objects.\n */\n export const getPickedInstancesCount = (objectsLists: ObjectsLists) => {\n let count = 0;\n const lists = gdjs.staticArray(\n gdjs.evtTools.object.getPickedInstancesCount\n );\n objectsLists.values(lists);\n for (let i = 0, len = lists.length; i < len; ++i) {\n count += lists[i].length;\n }\n return count;\n };\n\n /**\n * Return the number of instances of the specified objects living on the scene.\n */\n export const getSceneInstancesCount = (\n objectsContext: EventsFunctionContext | gdjs.RuntimeScene,\n objectsLists: ObjectsLists\n ) => {\n let count = 0;\n\n const objectNames = gdjs.staticArray(\n gdjs.evtTools.object.getSceneInstancesCount\n );\n objectsLists.keys(objectNames);\n\n const uniqueObjectNames = new Set(objectNames);\n for (const objectName of uniqueObjectNames) {\n count += objectsContext.getInstancesCountOnScene(objectName);\n }\n return count;\n };\n\n /** @deprecated */\n export const pickedObjectsCount = getPickedInstancesCount;\n }\n }\n\n /**\n * A container for objects lists that should last more than the current frame.\n * It automatically removes objects that were destroyed from the objects lists.\n */\n export class LongLivedObjectsList {\n private objectsLists = new Map<string, Array<RuntimeObject>>();\n private localVariablesContainers: Array<gdjs.VariablesContainer> = [];\n private callbacks = new Map<RuntimeObject, () => void>();\n private parent: LongLivedObjectsList | null = null;\n\n /**\n * Create a new container for objects lists, inheriting from another one. This is\n * useful should we get the objects that have not been saved in this context (using\n * `addObject`) but saved in a parent context.\n * This avoids to save all object lists every time we create a new `LongLivedObjectsList`,\n * despite not all objects lists being used.\n *\n * @param parent\n * @returns\n */\n static from(parent: LongLivedObjectsList): LongLivedObjectsList {\n const newList = new LongLivedObjectsList();\n newList.parent = parent;\n return newList;\n }\n\n private getOrCreateList(objectName: string): RuntimeObject[] {\n if (!this.objectsLists.has(objectName))\n this.objectsLists.set(objectName, []);\n return this.objectsLists.get(objectName)!;\n }\n\n getObjects(objectName: string): RuntimeObject[] {\n if (!this.objectsLists.has(objectName) && this.parent)\n return this.parent.getObjects(objectName);\n return this.objectsLists.get(objectName) || [];\n }\n\n addObject(objectName: string, runtimeObject: gdjs.RuntimeObject): void {\n const list = this.getOrCreateList(objectName);\n if (list.includes(runtimeObject)) return;\n list.push(runtimeObject);\n\n // Register callbacks for when the object is destroyed\n const onDestroy = () => this.removeObject(objectName, runtimeObject);\n this.callbacks.set(runtimeObject, onDestroy);\n runtimeObject.registerDestroyCallback(onDestroy);\n }\n\n removeObject(objectName: string, runtimeObject: gdjs.RuntimeObject): void {\n const list = this.getOrCreateList(objectName);\n const index = list.indexOf(runtimeObject);\n if (index === -1) return;\n list.splice(index, 1);\n\n // Properly remove callbacks to not leak the object\n runtimeObject.unregisterDestroyCallback(\n this.callbacks.get(runtimeObject)!\n );\n this.callbacks.delete(runtimeObject);\n }\n\n restoreLocalVariablesContainers(\n variablesContainers: Array<gdjs.VariablesContainer>\n ): void {\n gdjs.copyArray(this.localVariablesContainers, variablesContainers);\n }\n\n backupLocalVariablesContainers(\n variablesContainers: Array<gdjs.VariablesContainer>\n ): void {\n gdjs.copyArray(variablesContainers, this.localVariablesContainers);\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACS,GAAU,GAAV,UAAU,EAAV,CACE,GAAU,GAAV,UAAU,EAAV,CAOE,AAAM,WAAW,SACtB,EACA,EACA,CACA,SAAW,KAAY,GAAa,MAClC,GAAI,EAAa,MAAM,eAAe,GAAW,CAC/C,KAAM,GAAO,EAAa,MAAM,GAGhC,AAAI,EAAK,QAAQ,KAAmB,GAClC,EAAK,OAAS,EAEd,GAAK,OAAS,EAGd,EAAK,KAAK,MA8BL,eAAe,SAC1B,EAKA,EACA,EACA,EACA,EACA,CACA,GAAI,GAAS,GACb,KAAM,GAAgB,EAAK,YACzB,EAAK,SAAS,OAAO,cAEvB,EAAc,OAAO,GACrB,KAAM,GAAgB,EAAK,aACzB,EAAK,SAAS,OAAO,cAEvB,EAAc,OAAO,GACrB,OAAS,GAAI,EAAG,EAAO,EAAc,OAAQ,EAAI,EAAM,EAAE,EAAG,CAC1D,GAAI,GAAM,EAAc,GACxB,OAAS,GAAI,EAAG,EAAO,EAAI,OAAQ,EAAI,EAAM,EAAE,EAC7C,EAAI,GAAG,KAAO,GAGlB,OAAS,GAAI,EAAG,EAAO,EAAc,OAAQ,EAAI,EAAM,EAAE,EAAG,CAC1D,GAAI,GAAM,EAAc,GACxB,OAAS,GAAI,EAAG,EAAO,EAAI,OAAQ,EAAI,EAAM,EAAE,EAC7C,EAAI,GAAG,KAAO,GAMlB,OAAS,GAAI,EAAG,EAAO,EAAc,OAAQ,EAAI,EAAM,EAAE,EAAG,CAC1D,KAAM,GAAO,EAAc,GAC3B,OAAS,GAAI,EAAG,EAAO,EAAK,OAAQ,EAAI,EAAM,EAAE,EAAG,CACjD,GAAI,GAAmB,GACvB,OAAS,GAAI,EAAG,EAAO,EA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H,EAAK,aACJ,GAAK,eAAiB,EAAK,eAEhC,UAAY,IAAM,QAEhB,KAAK,IACH,EAAK,SAAS,OAAO,gBAAgB,EAAK,WAAY,KAExD,EAAY,GAKH,mBAAmB,SAC9B,EACA,EACA,EACA,EACA,CACA,MAAO,GAAK,SAAS,OAAO,aAC1B,EAAK,SAAS,OAAO,cACrB,EACA,EACA,EACA,IAIS,wBAAwB,SACnC,EACA,EACA,EACA,CACA,MACE,MAAK,IACH,EAAK,SAAS,OAAO,gBACnB,EAAK,WACL,EAAK,iBAAiB,MAErB,GAII,uBAAuB,SAClC,EACA,EACA,EACA,EACA,CACA,MAAO,GAAK,SAAS,OAAO,aAC1B,EAAK,SAAS,OAAO,sBACrB,EACA,EACA,EACA,IAIS,iBAAiB,SAAU,EAAgB,EAAc,CACpE,SAAW,KAAQ,GAAa,MAC9B,GAAI,EAAa,MAAM,eAAe,GAAO,CAC3C,KAAM,GAAa,EAAe,WAAW,GACvC,EAAc,EAAa,MAAM,GACvC,
|
|
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 export namespace evtTools {\n export namespace object {\n /**\n * Keep only the specified object in the lists of picked objects.\n *\n * @param objectsLists The lists of objects to trim\n * @param runtimeObject The object to keep in the lists\n */\n export const pickOnly = function (\n objectsLists: ObjectsLists,\n runtimeObject: gdjs.RuntimeObject\n ) {\n for (const listName in objectsLists.items) {\n if (objectsLists.items.hasOwnProperty(listName)) {\n const list = objectsLists.items[listName];\n\n //Be sure not to lose the reference to the original array\n if (list.indexOf(runtimeObject) === -1) {\n list.length = 0;\n } else {\n list.length = 0;\n\n //Be sure not to lose the reference to the original array\n list.push(runtimeObject);\n }\n }\n }\n };\n\n /**\n * Do a test on two tables of objects so as to pick only the pair of objects for which the test is true.\n *\n * Note that the predicate method is not called strictly for each pair: When considering a pair of objects, if\n * these objects have already been marked as picked, the predicate method won't be called again.\n *\n * Cost (Worst case, predicate being always false):\n * Cost(Setting property 'picked' of NbObjList1+NbObjList2 objects to false)\n * + Cost(predicate)*NbObjList1*NbObjList2\n * + Cost(Testing NbObjList1+NbObjList2 booleans)\n * + Cost(Removing NbObjList1+NbObjList2 objects from all the lists)\n *\n * Cost (Best case, predicate being always true):\n * Cost(Setting property 'picked' of NbObjList1+NbObjList2 objects to false)\n * + Cost(predicate)*(NbObjList1+NbObjList2)\n * + Cost(Testing NbObjList1+NbObjList2 booleans)\n *\n *\n * @param predicate The predicate function is called with the two objects to compare, and an optional argument `extraArg`\n * @param objectsLists1 The first lists of objects\n * @param objectsLists2 The second lists of objects\n * @param inverted If `inverted` == true, only the objects of the first table are filtered.\n * @param extraArg (optional) This argument should be used to avoid declaring the predicate as a closure that would be created and destroyed at each call to twoListsTest (potentially multiple time per frame).\n */\n export const twoListsTest = function (\n predicate: (\n object1: gdjs.RuntimeObject,\n object2: gdjs.RuntimeObject,\n extraArg: any\n ) => boolean,\n objectsLists1: ObjectsLists,\n objectsLists2: ObjectsLists,\n inverted: boolean,\n extraArg: any\n ) {\n let isTrue = false;\n const objects1Lists = gdjs.staticArray(\n gdjs.evtTools.object.twoListsTest\n );\n objectsLists1.values(objects1Lists);\n const objects2Lists = gdjs.staticArray2(\n gdjs.evtTools.object.twoListsTest\n );\n objectsLists2.values(objects2Lists);\n for (let i = 0, leni = objects1Lists.length; i < leni; ++i) {\n let arr = objects1Lists[i];\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n arr[k].pick = false;\n }\n }\n for (let i = 0, leni = objects2Lists.length; i < leni; ++i) {\n let arr = objects2Lists[i];\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n arr[k].pick = false;\n }\n }\n\n //Launch the function for each object of the first list with each object\n //of the second list.\n for (let i = 0, leni = objects1Lists.length; i < leni; ++i) {\n const arr1 = objects1Lists[i];\n for (let k = 0, lenk = arr1.length; k < lenk; ++k) {\n let atLeastOneObject = false;\n for (let j = 0, lenj = objects2Lists.length; j < lenj; ++j) {\n const arr2 = objects2Lists[j];\n for (let l = 0, lenl = arr2.length; l < lenl; ++l) {\n if (arr1[k].pick && arr2[l].pick) {\n continue;\n }\n\n //Avoid unnecessary costly call to predicate.\n if (\n arr1[k].id !== arr2[l].id &&\n predicate(arr1[k], arr2[l], extraArg)\n ) {\n if (!inverted) {\n isTrue = true;\n\n //Pick the objects\n arr1[k].pick = true;\n arr2[l].pick = true;\n }\n atLeastOneObject = true;\n }\n }\n }\n if (!atLeastOneObject && inverted) {\n //For example, the object is not overlapping any other object.\n isTrue = true;\n arr1[k].pick = true;\n }\n }\n }\n\n //Trim not picked objects from lists.\n for (let i = 0, leni = objects1Lists.length; i < leni; ++i) {\n let arr = objects1Lists[i];\n let finalSize = 0;\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n let obj = arr[k];\n if (arr[k].pick) {\n arr[finalSize] = obj;\n finalSize++;\n }\n }\n arr.length = finalSize;\n }\n if (!inverted) {\n for (let i = 0, leni = objects2Lists.length; i < leni; ++i) {\n let arr = objects2Lists[i];\n let finalSize = 0;\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n let obj = arr[k];\n if (arr[k].pick) {\n arr[finalSize] = obj;\n finalSize++;\n }\n }\n arr.length = finalSize;\n }\n }\n return isTrue;\n };\n\n /**\n * Filter objects to keep only the one that fullfil the predicate\n *\n * Objects that do not fullfil the predicate are removed from objects lists.\n *\n * @param predicate The function applied to each object: must return true if the object fulfill the predicate.\n * @param objectsLists The lists of objects to trim\n * @param negatePredicate If set to true, the result of the predicate is negated.\n * @param extraArg Argument passed to the predicate (along with the object). Useful for avoiding relying on temporary closures.\n * @return true if at least one object fulfill the predicate.\n */\n export const pickObjectsIf = function (\n predicate: Function,\n objectsLists: ObjectsLists,\n negatePredicate: boolean,\n extraArg: any\n ): boolean {\n let isTrue = false;\n const lists = gdjs.staticArray(gdjs.evtTools.object.pickObjectsIf);\n objectsLists.values(lists);\n\n // Pick only objects that are fulfilling the predicate.\n for (let i = 0, leni = lists.length; i < leni; ++i) {\n const arr = lists[i];\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n const object = arr[k];\n // @ts-ignore\n if (negatePredicate ^ predicate(object, extraArg)) {\n isTrue = true;\n object.pick = true;\n } else {\n object.pick = false;\n }\n }\n }\n\n // Trim not picked objects from lists.\n for (let i = 0, leni = lists.length; i < leni; ++i) {\n gdjs.evtTools.object.filterPickedObjectsList(lists[i]);\n }\n return isTrue;\n };\n\n /**\n * Filter in-place the specified array to remove objects for which\n * `pick` property is set to false.\n */\n export const filterPickedObjectsList = function (\n arr: gdjs.RuntimeObject[]\n ) {\n let finalSize = 0;\n for (let k = 0, lenk = arr.length; k < lenk; ++k) {\n const obj = arr[k];\n if (obj.pick) {\n arr[finalSize] = obj;\n finalSize++;\n }\n }\n arr.length = finalSize;\n };\n\n export const hitBoxesCollisionTest = function (\n objectsLists1: ObjectsLists,\n objectsLists2: ObjectsLists,\n inverted: boolean,\n instanceContainer: gdjs.RuntimeInstanceContainer,\n ignoreTouchingEdges: boolean\n ) {\n return gdjs.evtTools.object.twoListsTest(\n gdjs.RuntimeObject.collisionTest,\n objectsLists1,\n objectsLists2,\n inverted,\n ignoreTouchingEdges\n );\n };\n\n export const _distanceBetweenObjects = function (obj1, obj2, distance) {\n return obj1.getSqDistanceToObject(obj2) <= distance;\n };\n\n export const distanceTest = function (\n objectsLists1: ObjectsLists,\n objectsLists2: ObjectsLists,\n distance: float,\n inverted: boolean\n ) {\n return gdjs.evtTools.object.twoListsTest(\n gdjs.evtTools.object._distanceBetweenObjects,\n objectsLists1,\n objectsLists2,\n inverted,\n distance * distance\n );\n };\n\n export const _movesToward = function (obj1, obj2, tolerance) {\n if (obj1.hasNoForces()) {\n return false;\n }\n let objAngle = Math.atan2(\n obj2.getDrawableY() +\n obj2.getCenterY() -\n (obj1.getDrawableY() + obj1.getCenterY()),\n obj2.getDrawableX() +\n obj2.getCenterX() -\n (obj1.getDrawableX() + obj1.getCenterX())\n );\n objAngle *= 180 / 3.14159;\n return (\n Math.abs(\n gdjs.evtTools.common.angleDifference(\n obj1.getAverageForce().getAngle(),\n objAngle\n )\n ) <=\n tolerance / 2\n );\n };\n\n export const movesTowardTest = function (\n objectsLists1: ObjectsLists,\n objectsLists2: ObjectsLists,\n tolerance: float,\n inverted: boolean\n ) {\n return gdjs.evtTools.object.twoListsTest(\n gdjs.evtTools.object._movesToward,\n objectsLists1,\n objectsLists2,\n inverted,\n tolerance\n );\n };\n\n // Deprecated\n export const _turnedToward = function (obj1, obj2, tolerance) {\n let objAngle = Math.atan2(\n obj2.getDrawableY() +\n obj2.getCenterY() -\n (obj1.getDrawableY() + obj1.getCenterY()),\n obj2.getDrawableX() +\n obj2.getCenterX() -\n (obj1.getDrawableX() + obj1.getCenterX())\n );\n objAngle *= 180 / 3.14159;\n return (\n Math.abs(\n gdjs.evtTools.common.angleDifference(obj1.getAngle(), objAngle)\n ) <=\n tolerance / 2\n );\n };\n\n // Deprecated\n export const turnedTowardTest = function (\n objectsLists1,\n objectsLists2,\n tolerance,\n inverted\n ) {\n return gdjs.evtTools.object.twoListsTest(\n gdjs.evtTools.object._turnedToward,\n objectsLists1,\n objectsLists2,\n inverted,\n tolerance\n );\n };\n\n export const _isTurnedTowardObject = function (\n obj1: gdjs.RuntimeObject,\n obj2: gdjs.RuntimeObject,\n tolerance: float\n ) {\n return (\n Math.abs(\n gdjs.evtTools.common.angleDifference(\n obj1.getAngle(),\n obj1.getAngleToObject(obj2)\n )\n ) <= tolerance\n );\n };\n\n export const isTurnedTowardObject = function (\n objectsLists1: ObjectsLists,\n objectsLists2: ObjectsLists,\n tolerance: float,\n inverted: boolean\n ) {\n return gdjs.evtTools.object.twoListsTest(\n gdjs.evtTools.object._isTurnedTowardObject,\n objectsLists1,\n objectsLists2,\n inverted,\n tolerance\n );\n };\n\n export const pickAllObjects = function (objectsContext, objectsLists) {\n for (const name in objectsLists.items) {\n if (objectsLists.items.hasOwnProperty(name)) {\n const allObjects = objectsContext.getObjects(name);\n const objectsList = objectsLists.items[name];\n gdjs.copyArray(allObjects, objectsList);\n }\n }\n return true;\n };\n\n export const pickRandomObject = function (\n instanceContainer: gdjs.RuntimeInstanceContainer,\n objectsLists: ObjectsLists\n ) {\n // Compute one many objects we have\n let objectsCount = 0;\n for (let listName in objectsLists.items) {\n if (objectsLists.items.hasOwnProperty(listName)) {\n let list = objectsLists.items[listName];\n objectsCount += list.length;\n }\n }\n if (objectsCount === 0) {\n return false;\n }\n\n // Pick one random object\n let index = Math.floor(Math.random() * objectsCount);\n if (index >= objectsCount) {\n index = objectsCount - 1;\n }\n\n //Should never happen.\n\n // Find the object\n let startIndex = 0;\n let theChosenOne: gdjs.RuntimeObject | null = null;\n for (let listName in objectsLists.items) {\n if (objectsLists.items.hasOwnProperty(listName)) {\n let list = objectsLists.items[listName];\n if (index - startIndex < list.length) {\n theChosenOne = list[index - startIndex];\n break;\n }\n startIndex += list.length;\n }\n }\n // @ts-ignore\n gdjs.evtTools.object.pickOnly(objectsLists, theChosenOne);\n return true;\n };\n\n export const pickNearestObject = function (objectsLists, x, y, inverted) {\n let bestObject = null;\n let best = 0;\n let first = true;\n const lists = gdjs.staticArray(gdjs.evtTools.object.pickNearestObject);\n objectsLists.values(lists);\n for (let i = 0, len = lists.length; i < len; ++i) {\n const list = lists[i];\n for (let j = 0; j < list.length; ++j) {\n const object = list[j];\n const distance = object.getSqDistanceToPosition(x, y);\n // @ts-ignore\n if (first || (distance < best) ^ inverted) {\n best = distance;\n bestObject = object;\n }\n first = false;\n }\n }\n if (!bestObject) {\n return false;\n }\n gdjs.evtTools.object.pickOnly(objectsLists, bestObject);\n return true;\n };\n\n export const raycastObject = function (\n objectsLists: ObjectsLists,\n x: float,\n y: float,\n angle: float,\n dist: float,\n varX: gdjs.Variable,\n varY: gdjs.Variable,\n inverted: boolean\n ) {\n return gdjs.evtTools.object.raycastObjectToPosition(\n objectsLists,\n x,\n y,\n x + dist * Math.cos((angle * Math.PI) / 180.0),\n y + dist * Math.sin((angle * Math.PI) / 180.0),\n varX,\n varY,\n inverted\n );\n };\n\n export const raycastObjectToPosition = function (\n objectsLists: ObjectsLists,\n x: float,\n y: float,\n endX: float,\n endY: float,\n varX: gdjs.Variable,\n varY: gdjs.Variable,\n inverted: boolean\n ) {\n let matchObject: gdjs.RuntimeObject | null = null;\n let testSqDist = inverted\n ? 0\n : (endX - x) * (endX - x) + (endY - y) * (endY - y);\n let resultX = 0;\n let resultY = 0;\n const lists: RuntimeObject[][] = gdjs.staticArray(\n gdjs.evtTools.object.raycastObjectToPosition\n );\n objectsLists.values(lists);\n for (let i = 0; i < lists.length; i++) {\n const list = lists[i];\n for (let j = 0; j < list.length; j++) {\n const object = list[j];\n const result = object.raycastTest(x, y, endX, endY, !inverted);\n if (result.collision) {\n if (!inverted && result.closeSqDist <= testSqDist) {\n testSqDist = result.closeSqDist;\n matchObject = object;\n resultX = result.closeX;\n resultY = result.closeY;\n } else {\n if (inverted && result.farSqDist >= testSqDist) {\n testSqDist = result.farSqDist;\n matchObject = object;\n resultX = result.farX;\n resultY = result.farY;\n }\n }\n }\n }\n }\n if (!matchObject) {\n return false;\n }\n gdjs.evtTools.object.pickOnly(objectsLists, matchObject);\n varX.setNumber(resultX);\n varY.setNumber(resultY);\n return true;\n };\n\n /**\n * Do the work of creating a new object\n */\n export const doCreateObjectOnScene = function (\n objectsContext: EventsFunctionContext | gdjs.RuntimeScene,\n objectName: string,\n objectsLists: ObjectsLists,\n x: float,\n y: float,\n layerName: string\n ): gdjs.RuntimeObject | null {\n // objectsContext will either be the gdjs.RuntimeScene or, in an events function, the\n // eventsFunctionContext. We can't directly use runtimeScene because the object name could\n // be different than the real object name (this is the case in a function. The eventsFunctionContext\n // will take care of this in createObject).\n const obj = objectsContext.createObject(objectName);\n const layer = objectsContext.getLayer(layerName);\n if (obj !== null) {\n //Do some extra setup\n obj.setPosition(x, y);\n obj.setLayer(layerName);\n obj.setZOrder(layer.getDefaultZOrder());\n\n //Let the new object be picked by next actions/conditions.\n if (objectsLists.containsKey(objectName)) {\n objectsLists.get(objectName).push(obj);\n }\n }\n return obj;\n };\n\n /**\n * Allows events to create a new object on a scene.\n */\n export const createObjectOnScene = function (\n objectsContext: EventsFunctionContext | gdjs.RuntimeScene,\n objectsLists: ObjectsLists,\n x: float,\n y: float,\n layerName: string\n ): gdjs.RuntimeObject | null {\n return gdjs.evtTools.object.doCreateObjectOnScene(\n objectsContext,\n objectsLists.firstKey() as string,\n objectsLists,\n x,\n y,\n layerName\n );\n };\n\n /**\n * Allows events to create a new object on a scene.\n */\n export const createObjectFromGroupOnScene = function (\n objectsContext: EventsFunctionContext | gdjs.RuntimeScene,\n objectsLists: ObjectsLists,\n objectName: string,\n x: float,\n y: float,\n layerName: string\n ) {\n gdjs.evtTools.object.doCreateObjectOnScene(\n objectsContext,\n objectName,\n objectsLists,\n x,\n y,\n layerName\n );\n };\n\n /**\n * Return the number of instances in the specified lists of objects.\n */\n export const getPickedInstancesCount = (objectsLists: ObjectsLists) => {\n let count = 0;\n const lists = gdjs.staticArray(\n gdjs.evtTools.object.getPickedInstancesCount\n );\n objectsLists.values(lists);\n for (let i = 0, len = lists.length; i < len; ++i) {\n count += lists[i].length;\n }\n return count;\n };\n\n /**\n * Return the number of instances of the specified objects living on the scene.\n */\n export const getSceneInstancesCount = (\n objectsContext: EventsFunctionContext | gdjs.RuntimeScene,\n objectsLists: ObjectsLists\n ) => {\n let count = 0;\n\n const objectNames = gdjs.staticArray(\n gdjs.evtTools.object.getSceneInstancesCount\n );\n objectsLists.keys(objectNames);\n\n const uniqueObjectNames = new Set(objectNames);\n for (const objectName of uniqueObjectNames) {\n count += objectsContext.getInstancesCountOnScene(objectName);\n }\n return count;\n };\n\n /** @deprecated */\n export const pickedObjectsCount = getPickedInstancesCount;\n }\n }\n\n /**\n * A container for objects lists that should last more than the current frame.\n * It automatically removes objects that were destroyed from the objects lists.\n */\n export class LongLivedObjectsList {\n private objectsLists = new Map<string, Array<RuntimeObject>>();\n private localVariablesContainers: Array<gdjs.VariablesContainer> = [];\n private callbacks = new Map<RuntimeObject, () => void>();\n private parent: LongLivedObjectsList | null = null;\n\n /**\n * Create a new container for objects lists, inheriting from another one. This is\n * useful should we get the objects that have not been saved in this context (using\n * `addObject`) but saved in a parent context.\n * This avoids to save all object lists every time we create a new `LongLivedObjectsList`,\n * despite not all objects lists being used.\n *\n * @param parent\n * @returns\n */\n static from(parent: LongLivedObjectsList): LongLivedObjectsList {\n const newList = new LongLivedObjectsList();\n newList.parent = parent;\n return newList;\n }\n\n private getOrCreateList(objectName: string): RuntimeObject[] {\n if (!this.objectsLists.has(objectName))\n this.objectsLists.set(objectName, []);\n return this.objectsLists.get(objectName)!;\n }\n\n getObjects(objectName: string): RuntimeObject[] {\n if (!this.objectsLists.has(objectName) && this.parent)\n return this.parent.getObjects(objectName);\n return this.objectsLists.get(objectName) || [];\n }\n\n addObject(objectName: string, runtimeObject: gdjs.RuntimeObject): void {\n const list = this.getOrCreateList(objectName);\n if (list.includes(runtimeObject)) return;\n list.push(runtimeObject);\n\n // Register callbacks for when the object is destroyed\n const onDestroy = () => this.removeObject(objectName, runtimeObject);\n this.callbacks.set(runtimeObject, onDestroy);\n runtimeObject.registerDestroyCallback(onDestroy);\n }\n\n removeObject(objectName: string, runtimeObject: gdjs.RuntimeObject): void {\n const list = this.getOrCreateList(objectName);\n const index = list.indexOf(runtimeObject);\n if (index === -1) return;\n list.splice(index, 1);\n\n // Properly remove callbacks to not leak the object\n runtimeObject.unregisterDestroyCallback(\n this.callbacks.get(runtimeObject)!\n );\n this.callbacks.delete(runtimeObject);\n }\n\n restoreLocalVariablesContainers(\n variablesContainers: Array<gdjs.VariablesContainer>\n ): void {\n gdjs.copyArray(this.localVariablesContainers, variablesContainers);\n }\n\n backupLocalVariablesContainers(\n variablesContainers: Array<gdjs.VariablesContainer>\n ): void {\n gdjs.copyArray(variablesContainers, this.localVariablesContainers);\n }\n }\n}\n"],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AI,CAAC,KAAK,aAAa,IAAI,IAAe,KAAK,OACtC,KAAK,OAAO,WAAW,GACzB,KAAK,aAAa,IAAI,IAAe,GAG9C,UAAU,EAAoB,EAAyC,CACrE,KAAM,GAAO,KAAK,gBAAgB,GAClC,GAAI,EAAK,SAAS,GAAgB,OAClC,EAAK,KAAK,GAGV,KAAM,GAAY,IAAM,KAAK,aAAa,EAAY,GACtD,KAAK,UAAU,IAAI,EAAe,GAClC,EAAc,wBAAwB,GAGxC,aAAa,EAAoB,EAAyC,CACxE,KAAM,GAAO,KAAK,gBAAgB,GAC5B,EAAQ,EAAK,QAAQ,GAC3B,AAAI,IAAU,IACd,GAAK,OAAO,EAAO,GAGnB,EAAc,0BACZ,KAAK,UAAU,IAAI,IAErB,KAAK,UAAU,OAAO,IAGxB,gCACE,EACM,CACN,EAAK,UAAU,KAAK,yBAA0B,GAGhD,+BACE,EACM,CACN,EAAK,UAAU,EAAqB,KAAK,2BAnEtC,EAAM,yBA/mBL",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(i){const s=new i.Logger("Font manager"),d=["font"];class
|
|
1
|
+
var gdjs;(function(i){const s=new i.Logger("Font manager"),d=["font"];class l{constructor(t){this._loadedFontFamily=new i.ResourceCache;this._loadedFontFamilySet=new Set;this._resourceLoader=t}getResourceKinds(){return d}getFontFamily(t){return this._loadedFontFamily.getFromName(t)||"Arial"}getFontFile(t){const e=this._resourceLoader.getResource(t);return e?e.file||"":t}_getFontFamilyFromFilename(t){let e="gdjs_font_"+t.file.toLowerCase().replace(/[^\w]/gi,"-");const n=e;let o=2;for(;this._loadedFontFamilySet.has(e);)e=e+"-"+o,o++;return n}_loadFont(t,e){const n={},o="url("+encodeURI(e)+")";if(typeof FontFace!="undefined")return fetch(this._resourceLoader.getFullUrl(e),{credentials:this._resourceLoader.checkIfCredentialsRequired(e)?"include":"same-origin"}).then(r=>{if(!r.ok){const a="Unable to fetch "+e+" to be loaded as a font. HTTP status is: "+r.status+".";throw s.error(a),new Error(a)}return r.arrayBuffer()}).then(r=>{const a=new FontFace(t,r,n);document.fonts.add(a)});{const r=document.createElement("style");return r.appendChild(document.createTextNode("@font-face { font-family: '"+t+"'; src: "+o+"; }")),document.head.appendChild(r),new FontFaceObserver(t,n).load()}}async processResource(t){}async loadResource(t){const e=this._resourceLoader.getResource(t);if(!e){s.warn('Unable to find font for resource "'+t+'".');return}if(this._loadedFontFamily.get(e))return;const n=e.file;if(!n)return;const o=this._getFontFamilyFromFilename(e);this._loadedFontFamily.set(e,o),this._loadedFontFamilySet.add(o);try{await this._loadFont(o,n)}catch(r){s.error('Error loading font resource "'+e.name+'" (file: '+n+"): "+(r.message||"Unknown error"))}}dispose(){this._loadedFontFamily.clear(),this._loadedFontFamilySet.clear()}unloadResourcesList(t){t.forEach(e=>{this._loadedFontFamily.get(e)&&this._loadedFontFamily.delete(e);const o=this._getFontFamilyFromFilename(e);o&&this._loadedFontFamilySet.delete(o)})}}i.FontFaceObserverFontManager=l,i.FontManager=l})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=fontfaceobserver-font-manager.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../GDevelop/GDJS/Runtime/fontfaceobserver-font-manager/fontfaceobserver-font-manager.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * GDevelop JS Platform\n * Copyright 2013-present 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('Font manager');\n\n const resourceKinds: Array<ResourceKind> = ['font'];\n\n /**\n * FontFaceObserverFontManager loads fonts (using `FontFace` or `fontfaceobserver` library)\n * from the game resources (see `loadFonts`), and allow to access to\n * the font families of the loaded fonts during the game (see `getFontFamily`).\n */\n export class FontFaceObserverFontManager implements gdjs.ResourceManager {\n _resourceLoader: gdjs.ResourceLoader;\n // Associate font resource names to the loaded font family\n _loadedFontFamily = new gdjs.ResourceCache<string>();\n _loadedFontFamilySet = new Set<string>();\n\n /**\n * @param resourceLoader The resources loader of the game.\n */\n constructor(resourceLoader: gdjs.ResourceLoader) {\n this._resourceLoader = resourceLoader;\n }\n\n getResourceKinds(): ResourceKind[] {\n return resourceKinds;\n }\n\n /**\n * Return the font family associated to the specified font resource name.\n * The font resource must have been loaded before. If that's not the case,\n * a default font family will be returned (\"Arial\").\n *\n * @param resourceName The name of the resource to get.\n * @returns The font family to be used for this font resource,\n * or \"Arial\" if not loaded.\n */\n getFontFamily(resourceName: string): string {\n return this._loadedFontFamily.getFromName(resourceName) || 'Arial';\n }\n\n /**\n * Return the font file associated to the specified font resource name.\n * The font resource must have been loaded before. If that's not the case,\n * the resource name will be returned (to\n * keep compatibility with GDevelop 5.0-beta56 and previous).\n *\n * Should only be useful for renderers running on a non HTML5/non browser environment.\n *\n * @param resourceName The name of the resource to get.\n * @returns The file of the font resource.\n */\n getFontFile(resourceName: string): string {\n const resource = this._resourceLoader.getResource(resourceName);\n return resource ? resource.file || '' : resourceName;\n }\n\n /**\n * Return the font family to use for a given filename.\n * Each filename is guaranteed to have a unique font family. You should not rely\n * on the font family formatting (consider it as an \"opaque string\") - it's slugified\n * (no spaces, no dots, no non-alphanumeric characters) to avoid issues when using the\n * font family in various contexts.\n *\n * @param filename The filename of the font.\n * @returns The font family to be used for this font resource.\n */\n _getFontFamilyFromFilename(resource: ResourceData): string {\n // Replaces all non-alphanumeric characters with dashes to ensure no issues when\n // referring to this font family (see https://github.com/4ian/GDevelop/issues/1521).\n let baseSlugifiedName =\n 'gdjs_font_' + resource.file.toLowerCase().replace(/[^\\w]/gi, '-');\n\n // Ensure the generated font family is unique.\n const slugifiedName = baseSlugifiedName;\n let uniqueSuffix = 2;\n while (this._loadedFontFamilySet.has(baseSlugifiedName)) {\n baseSlugifiedName = baseSlugifiedName + '-' + uniqueSuffix;\n uniqueSuffix++;\n }\n return slugifiedName;\n }\n\n /**\n * Load the font at the given `src` location (relative to the project), giving\n * it the specified `fontFamily` name.\n *\n * This uses FontFace (if supported) or @font-face + FontFaceObserver\n * to load a font from an url and be notified when loading is done (or failed).\n *\n * @param fontFamily The font\n * @returns The font family to be used for this font resource.\n */\n private _loadFont(fontFamily: string, src: string): Promise<void> {\n const descriptors = {};\n const srcWithUrl = 'url(' + encodeURI(src) + ')';\n\n // @ts-ignore\n if (typeof FontFace !== 'undefined') {\n // Load the given font using CSS Font Loading API.\n return fetch(this._resourceLoader.getFullUrl(src), {\n credentials: this._resourceLoader.checkIfCredentialsRequired(src)\n ? // Any resource stored on the GDevelop Cloud buckets needs the \"credentials\" of the user,\n // i.e: its gdevelop.io cookie, to be passed.\n 'include'\n : // For other resources, use \"same-origin\" as done by default by fetch.\n 'same-origin',\n })\n .then((response) => {\n if (!response.ok) {\n const errorMessage =\n 'Unable to fetch ' +\n src +\n ' to be loaded as a font. HTTP status is: ' +\n response.status +\n '.';\n logger.error(errorMessage);\n throw new Error(errorMessage);\n }\n\n return response.arrayBuffer();\n })\n .then((arrayBuffer) => {\n // @ts-ignore\n const fontFace = new FontFace(fontFamily, arrayBuffer, descriptors);\n\n // @ts-ignore\n document.fonts.add(fontFace);\n });\n } else {\n // TODO: this method of loading font should be removed as old and not allowing\n // to handle loading with credentials. All moderns and not-so-modern browsers\n // that we support also support FontFace API.\n\n // Add @font-face and use FontFaceObserver to be notified when the\n // font is ready.\n const newStyle = document.createElement('style');\n newStyle.appendChild(\n document.createTextNode(\n \"@font-face { font-family: '\" +\n fontFamily +\n \"'; src: \" +\n srcWithUrl +\n '; }'\n )\n );\n document.head.appendChild(newStyle);\n\n // @ts-ignore\n return new FontFaceObserver(fontFamily, descriptors).load();\n }\n }\n\n async processResource(resourceName: string): Promise<void> {\n // Do nothing because fonts are light enough to be parsed in background.\n }\n\n /**\n * Load the specified resources, so that fonts are loaded and can then be\n * used by using the font family returned by getFontFamily.\n * @param resourceName The name of the resource to load.\n */\n async loadResource(resourceName: string): Promise<void> {\n const resource = this._resourceLoader.getResource(resourceName);\n if (!resource) {\n logger.warn('Unable to find font for resource \"' + resourceName + '\".');\n return;\n }\n\n if (this._loadedFontFamily.get(resource)) {\n return;\n }\n const file = resource.file;\n if (!file) {\n return;\n }\n\n const fontFamily = this._getFontFamilyFromFilename(resource);\n // Cache the result to avoid collision with a similar slugified name for another filename.\n this._loadedFontFamily.set(resource, fontFamily);\n this._loadedFontFamilySet.add(fontFamily);\n try {\n await this._loadFont(fontFamily, file);\n } catch (error) {\n logger.error(\n 'Error loading font resource \"' +\n resource.name +\n '\" (file: ' +\n file +\n '): ' +\n (error.message || 'Unknown error')\n );\n }\n }\n\n /**\n * To be called when the game is disposed.\n * Clear caches of loaded font families.\n */\n dispose(): void {\n this._loadedFontFamily.clear();\n this._loadedFontFamilySet.clear();\n }\n }\n\n //Register the class to let the engine use it.\n export type FontManager = FontFaceObserverFontManager;\n export const FontManager = FontFaceObserverFontManager;\n}\n"],
|
|
5
|
-
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,gBAEzB,EAAqC,CAAC,QAOrC,OAAkE,CASvE,YAAY,EAAqC,CANjD,uBAAoB,GAAI,GAAK,cAC7B,0BAAuB,GAAI,KAMzB,KAAK,gBAAkB,EAGzB,kBAAmC,CACjC,MAAO,GAYT,cAAc,EAA8B,CAC1C,MAAO,MAAK,kBAAkB,YAAY,IAAiB,QAc7D,YAAY,EAA8B,CACxC,KAAM,GAAW,KAAK,gBAAgB,YAAY,GAClD,MAAO,GAAW,EAAS,MAAQ,GAAK,EAa1C,2BAA2B,EAAgC,CAGzD,GAAI,GACF,aAAe,EAAS,KAAK,cAAc,QAAQ,UAAW,KAGhE,KAAM,GAAgB,EACtB,GAAI,GAAe,EACnB,KAAO,KAAK,qBAAqB,IAAI,IACnC,EAAoB,EAAoB,IAAM,EAC9C,IAEF,MAAO,GAaD,UAAU,EAAoB,EAA4B,CAChE,KAAM,GAAc,GACd,EAAa,OAAS,UAAU,GAAO,IAG7C,GAAI,MAAO,WAAa,YAEtB,MAAO,OAAM,KAAK,gBAAgB,WAAW,GAAM,CACjD,YAAa,KAAK,gBAAgB,2BAA2B,GAGzD,UAEA,gBAEH,KAAK,AAAC,GAAa,CAClB,GAAI,CAAC,EAAS,GAAI,CAChB,KAAM,GACJ,mBACA,EACA,4CACA,EAAS,OACT,IACF,QAAO,MAAM,GACP,GAAI,OAAM,GAGlB,MAAO,GAAS,gBAEjB,KAAK,AAAC,GAAgB,CAErB,KAAM,GAAW,GAAI,UAAS,EAAY,EAAa,GAGvD,SAAS,MAAM,IAAI,KAElB,CAOL,KAAM,GAAW,SAAS,cAAc,SACxC,SAAS,YACP,SAAS,eACP,8BACE,EACA,WACA,EACA,QAGN,SAAS,KAAK,YAAY,GAGnB,GAAI,kBAAiB,EAAY,GAAa,aAInD,iBAAgB,EAAqC,OASrD,cAAa,EAAqC,CACtD,KAAM,GAAW,KAAK,gBAAgB,YAAY,GAClD,GAAI,CAAC,EAAU,CACb,EAAO,KAAK,qCAAuC,EAAe,MAClE,OAGF,GAAI,KAAK,kBAAkB,IAAI,GAC7B,OAEF,KAAM,GAAO,EAAS,KACtB,GAAI,CAAC,EACH,OAGF,KAAM,GAAa,KAAK,2BAA2B,GAEnD,KAAK,kBAAkB,IAAI,EAAU,GACrC,KAAK,qBAAqB,IAAI,GAC9B,GAAI,CACF,KAAM,MAAK,UAAU,EAAY,SAC1B,EAAP,CACA,EAAO,MACL,gCACE,EAAS,KACT,YACA,EACA,MACC,GAAM,SAAW,mBAS1B,SAAgB,CACd,KAAK,kBAAkB,QACvB,KAAK,qBAAqB,
|
|
4
|
+
"sourcesContent": ["/*\n * GDevelop JS Platform\n * Copyright 2013-present 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('Font manager');\n\n const resourceKinds: Array<ResourceKind> = ['font'];\n\n /**\n * FontFaceObserverFontManager loads fonts (using `FontFace` or `fontfaceobserver` library)\n * from the game resources (see `loadFonts`), and allow to access to\n * the font families of the loaded fonts during the game (see `getFontFamily`).\n */\n export class FontFaceObserverFontManager implements gdjs.ResourceManager {\n _resourceLoader: gdjs.ResourceLoader;\n // Associate font resource names to the loaded font family\n _loadedFontFamily = new gdjs.ResourceCache<string>();\n _loadedFontFamilySet = new Set<string>();\n\n /**\n * @param resourceLoader The resources loader of the game.\n */\n constructor(resourceLoader: gdjs.ResourceLoader) {\n this._resourceLoader = resourceLoader;\n }\n\n getResourceKinds(): ResourceKind[] {\n return resourceKinds;\n }\n\n /**\n * Return the font family associated to the specified font resource name.\n * The font resource must have been loaded before. If that's not the case,\n * a default font family will be returned (\"Arial\").\n *\n * @param resourceName The name of the resource to get.\n * @returns The font family to be used for this font resource,\n * or \"Arial\" if not loaded.\n */\n getFontFamily(resourceName: string): string {\n return this._loadedFontFamily.getFromName(resourceName) || 'Arial';\n }\n\n /**\n * Return the font file associated to the specified font resource name.\n * The font resource must have been loaded before. If that's not the case,\n * the resource name will be returned (to\n * keep compatibility with GDevelop 5.0-beta56 and previous).\n *\n * Should only be useful for renderers running on a non HTML5/non browser environment.\n *\n * @param resourceName The name of the resource to get.\n * @returns The file of the font resource.\n */\n getFontFile(resourceName: string): string {\n const resource = this._resourceLoader.getResource(resourceName);\n return resource ? resource.file || '' : resourceName;\n }\n\n /**\n * Return the font family to use for a given filename.\n * Each filename is guaranteed to have a unique font family. You should not rely\n * on the font family formatting (consider it as an \"opaque string\") - it's slugified\n * (no spaces, no dots, no non-alphanumeric characters) to avoid issues when using the\n * font family in various contexts.\n *\n * @param filename The filename of the font.\n * @returns The font family to be used for this font resource.\n */\n _getFontFamilyFromFilename(resource: ResourceData): string {\n // Replaces all non-alphanumeric characters with dashes to ensure no issues when\n // referring to this font family (see https://github.com/4ian/GDevelop/issues/1521).\n let baseSlugifiedName =\n 'gdjs_font_' + resource.file.toLowerCase().replace(/[^\\w]/gi, '-');\n\n // Ensure the generated font family is unique.\n const slugifiedName = baseSlugifiedName;\n let uniqueSuffix = 2;\n while (this._loadedFontFamilySet.has(baseSlugifiedName)) {\n baseSlugifiedName = baseSlugifiedName + '-' + uniqueSuffix;\n uniqueSuffix++;\n }\n return slugifiedName;\n }\n\n /**\n * Load the font at the given `src` location (relative to the project), giving\n * it the specified `fontFamily` name.\n *\n * This uses FontFace (if supported) or @font-face + FontFaceObserver\n * to load a font from an url and be notified when loading is done (or failed).\n *\n * @param fontFamily The font\n * @returns The font family to be used for this font resource.\n */\n private _loadFont(fontFamily: string, src: string): Promise<void> {\n const descriptors = {};\n const srcWithUrl = 'url(' + encodeURI(src) + ')';\n\n // @ts-ignore\n if (typeof FontFace !== 'undefined') {\n // Load the given font using CSS Font Loading API.\n return fetch(this._resourceLoader.getFullUrl(src), {\n credentials: this._resourceLoader.checkIfCredentialsRequired(src)\n ? // Any resource stored on the GDevelop Cloud buckets needs the \"credentials\" of the user,\n // i.e: its gdevelop.io cookie, to be passed.\n 'include'\n : // For other resources, use \"same-origin\" as done by default by fetch.\n 'same-origin',\n })\n .then((response) => {\n if (!response.ok) {\n const errorMessage =\n 'Unable to fetch ' +\n src +\n ' to be loaded as a font. HTTP status is: ' +\n response.status +\n '.';\n logger.error(errorMessage);\n throw new Error(errorMessage);\n }\n\n return response.arrayBuffer();\n })\n .then((arrayBuffer) => {\n // @ts-ignore\n const fontFace = new FontFace(fontFamily, arrayBuffer, descriptors);\n\n // @ts-ignore\n document.fonts.add(fontFace);\n });\n } else {\n // TODO: this method of loading font should be removed as old and not allowing\n // to handle loading with credentials. All moderns and not-so-modern browsers\n // that we support also support FontFace API.\n\n // Add @font-face and use FontFaceObserver to be notified when the\n // font is ready.\n const newStyle = document.createElement('style');\n newStyle.appendChild(\n document.createTextNode(\n \"@font-face { font-family: '\" +\n fontFamily +\n \"'; src: \" +\n srcWithUrl +\n '; }'\n )\n );\n document.head.appendChild(newStyle);\n\n // @ts-ignore\n return new FontFaceObserver(fontFamily, descriptors).load();\n }\n }\n\n async processResource(resourceName: string): Promise<void> {\n // Do nothing because fonts are light enough to be parsed in background.\n }\n\n /**\n * Load the specified resources, so that fonts are loaded and can then be\n * used by using the font family returned by getFontFamily.\n * @param resourceName The name of the resource to load.\n */\n async loadResource(resourceName: string): Promise<void> {\n const resource = this._resourceLoader.getResource(resourceName);\n if (!resource) {\n logger.warn('Unable to find font for resource \"' + resourceName + '\".');\n return;\n }\n\n if (this._loadedFontFamily.get(resource)) {\n return;\n }\n const file = resource.file;\n if (!file) {\n return;\n }\n\n const fontFamily = this._getFontFamilyFromFilename(resource);\n // Cache the result to avoid collision with a similar slugified name for another filename.\n this._loadedFontFamily.set(resource, fontFamily);\n this._loadedFontFamilySet.add(fontFamily);\n try {\n await this._loadFont(fontFamily, file);\n } catch (error) {\n logger.error(\n 'Error loading font resource \"' +\n resource.name +\n '\" (file: ' +\n file +\n '): ' +\n (error.message || 'Unknown error')\n );\n }\n }\n\n /**\n * To be called when the game is disposed.\n * Clear caches of loaded font families.\n */\n dispose(): void {\n this._loadedFontFamily.clear();\n this._loadedFontFamilySet.clear();\n }\n\n /**\n * Unload the specified list of resources:\n * this clears the caches of loaded font families.\n *\n * Usually called when scene resoures are unloaded.\n *\n * @param resourcesList The list of specific resources\n */\n unloadResourcesList(resourcesList: ResourceData[]): void {\n resourcesList.forEach((resourceData) => {\n const resource = this._loadedFontFamily.get(resourceData);\n if (resource) {\n this._loadedFontFamily.delete(resourceData);\n }\n\n const fontName = this._getFontFamilyFromFilename(resourceData);\n if (fontName) {\n this._loadedFontFamilySet.delete(fontName);\n }\n });\n }\n }\n\n //Register the class to let the engine use it.\n export type FontManager = FontFaceObserverFontManager;\n export const FontManager = FontFaceObserverFontManager;\n}\n"],
|
|
5
|
+
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,gBAEzB,EAAqC,CAAC,QAOrC,OAAkE,CAS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EF,KAAM,GAAO,EAAS,KACtB,GAAI,CAAC,EACH,OAGF,KAAM,GAAa,KAAK,2BAA2B,GAEnD,KAAK,kBAAkB,IAAI,EAAU,GACrC,KAAK,qBAAqB,IAAI,GAC9B,GAAI,CACF,KAAM,MAAK,UAAU,EAAY,SAC1B,EAAP,CACA,EAAO,MACL,gCACE,EAAS,KACT,YACA,EACA,MACC,GAAM,SAAW,mBAS1B,SAAgB,CACd,KAAK,kBAAkB,QACvB,KAAK,qBAAqB,QAW5B,oBAAoB,EAAqC,CACvD,EAAc,QAAQ,AAAC,GAAiB,CAEtC,AAAI,AADa,KAAK,kBAAkB,IAAI,IAE1C,KAAK,kBAAkB,OAAO,GAGhC,KAAM,GAAW,KAAK,2BAA2B,GACjD,AAAI,GACF,KAAK,qBAAqB,OAAO,MAlNlC,EAAM,8BA0NA,cAAc,IApOnB",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(a){const h=new a.Logger("Audio manager"),_=["audio"],c={preload:!0,onplayerror:(u,e)=>h.error("Can't play an audio file: "+e),onloaderror:(u,e)=>h.error("Error while loading an audio file: "+e)},d=u=>u>1?1:u<0?0:u;class
|
|
1
|
+
var gdjs;(function(a){const h=new a.Logger("Audio manager"),_=["audio"],c={preload:!0,onplayerror:(u,e)=>h.error("Can't play an audio file: "+e),onloaderror:(u,e)=>h.error("Error while loading an audio file: "+e)},d=u=>u>1?1:u<0?0:u;class p{constructor(e,s,t,l){this._id=null;this._oncePlay=[];this._onPlay=[];this._howl=e,this._initialVolume=d(s),this._loop=t,this._rate=l}isLoaded(){return this._howl.state()==="loaded"}play(){if(this.isLoaded()){const e=this._howl.play(this._id===null?"__default":this._id);this._id=e,this._howl.volume(this._initialVolume,e),this._howl.loop(this._loop,e),this._howl.rate(a.HowlerSoundManager.clampRate(this._rate),e),this._onPlay.forEach(s=>{this.on("play",s),s(e)}),this._oncePlay.forEach(s=>s(e)),this._onPlay=[],this._oncePlay=[]}else this._howl.once("load",()=>this.play());return this}pause(){return this._id!==null&&this._howl.pause(this._id),this}stop(){return this._id!==null&&this._howl.stop(this._id),this}playing(){return(this._id!==null?this._howl.playing(this._id):!0)||!this.isLoaded()}paused(){return!this.playing()}stopped(){return this.paused()&&this.getSeek()===0}getRate(){return this._rate}setRate(e){return this._rate=e,this._id!==null&&(e=a.HowlerSoundManager.clampRate(e),this._howl.rate(e,this._id)),this}getLoop(){return this._loop}setLoop(e){return this._loop=e,this._id!==null&&this._howl.loop(e,this._id),this}getVolume(){return this._id===null?this._initialVolume:this._howl.volume(this._id)}setVolume(e){return this._initialVolume=d(e),this._id!==null&&this._howl.volume(this._initialVolume,this._id),this}getMute(){return this._id===null?!1:this._howl.mute(this._id)}setMute(e){return this._id!==null&&this._howl.mute(e,this._id),this}getSeek(){return this._id===null?0:this._howl.seek(this._id)}setSeek(e){return this._id!==null&&this._howl.seek(e,this._id),this}getSpatialPosition(e){return this._id===null?0:this._howl.pos(this._id)[e==="x"?0:e==="y"?1:2]}setSpatialPosition(e,s,t){return this._id!==null&&this._howl.pos(e,s,t,this._id),this}fade(e,s,t){return this._id!==null&&this._howl.fade(d(e),d(s),t,this._id),this}on(e,s){return e==="play"?this._id===null?this._onPlay.push(s):this._howl.on(e,s,this._id):this._id===null?this.once("play",()=>this.on(e,s)):this._howl.on(e,s,this._id),this}once(e,s){return e==="play"?this._id===null?this._oncePlay.push(s):this.playing()?s(this._id):this._howl.once(e,s,this._id):this._id===null?this.once("play",()=>this.once(e,s)):this._howl.once(e,s,this._id),this}off(e,s){return this._id!==null&&this._howl.off(e,s,this._id),this}}a.HowlerSound=p;class f{constructor(e){this._loadedMusics=new a.ResourceCache;this._loadedSounds=new a.ResourceCache;this._availableResources={};this._globalVolume=100;this._sounds={};this._cachedSpatialPosition={};this._musics={};this._freeSounds=[];this._freeMusics=[];this._pausedSounds=[];this._paused=!1;this._getAudioResource=e=>{const s=this._resourceLoader.getResource(e);return s&&this.getResourceKinds().includes(s.kind)?s:{file:e,kind:"audio",metadata:"",name:e}};this._resourceLoader=e,a.registerRuntimeScenePostEventsCallback(this._clearCachedSpatialPosition.bind(this));const s=this;document.addEventListener("deviceready",function(){document.addEventListener("pause",function(){s.pauseAllActiveSounds()},!1),document.addEventListener("resume",function(){s.resumeAllActiveSounds()},!1)})}pauseAllActiveSounds(){const e=this._freeSounds.concat(this._freeMusics);for(let s in this._sounds)this._sounds.hasOwnProperty(s)&&e.push(this._sounds[s]);for(let s in this._musics)this._musics.hasOwnProperty(s)&&e.push(this._musics[s]);for(let s=0;s<e.length;s++){const t=e[s];!t.paused()&&!t.stopped()&&(t.pause(),this._pausedSounds.push(t))}this._paused=!0}resumeAllActiveSounds(){try{for(let e=0;e<this._pausedSounds.length;e++){const s=this._pausedSounds[e];s.stopped()||s.play()}}catch(e){if(e.message&&typeof e.message=="string"&&e.message.startsWith("Maximum call stack size exceeded"))console.warn("An error occurred when resuming paused sounds while the game was in background:",e);else throw e}this._pausedSounds.length=0,this._paused=!1}getResourceKinds(){return _}static clampRate(e){return e>4?4:e<.5?.5:e}_getSoundUrlsFromResource(e){return[this._resourceLoader.getFullUrl(e.file)]}_getDefaultSoundUrl(e){return this._resourceLoader.getFullUrl(e.file)}_preloadAudioFile(e,s){const t=e.file;return new Promise((l,i)=>{const o=s?this._loadedMusics:this._loadedSounds;o[t]=new Howl(Object.assign({},c,{src:this._getSoundUrlsFromResource(e),onload:l,onloaderror:(r,n)=>i(n),html5:s,xhr:{withCredentials:this._resourceLoader.checkIfCredentialsRequired(t)},volume:0}))})}_storeSoundInArray(e,s){for(let t=0,l=e.length;t<l;++t)if(!e[t]||e[t].stopped())return e[t]=s,s;return e.push(s),s}createHowlerSound(e,s,t,l,i){const o=s?this._loadedMusics:this._loadedSounds,r=this._getAudioResource(e);let n=o.get(r);return n||(n=new Howl(Object.assign({src:this._getSoundUrlsFromResource(r),html5:s,xhr:{withCredentials:this._resourceLoader.checkIfCredentialsRequired(r.file)},volume:0},c)),o.set(r,n)),new a.HowlerSound(n,t,l,i)}loadAudio(e,s){const t=s?this._loadedMusics:this._loadedSounds,l=this._getAudioResource(e);t.get(l)||t.set(l,new Howl(Object.assign({src:this._getSoundUrlsFromResource(l),html5:s,xhr:{withCredentials:this._resourceLoader.checkIfCredentialsRequired(l.file)},volume:0},c)))}unloadAudio(e,s){const t=s?this._loadedMusics:this._loadedSounds,l=this._getAudioResource(e),i=t.get(l);if(!i)return;function o(r){for(let n in r)r[n]&&r[n]._howl===i&&(r[n].stop(),delete r[n])}o(this._freeMusics),o(this._freeSounds),o(Object.values(this._musics)),o(Object.values(this._sounds)),o(this._pausedSounds),i.unload(),t.delete(l)}unloadAll(){Howler.unload(),this._freeSounds.length=0,this._freeMusics.length=0,this._sounds={},this._musics={},this._pausedSounds.length=0,this._loadedMusics.clear(),this._loadedSounds.clear()}playSound(e,s,t,l){const i=this.createHowlerSound(e,!1,t/100,s,l);this._storeSoundInArray(this._freeSounds,i),i.once("play",()=>{this._paused&&(i.pause(),this._pausedSounds.push(i))}),i.play()}playSoundOnChannel(e,s,t,l,i){this._sounds[s]&&this._sounds[s].stop();const o=this.createHowlerSound(e,!1,l/100,t,i),r=this._cachedSpatialPosition[s];r&&o.once("play",()=>{o.setSpatialPosition(...r)}),this._sounds[s]=o,o.once("play",()=>{this._paused&&(o.pause(),this._pausedSounds.push(o))}),o.play()}getSoundOnChannel(e){return this._sounds[e]||null}playMusic(e,s,t,l){const i=this.createHowlerSound(e,!0,t/100,s,l);this._storeSoundInArray(this._freeMusics,i),i.once("play",()=>{this._paused&&(i.pause(),this._pausedSounds.push(i))}),i.play()}playMusicOnChannel(e,s,t,l,i){this._musics[s]&&this._musics[s].stop();const o=this.createHowlerSound(e,!0,l/100,t,i);this._musics[s]=o,o.once("play",()=>{this._paused&&(o.pause(),this._pausedSounds.push(o))}),o.play()}getMusicOnChannel(e){return this._musics[e]||null}setSoundSpatialPositionOnChannel(e,s,t,l){const i=this.getSoundOnChannel(e);i&&!i.paused()?i.setSpatialPosition(s,t,l):this._cachedSpatialPosition[e]=[s,t,l]}_clearCachedSpatialPosition(){this._cachedSpatialPosition={}}setGlobalVolume(e){this._globalVolume=e,this._globalVolume>100&&(this._globalVolume=100),this._globalVolume<0&&(this._globalVolume=0),Howler.volume(this._globalVolume/100)}getGlobalVolume(){return this._globalVolume}clearAll(){Howler.stop(),this._freeSounds.length=0,this._freeMusics.length=0,this._sounds={},this._musics={},this._pausedSounds.length=0}async processResource(e){}async loadResource(e){const s=this._resourceLoader.getResource(e);if(!s){h.warn('Unable to find audio for resource "'+e+'".');return}if(s.file){if(this._availableResources[s.name])return;this._availableResources[s.name]=s}if(s.preloadAsMusic)try{await this._preloadAudioFile(s,!0)}catch(t){h.warn("There was an error while preloading an audio file: "+t)}if(s.preloadAsSound)try{await this._preloadAudioFile(s,!1)}catch(t){h.warn("There was an error while preloading an audio file: "+t)}else if(s.preloadInCache||!s.preloadAsMusic)try{const t=s.file;await new Promise((l,i)=>{const o=new XMLHttpRequest;o.withCredentials=this._resourceLoader.checkIfCredentialsRequired(t),o.addEventListener("load",l),o.addEventListener("error",r=>i("XHR error: "+t)),o.addEventListener("abort",r=>i("XHR abort: "+t)),o.open("GET",this._getDefaultSoundUrl(s)),o.send()})}catch(t){h.warn("There was an error while preloading an audio file: "+t)}}dispose(){this.unloadAll()}unloadResourcesList(e){e.forEach(s=>{this._loadedMusics.get(s)&&this.unloadAudio(s.name,!0),this._loadedSounds.get(s)&&this.unloadAudio(s.name,!1)})}}a.HowlerSoundManager=f,a.SoundManager=f})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=howler-sound-manager.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../GDevelop/GDJS/Runtime/howler-sound-manager/howler-sound-manager.ts"],
|
|
4
|
-
"sourcesContent": ["///<reference path='../types/howler'>\n/*\n * GDevelop JS Platform\n * Copyright 2013-present 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('Audio manager');\n\n const resourceKinds: Array<ResourceKind> = ['audio'];\n\n const HowlParameters: HowlOptions = {\n preload: true,\n onplayerror: (_, error) =>\n logger.error(\"Can't play an audio file: \" + error),\n onloaderror: (_, error) =>\n logger.error('Error while loading an audio file: ' + error),\n };\n\n /**\n * Ensure the volume is between 0 and 1.\n */\n const clampVolume = (volume: float): float => {\n if (volume > 1.0) {\n return 1.0;\n }\n if (volume < 0) {\n return 0;\n }\n return volume;\n };\n\n /**\n * A thin wrapper around a Howl object with:\n * * Handling of callbacks when the sound is not yet loaded.\n * * Automatic clamping when calling `setRate` to ensure a valid value is passed to Howler.js.\n * * Automatic clamping when calling `setVolume` so that the volume is always between 0 and 1.\n *\n * @memberof gdjs\n * @class HowlerSound\n */\n export class HowlerSound {\n /**\n * The ID of the played sound.\n */\n private _id: integer | null = null;\n\n /**\n * The Howl passed to the constructor.\n * It defines the sound file that is being played.\n */\n private _howl: Howl;\n\n /**\n * The **initial** volume at which the sound is being played.\n * Once the sound is started, this volume can be not in sync\n * (in the case the sound is faded by Howler), so volume must\n * be gotten from `this._howl` directly.\n *\n * This value is clamped between 0 and 1.\n */\n private _initialVolume: float;\n\n /**\n * Whether the sound is being played in a loop or not.\n */\n private _loop: boolean;\n\n /**\n * The rate (speed) the sound is being played at.\n * This value is not clamped, though technically Howler.js will only\n * accepts values between a specific range (so we clamp this when\n * passing it to Howler.js, but keep the original value here).\n */\n private _rate: float;\n\n /**\n * An array of callbacks to call once the sound starts to play.\n */\n private _oncePlay: Array<HowlCallback> = [];\n\n /**\n * An array of callbacks to call everytime the sound starts to play.\n */\n private _onPlay: Array<HowlCallback> = [];\n\n constructor(howl: Howl, volume: float, loop: boolean, rate: float) {\n this._howl = howl;\n this._initialVolume = clampVolume(volume);\n this._loop = loop;\n this._rate = rate;\n }\n\n /**\n * Returns true if the associated howl is fully loaded.\n */\n isLoaded(): boolean {\n return this._howl.state() === 'loaded';\n }\n\n /**\n * Begins playback of the sound, or if the Howl is still loading, schedule playing for once it loads.\n * @returns The current instance for chaining.\n */\n play(): this {\n if (this.isLoaded()) {\n const newID = this._howl.play(\n this._id === null ? '__default' : this._id\n );\n this._id = newID;\n\n // Set the howl properties as soon as the sound is played and we have its ID.\n this._howl.volume(this._initialVolume, newID); // this._initialVolume is already clamped between 0 and 1.\n this._howl.loop(this._loop, newID);\n // this._rate is not clamped, but we need to clamp it when passing it to Howler.js as it\n // only supports a specific range.\n this._howl.rate(gdjs.HowlerSoundManager.clampRate(this._rate), newID);\n\n // Manually handle the play event before we have an ID.\n // Before loading, howler won't register events as without an ID we cannot set a listener.\n // Once we have an ID, we can transfer control of the events to howler.\n // We also need to call them once as Howler doesn't for the first play event.\n this._onPlay.forEach((func) => {\n // Transfer the event to howler now that we have an ID\n this.on('play', func);\n func(newID);\n });\n this._oncePlay.forEach((func) => func(newID));\n this._onPlay = [];\n this._oncePlay = [];\n } else this._howl.once('load', () => this.play()); // Play only once the howl is fully loaded\n\n return this;\n }\n\n /**\n * Pauses playback of the sound, saving the seek of playback.\n * @returns The current instance for chaining.\n */\n pause(): this {\n if (this._id !== null) this._howl.pause(this._id);\n return this;\n }\n\n /**\n * Stops playback of the sound, resetting seek to 0.\n * @returns The current instance for chaining.\n */\n stop(): this {\n if (this._id !== null) this._howl.stop(this._id);\n return this;\n }\n\n /**\n * Check if the sound is currently playing.\n * Note that a loading sound is considered as playing (as it will be\n * played as soon as it's loaded). To avoid loading at runtime, prefer\n * to preload the sounds.\n */\n playing(): boolean {\n return (\n (this._id !== null ? this._howl.playing(this._id) : true) ||\n !this.isLoaded() // Loading is considered playing\n );\n }\n\n /**\n * Check if the sound is currently paused.\n */\n paused(): boolean {\n return !this.playing();\n }\n\n /**\n * Check if the sound is currently stopped.\n */\n stopped(): boolean {\n return this.paused() && this.getSeek() === 0;\n }\n\n /**\n * Get the sound playback rate. This 1 for the default speed.\n * This value is not clamped (any value greater than 0 is valid),\n * but the underlying audio system might not play the sound at the required\n * rate if it's very low or very high.\n */\n getRate(): float {\n return this._rate;\n }\n\n /**\n * Set the playback rate.\n * This value is not clamped (any value greater than 0 is valid),\n * but the underlying audio system might not play the sound at the required\n * rate if it's very low or very high.\n * @returns The current instance for chaining.\n */\n setRate(rate: float): this {\n this._rate = rate;\n // If the sound has already started playing, then change the value directly.\n if (this._id !== null) {\n rate = gdjs.HowlerSoundManager.clampRate(rate);\n this._howl.rate(rate, this._id);\n }\n return this;\n }\n\n /**\n * Get if the sound is looping.\n */\n getLoop(): boolean {\n return this._loop;\n }\n\n /**\n * Set if the sound is looping.\n * @returns The current instance for chaining.\n */\n setLoop(loop: boolean): this {\n this._loop = loop;\n // If the sound has already started playing, then change the value directly.\n if (this._id !== null) this._howl.loop(loop, this._id);\n return this;\n }\n\n //TODO: Replace float type in those 2 methods with RangeOf<0..1> once it is standardized (https://github.com/Microsoft/TypeScript/issues/15480)\n /**\n * Get the sound volume.\n * @returns A float from 0 to 1.\n */\n getVolume(): float {\n if (this._id === null) return this._initialVolume;\n return this._howl.volume(this._id);\n }\n\n /**\n * Set the sound volume.\n * @param volume A float from 0 to 1. The value is clamped if too high or too low.\n * @returns The current instance for chaining.\n */\n setVolume(volume: float): this {\n this._initialVolume = clampVolume(volume);\n\n // If the sound has already started playing, then change the value directly.\n if (this._id !== null) this._howl.volume(this._initialVolume, this._id);\n return this;\n }\n\n /**\n * Get if the sound is muted.\n */\n getMute(): boolean {\n if (this._id === null) return false;\n return this._howl.mute(this._id);\n }\n\n /**\n * Set if the sound is muted.\n * @returns The current instance for chaining.\n */\n setMute(mute: boolean): this {\n if (this._id !== null) this._howl.mute(mute, this._id);\n return this;\n }\n\n /**\n * Get the sound seek.\n */\n getSeek(): float {\n if (this._id === null) return 0;\n return this._howl.seek(this._id);\n }\n\n /**\n * Set the sound seek.\n * @returns The current instance for chaining.\n */\n setSeek(seek: float): this {\n if (this._id !== null) this._howl.seek(seek, this._id);\n return this;\n }\n\n /**\n * Get the sound spatial position.\n */\n getSpatialPosition(axis: 'x' | 'y' | 'z'): float {\n if (this._id === null) return 0;\n return this._howl.pos(this._id)[axis === 'x' ? 0 : axis === 'y' ? 1 : 2];\n }\n\n /**\n * Set the sound spatial position.\n * @returns The current instance for chaining.\n */\n setSpatialPosition(x: float, y: float, z: float): this {\n if (this._id !== null) this._howl.pos(x, y, z, this._id);\n return this;\n }\n\n /**\n * Fade the volume sound.\n * @returns The current instance for chaining.\n */\n fade(from: float, to: float, duration: float): this {\n if (this._id !== null)\n this._howl.fade(clampVolume(from), clampVolume(to), duration, this._id);\n return this;\n }\n\n /**\n * Adds an event listener to the howl.\n */\n on(event: HowlEvent, handler: HowlCallback): this {\n if (event === 'play') {\n if (this._id === null) {\n this._onPlay.push(handler);\n } else {\n this._howl.on(event, handler, this._id);\n }\n } else if (this._id === null)\n this.once('play', () => this.on(event, handler));\n else this._howl.on(event, handler, this._id);\n\n return this;\n }\n\n /**\n * Adds an event listener to the howl that removes itself after being called.\n * If the event is `play` and the sound is being played, the handler is\n * called synchronously.\n */\n once(event: HowlEvent, handler: HowlCallback): this {\n if (event === 'play') {\n if (this._id === null) {\n this._oncePlay.push(handler);\n } else if (this.playing()) {\n // Immediately call the handler if the sound is already playing.\n // This is useful for sounds that were just started and have a `.once('play', ...)`\n // handler added on them to set up the volume/rate/loop. If we don't do it\n // synchronously, the sound can play for a tiny bit at the default volume and rate.\n // See https://github.com/4ian/GDevelop/issues/2490.\n handler(this._id);\n } else {\n this._howl.once(event, handler, this._id);\n }\n } else if (this._id === null)\n this.once('play', () => this.once(event, handler));\n else this._howl.once(event, handler, this._id);\n\n return this;\n }\n\n /**\n * Removes an event listener to the howl.\n */\n off(event: HowlEvent, handler: HowlCallback): this {\n if (this._id !== null) this._howl.off(event, handler, this._id);\n return this;\n }\n }\n\n /**\n * HowlerSoundManager is used to manage the sounds and musics of a RuntimeScene.\n *\n * It is basically a container to associate channels to sounds and keep a list\n * of all sounds being played.\n */\n export class HowlerSoundManager {\n _loadedMusics = new gdjs.ResourceCache<Howl>();\n _loadedSounds = new gdjs.ResourceCache<Howl>();\n _availableResources: Record<string, ResourceData> = {};\n _globalVolume: float = 100;\n _sounds: Record<integer, HowlerSound> = {};\n _cachedSpatialPosition: Record<integer, [number, number, number]> = {};\n _musics: Record<integer, HowlerSound> = {};\n _freeSounds: HowlerSound[] = []; // Sounds without an assigned channel.\n _freeMusics: HowlerSound[] = []; // Musics without an assigned channel.\n\n /** Paused sounds or musics that should be played once the game is resumed. */\n _pausedSounds: HowlerSound[] = [];\n _paused: boolean = false;\n\n _resourceLoader: gdjs.ResourceLoader;\n\n /**\n * @param resourceLoader The resources loader of the game.\n */\n constructor(resourceLoader: gdjs.ResourceLoader) {\n this._resourceLoader = resourceLoader;\n\n gdjs.registerRuntimeScenePostEventsCallback(\n this._clearCachedSpatialPosition.bind(this)\n );\n const that = this;\n document.addEventListener('deviceready', function () {\n // pause/resume sounds in Cordova when the app is being paused/resumed\n document.addEventListener(\n 'pause',\n function () {\n that.pauseAllActiveSounds();\n },\n false\n );\n document.addEventListener(\n 'resume',\n function () {\n that.resumeAllActiveSounds();\n },\n false\n );\n });\n }\n\n pauseAllActiveSounds(): void {\n const soundList = this._freeSounds.concat(this._freeMusics);\n for (let key in this._sounds) {\n if (this._sounds.hasOwnProperty(key)) {\n soundList.push(this._sounds[key]);\n }\n }\n for (let key in this._musics) {\n if (this._musics.hasOwnProperty(key)) {\n soundList.push(this._musics[key]);\n }\n }\n for (let i = 0; i < soundList.length; i++) {\n const sound = soundList[i];\n if (!sound.paused() && !sound.stopped()) {\n sound.pause();\n this._pausedSounds.push(sound);\n }\n }\n this._paused = true;\n }\n\n resumeAllActiveSounds(): void {\n try {\n for (let i = 0; i < this._pausedSounds.length; i++) {\n const sound = this._pausedSounds[i];\n if (!sound.stopped()) {\n sound.play();\n }\n }\n } catch (error) {\n if (\n error.message &&\n typeof error.message === 'string' &&\n error.message.startsWith('Maximum call stack size exceeded')\n ) {\n console.warn(\n 'An error occurred when resuming paused sounds while the game was in background:',\n error\n );\n } else {\n throw error;\n }\n }\n this._pausedSounds.length = 0;\n this._paused = false;\n }\n\n getResourceKinds(): ResourceKind[] {\n return resourceKinds;\n }\n\n /**\n * Ensure rate is in a range valid for Howler.js\n * @return The clamped rate\n */\n static clampRate(rate: float): float {\n if (rate > 4.0) {\n return 4.0;\n }\n if (rate < 0.5) {\n return 0.5;\n }\n return rate;\n }\n\n /**\n * Return the file associated to the given sound name.\n *\n * Names and files are loaded from resources when preloadAudio is called. If no\n * file is associated to the given name, then the name will be considered as a\n * filename and will be returned.\n *\n * @return The associated resource\n */\n private _getAudioResource = (resourceName: string): ResourceData => {\n const resource = this._resourceLoader.getResource(resourceName);\n return resource && this.getResourceKinds().includes(resource.kind)\n ? resource\n : ({\n file: resourceName,\n kind: 'audio',\n metadata: '',\n name: resourceName,\n } as ResourceData);\n };\n\n /**\n * @param resource\n * @returns Resource files\n */\n private _getSoundUrlsFromResource(resource: ResourceData): string[] {\n return [this._resourceLoader.getFullUrl(resource.file)];\n }\n\n /**\n * @param resource\n * @returns Resource file\n */\n private _getDefaultSoundUrl(resource: ResourceData): string {\n return this._resourceLoader.getFullUrl(resource.file);\n }\n\n /**\n * Preload audio file\n * @param resource\n * @param isMusic\n */\n private _preloadAudioFile(\n resource: ResourceData,\n isMusic: boolean\n ): Promise<number> {\n const file = resource.file;\n return new Promise((resolve, reject) => {\n const container = isMusic ? this._loadedMusics : this._loadedSounds;\n container[file] = new Howl(\n Object.assign({}, HowlParameters, {\n src: this._getSoundUrlsFromResource(resource),\n onload: resolve,\n onloaderror: (soundId: number, error?: string) => reject(error),\n html5: isMusic,\n xhr: {\n withCredentials:\n this._resourceLoader.checkIfCredentialsRequired(file),\n },\n // Cache the sound with no volume. This avoids a bug where it plays at full volume\n // for a split second before setting its correct volume.\n volume: 0,\n })\n );\n });\n }\n\n /**\n * Store the sound in the specified array, put it at the first index that\n * is free, or add it at the end if no element is free\n * (\"free\" means that the gdjs.HowlerSound can be destroyed).\n *\n * @param arr The array containing the sounds.\n * @param arr The gdjs.HowlerSound to add.\n * @return The gdjs.HowlerSound that have been added (i.e: the second parameter).\n */\n private _storeSoundInArray(\n arr: Array<HowlerSound>,\n sound: HowlerSound\n ): HowlerSound {\n // Try to recycle an old sound.\n for (let i = 0, len = arr.length; i < len; ++i) {\n if (!arr[i] || arr[i].stopped()) {\n arr[i] = sound;\n return sound;\n }\n }\n\n arr.push(sound);\n return sound;\n }\n\n /**\n * Creates a new gdjs.HowlerSound using preloaded/cached Howl instances.\n * @param soundName The name of the file or resource to play.\n * @param isMusic True if a music, false if a sound.\n * @param volume Between 0 and 1.\n * @param loop True if it should be played looping.\n * @param rate speed at which it is played.\n */\n createHowlerSound(\n soundName: string,\n isMusic: boolean,\n volume: float,\n loop: boolean,\n rate: float\n ): HowlerSound {\n const cacheContainer = isMusic ? this._loadedMusics : this._loadedSounds;\n const resource = this._getAudioResource(soundName);\n\n let howl = cacheContainer.get(resource);\n if (!howl) {\n howl = new Howl(\n Object.assign(\n {\n src: this._getSoundUrlsFromResource(resource),\n html5: isMusic,\n xhr: {\n withCredentials:\n this._resourceLoader.checkIfCredentialsRequired(\n resource.file\n ),\n },\n // Cache the sound with no volume. This avoids a bug where it plays at full volume\n // for a split second before setting its correct volume.\n volume: 0,\n },\n HowlParameters\n )\n );\n cacheContainer.set(resource, howl);\n }\n\n return new gdjs.HowlerSound(howl, volume, loop, rate);\n }\n\n /**\n * Preloads a sound or a music in memory.\n * @param soundName The name of the file or resource to preload.\n * @param isMusic True if a music, false if a sound.\n */\n loadAudio(soundName: string, isMusic: boolean) {\n const cacheContainer = isMusic ? this._loadedMusics : this._loadedSounds;\n const resource = this._getAudioResource(soundName);\n\n // Do not reload if it is already loaded.\n if (cacheContainer.get(resource)) {\n return;\n }\n\n cacheContainer.set(\n resource,\n new Howl(\n Object.assign(\n {\n src: this._getSoundUrlsFromResource(resource),\n html5: isMusic,\n xhr: {\n withCredentials:\n this._resourceLoader.checkIfCredentialsRequired(\n resource.file\n ),\n },\n // Cache the sound with no volume. This avoids a bug where it plays at full volume\n // for a split second before setting its correct volume.\n volume: 0,\n },\n HowlParameters\n )\n )\n );\n }\n\n /**\n * Unloads a sound or a music from memory. This will stop any sound/music using it.\n * @param soundName The name of the file or resource to unload.\n * @param isMusic True if a music, false if a sound.\n */\n unloadAudio(soundName: string, isMusic: boolean) {\n const cacheContainer = isMusic ? this._loadedMusics : this._loadedSounds;\n const resource = this._getAudioResource(soundName);\n\n const howl = cacheContainer.get(resource);\n if (!howl) {\n return;\n }\n\n // Make sure any sound using the howl is deleted so\n // that the howl can be garbage collected\n // and no weird \"zombies\" using the unloaded howl can exist.\n function clearContainer(howlerSoundContainer: HowlerSound[]) {\n for (let i in howlerSoundContainer) {\n if (\n howlerSoundContainer[i] &&\n //@ts-ignore We really need to access the raw howl here.\n howlerSoundContainer[i]._howl === howl\n ) {\n howlerSoundContainer[i].stop();\n delete howlerSoundContainer[i];\n }\n }\n }\n\n clearContainer(this._freeMusics);\n clearContainer(this._freeSounds);\n clearContainer(Object.values(this._musics));\n clearContainer(Object.values(this._sounds));\n clearContainer(this._pausedSounds);\n\n howl.unload();\n cacheContainer.delete(resource);\n }\n\n /**\n * Unloads all audio from memory.\n * This will clear the Howl cache.\n * This will also stop any running music or sounds.\n */\n unloadAll() {\n Howler.unload();\n\n // Clean up old sounds that still have the dead Howl instances.\n this._freeSounds.length = 0;\n this._freeMusics.length = 0;\n this._sounds = {};\n this._musics = {};\n this._pausedSounds.length = 0;\n this._loadedMusics.clear();\n this._loadedSounds.clear();\n }\n\n playSound(soundName: string, loop: boolean, volume: float, pitch: float) {\n const sound = this.createHowlerSound(\n soundName,\n /* isMusic= */ false,\n volume / 100,\n loop,\n pitch\n );\n this._storeSoundInArray(this._freeSounds, sound);\n sound.once('play', () => {\n if (this._paused) {\n sound.pause();\n this._pausedSounds.push(sound);\n }\n });\n sound.play();\n }\n\n playSoundOnChannel(\n soundName: string,\n channel: integer,\n loop: boolean,\n volume: float,\n pitch: float\n ) {\n if (this._sounds[channel]) this._sounds[channel].stop();\n\n const sound = this.createHowlerSound(\n soundName,\n /* isMusic= */ false,\n volume / 100,\n loop,\n pitch\n );\n const spatialPosition = this._cachedSpatialPosition[channel];\n if (spatialPosition) {\n sound.once('play', () => {\n sound.setSpatialPosition(...spatialPosition);\n });\n }\n this._sounds[channel] = sound;\n sound.once('play', () => {\n if (this._paused) {\n sound.pause();\n this._pausedSounds.push(sound);\n }\n });\n sound.play();\n }\n\n getSoundOnChannel(channel: integer): HowlerSound | null {\n return this._sounds[channel] || null;\n }\n\n playMusic(soundName: string, loop: boolean, volume: float, pitch: float) {\n const music = this.createHowlerSound(\n soundName,\n /* isMusic= */ true,\n volume / 100,\n loop,\n pitch\n );\n this._storeSoundInArray(this._freeMusics, music);\n music.once('play', () => {\n if (this._paused) {\n music.pause();\n this._pausedSounds.push(music);\n }\n });\n music.play();\n }\n\n playMusicOnChannel(\n soundName: string,\n channel: integer,\n loop: boolean,\n volume: float,\n pitch: float\n ) {\n if (this._musics[channel]) this._musics[channel].stop();\n\n const music = this.createHowlerSound(\n soundName,\n /* isMusic= */ true,\n volume / 100,\n loop,\n pitch\n );\n // Musics are played with the html5 backend, that is not compatible with spatialization.\n this._musics[channel] = music;\n music.once('play', () => {\n if (this._paused) {\n music.pause();\n this._pausedSounds.push(music);\n }\n });\n music.play();\n }\n\n getMusicOnChannel(channel: integer): HowlerSound | null {\n return this._musics[channel] || null;\n }\n\n setSoundSpatialPositionOnChannel(\n channel: number,\n x: number,\n y: number,\n z: number\n ) {\n const sound = this.getSoundOnChannel(channel);\n if (sound && !sound.paused()) sound.setSpatialPosition(x, y, z);\n else {\n // If no sound is playing at the time the method is called, the\n // position is cached and will be used by the `playSoundOnChannel` method\n // to set the spatial position right after the sound starts playing.\n // This cached value is then cleared at the end of the frame.\n // Without this caching strategy, if actions are in the wrong order,\n // the spatial position will not apply to the sound because\n // it is not playing yet.\n this._cachedSpatialPosition[channel] = [x, y, z];\n }\n }\n\n _clearCachedSpatialPosition() {\n this._cachedSpatialPosition = {};\n }\n\n setGlobalVolume(volume: float): void {\n this._globalVolume = volume;\n if (this._globalVolume > 100) {\n this._globalVolume = 100;\n }\n if (this._globalVolume < 0) {\n this._globalVolume = 0;\n }\n Howler.volume(this._globalVolume / 100);\n }\n\n getGlobalVolume(): float {\n return this._globalVolume;\n }\n\n clearAll() {\n Howler.stop();\n\n this._freeSounds.length = 0;\n this._freeMusics.length = 0;\n this._sounds = {};\n this._musics = {};\n this._pausedSounds.length = 0;\n }\n\n async processResource(resourceName: string): Promise<void> {\n // Do nothing because sounds are light enough to be parsed in background.\n }\n\n async loadResource(resourceName: string): Promise<void> {\n const resource = this._resourceLoader.getResource(resourceName);\n if (!resource) {\n logger.warn(\n 'Unable to find audio for resource \"' + resourceName + '\".'\n );\n return;\n }\n if (resource.file) {\n if (this._availableResources[resource.name]) {\n return;\n }\n\n this._availableResources[resource.name] = resource;\n }\n\n if (resource.preloadAsMusic) {\n try {\n await this._preloadAudioFile(resource, /* isMusic= */ true);\n } catch (error) {\n logger.warn(\n 'There was an error while preloading an audio file: ' + error\n );\n }\n }\n\n if (resource.preloadAsSound) {\n try {\n await this._preloadAudioFile(resource, /* isMusic= */ false);\n } catch (error) {\n logger.warn(\n 'There was an error while preloading an audio file: ' + error\n );\n }\n } else if (\n resource.preloadInCache ||\n // Force downloading of sounds.\n // TODO Decide if sounds should be allowed to be downloaded after the scene starts.\n // - they should be requested automatically at the end of the scene loading\n // - they will be downloaded while the scene is playing\n // - other scenes will be pre-loaded only when all the sounds for the current scene are in cache\n !resource.preloadAsMusic\n ) {\n // preloading as sound already does a XHR request, hence \"else if\"\n try {\n const file = resource.file;\n await new Promise((resolve, reject) => {\n const sound = new XMLHttpRequest();\n sound.withCredentials =\n this._resourceLoader.checkIfCredentialsRequired(file);\n sound.addEventListener('load', resolve);\n sound.addEventListener('error', (_) =>\n reject('XHR error: ' + file)\n );\n sound.addEventListener('abort', (_) =>\n reject('XHR abort: ' + file)\n );\n sound.open('GET', this._getDefaultSoundUrl(resource));\n sound.send();\n });\n } catch (error) {\n logger.warn(\n 'There was an error while preloading an audio file: ' + error\n );\n }\n }\n }\n\n /**\n * To be called when the game is disposed.\n * Unloads all audio from memory, clear Howl cache and stop all audio.\n */\n dispose(): void {\n this.unloadAll();\n }\n }\n\n // Register the class to let the engine use it.\n export const SoundManager = HowlerSoundManager;\n export type SoundManager = HowlerSoundManager;\n}\n"],
|
|
5
|
-
"mappings": "AAMA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,iBAEzB,EAAqC,CAAC,SAEtC,EAA8B,CAClC,QAAS,GACT,YAAa,CAAC,EAAG,IACf,EAAO,MAAM,6BAA+B,GAC9C,YAAa,CAAC,EAAG,IACf,EAAO,MAAM,sCAAwC,IAMnD,EAAc,AAAC,GACf,EAAS,EACJ,EAEL,EAAS,EACJ,EAEF,EAYF,OAAkB,CA6CvB,YAAY,EAAY,EAAe,EAAe,EAAa,CAzC3D,SAAsB,KAkCtB,eAAiC,GAKjC,aAA+B,GAGrC,KAAK,MAAQ,EACb,KAAK,eAAiB,EAAY,GAClC,KAAK,MAAQ,EACb,KAAK,MAAQ,EAMf,UAAoB,CAClB,MAAO,MAAK,MAAM,UAAY,SAOhC,MAAa,CACX,GAAI,KAAK,WAAY,CACnB,KAAM,GAAQ,KAAK,MAAM,KACvB,KAAK,MAAQ,KAAO,YAAc,KAAK,KAEzC,KAAK,IAAM,EAGX,KAAK,MAAM,OAAO,KAAK,eAAgB,GACvC,KAAK,MAAM,KAAK,KAAK,MAAO,GAG5B,KAAK,MAAM,KAAK,EAAK,mBAAmB,UAAU,KAAK,OAAQ,GAM/D,KAAK,QAAQ,QAAQ,AAAC,GAAS,CAE7B,KAAK,GAAG,OAAQ,GAChB,EAAK,KAEP,KAAK,UAAU,QA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CAAwC,EAAe,MAEzD,OAEF,GAAI,EAAS,KAAM,CACjB,GAAI,KAAK,oBAAoB,EAAS,MACpC,OAGF,KAAK,oBAAoB,EAAS,MAAQ,EAG5C,GAAI,EAAS,eACX,GAAI,CACF,KAAM,MAAK,kBAAkB,EAAyB,UAC/C,EAAP,CACA,EAAO,KACL,sDAAwD,GAK9D,GAAI,EAAS,eACX,GAAI,CACF,KAAM,MAAK,kBAAkB,EAAyB,UAC/C,EAAP,CACA,EAAO,KACL,sDAAwD,WAI5D,EAAS,gBAMT,CAAC,EAAS,eAGV,GAAI,CACF,KAAM,GAAO,EAAS,KACtB,KAAM,IAAI,SAAQ,CAAC,EAAS,IAAW,CACrC,KAAM,GAAQ,GAAI,gBAClB,EAAM,gBACJ,KAAK,gBAAgB,2BAA2B,GAClD,EAAM,iBAAiB,OAAQ,GAC/B,EAAM,iBAAiB,QAAS,AAAC,GAC/B,EAAO,cAAgB,IAEzB,EAAM,iBAAiB,QAAS,AAAC,GAC/B,EAAO,cAAgB,IAEzB,EAAM,KAAK,MAAO,KAAK,oBAAoB,IAC3C,EAAM,eAED,EAAP,CACA,EAAO,KACL,sDAAwD,IAUhE,SAAgB,CACd,KAAK,
|
|
4
|
+
"sourcesContent": ["///<reference path='../types/howler'>\n/*\n * GDevelop JS Platform\n * Copyright 2013-present 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('Audio manager');\n\n const resourceKinds: Array<ResourceKind> = ['audio'];\n\n const HowlParameters: HowlOptions = {\n preload: true,\n onplayerror: (_, error) =>\n logger.error(\"Can't play an audio file: \" + error),\n onloaderror: (_, error) =>\n logger.error('Error while loading an audio file: ' + error),\n };\n\n /**\n * Ensure the volume is between 0 and 1.\n */\n const clampVolume = (volume: float): float => {\n if (volume > 1.0) {\n return 1.0;\n }\n if (volume < 0) {\n return 0;\n }\n return volume;\n };\n\n /**\n * A thin wrapper around a Howl object with:\n * * Handling of callbacks when the sound is not yet loaded.\n * * Automatic clamping when calling `setRate` to ensure a valid value is passed to Howler.js.\n * * Automatic clamping when calling `setVolume` so that the volume is always between 0 and 1.\n *\n * @memberof gdjs\n * @class HowlerSound\n */\n export class HowlerSound {\n /**\n * The ID of the played sound.\n */\n private _id: integer | null = null;\n\n /**\n * The Howl passed to the constructor.\n * It defines the sound file that is being played.\n */\n private _howl: Howl;\n\n /**\n * The **initial** volume at which the sound is being played.\n * Once the sound is started, this volume can be not in sync\n * (in the case the sound is faded by Howler), so volume must\n * be gotten from `this._howl` directly.\n *\n * This value is clamped between 0 and 1.\n */\n private _initialVolume: float;\n\n /**\n * Whether the sound is being played in a loop or not.\n */\n private _loop: boolean;\n\n /**\n * The rate (speed) the sound is being played at.\n * This value is not clamped, though technically Howler.js will only\n * accepts values between a specific range (so we clamp this when\n * passing it to Howler.js, but keep the original value here).\n */\n private _rate: float;\n\n /**\n * An array of callbacks to call once the sound starts to play.\n */\n private _oncePlay: Array<HowlCallback> = [];\n\n /**\n * An array of callbacks to call everytime the sound starts to play.\n */\n private _onPlay: Array<HowlCallback> = [];\n\n constructor(howl: Howl, volume: float, loop: boolean, rate: float) {\n this._howl = howl;\n this._initialVolume = clampVolume(volume);\n this._loop = loop;\n this._rate = rate;\n }\n\n /**\n * Returns true if the associated howl is fully loaded.\n */\n isLoaded(): boolean {\n return this._howl.state() === 'loaded';\n }\n\n /**\n * Begins playback of the sound, or if the Howl is still loading, schedule playing for once it loads.\n * @returns The current instance for chaining.\n */\n play(): this {\n if (this.isLoaded()) {\n const newID = this._howl.play(\n this._id === null ? '__default' : this._id\n );\n this._id = newID;\n\n // Set the howl properties as soon as the sound is played and we have its ID.\n this._howl.volume(this._initialVolume, newID); // this._initialVolume is already clamped between 0 and 1.\n this._howl.loop(this._loop, newID);\n // this._rate is not clamped, but we need to clamp it when passing it to Howler.js as it\n // only supports a specific range.\n this._howl.rate(gdjs.HowlerSoundManager.clampRate(this._rate), newID);\n\n // Manually handle the play event before we have an ID.\n // Before loading, howler won't register events as without an ID we cannot set a listener.\n // Once we have an ID, we can transfer control of the events to howler.\n // We also need to call them once as Howler doesn't for the first play event.\n this._onPlay.forEach((func) => {\n // Transfer the event to howler now that we have an ID\n this.on('play', func);\n func(newID);\n });\n this._oncePlay.forEach((func) => func(newID));\n this._onPlay = [];\n this._oncePlay = [];\n } else this._howl.once('load', () => this.play()); // Play only once the howl is fully loaded\n\n return this;\n }\n\n /**\n * Pauses playback of the sound, saving the seek of playback.\n * @returns The current instance for chaining.\n */\n pause(): this {\n if (this._id !== null) this._howl.pause(this._id);\n return this;\n }\n\n /**\n * Stops playback of the sound, resetting seek to 0.\n * @returns The current instance for chaining.\n */\n stop(): this {\n if (this._id !== null) this._howl.stop(this._id);\n return this;\n }\n\n /**\n * Check if the sound is currently playing.\n * Note that a loading sound is considered as playing (as it will be\n * played as soon as it's loaded). To avoid loading at runtime, prefer\n * to preload the sounds.\n */\n playing(): boolean {\n return (\n (this._id !== null ? this._howl.playing(this._id) : true) ||\n !this.isLoaded() // Loading is considered playing\n );\n }\n\n /**\n * Check if the sound is currently paused.\n */\n paused(): boolean {\n return !this.playing();\n }\n\n /**\n * Check if the sound is currently stopped.\n */\n stopped(): boolean {\n return this.paused() && this.getSeek() === 0;\n }\n\n /**\n * Get the sound playback rate. This 1 for the default speed.\n * This value is not clamped (any value greater than 0 is valid),\n * but the underlying audio system might not play the sound at the required\n * rate if it's very low or very high.\n */\n getRate(): float {\n return this._rate;\n }\n\n /**\n * Set the playback rate.\n * This value is not clamped (any value greater than 0 is valid),\n * but the underlying audio system might not play the sound at the required\n * rate if it's very low or very high.\n * @returns The current instance for chaining.\n */\n setRate(rate: float): this {\n this._rate = rate;\n // If the sound has already started playing, then change the value directly.\n if (this._id !== null) {\n rate = gdjs.HowlerSoundManager.clampRate(rate);\n this._howl.rate(rate, this._id);\n }\n return this;\n }\n\n /**\n * Get if the sound is looping.\n */\n getLoop(): boolean {\n return this._loop;\n }\n\n /**\n * Set if the sound is looping.\n * @returns The current instance for chaining.\n */\n setLoop(loop: boolean): this {\n this._loop = loop;\n // If the sound has already started playing, then change the value directly.\n if (this._id !== null) this._howl.loop(loop, this._id);\n return this;\n }\n\n //TODO: Replace float type in those 2 methods with RangeOf<0..1> once it is standardized (https://github.com/Microsoft/TypeScript/issues/15480)\n /**\n * Get the sound volume.\n * @returns A float from 0 to 1.\n */\n getVolume(): float {\n if (this._id === null) return this._initialVolume;\n return this._howl.volume(this._id);\n }\n\n /**\n * Set the sound volume.\n * @param volume A float from 0 to 1. The value is clamped if too high or too low.\n * @returns The current instance for chaining.\n */\n setVolume(volume: float): this {\n this._initialVolume = clampVolume(volume);\n\n // If the sound has already started playing, then change the value directly.\n if (this._id !== null) this._howl.volume(this._initialVolume, this._id);\n return this;\n }\n\n /**\n * Get if the sound is muted.\n */\n getMute(): boolean {\n if (this._id === null) return false;\n return this._howl.mute(this._id);\n }\n\n /**\n * Set if the sound is muted.\n * @returns The current instance for chaining.\n */\n setMute(mute: boolean): this {\n if (this._id !== null) this._howl.mute(mute, this._id);\n return this;\n }\n\n /**\n * Get the sound seek.\n */\n getSeek(): float {\n if (this._id === null) return 0;\n return this._howl.seek(this._id);\n }\n\n /**\n * Set the sound seek.\n * @returns The current instance for chaining.\n */\n setSeek(seek: float): this {\n if (this._id !== null) this._howl.seek(seek, this._id);\n return this;\n }\n\n /**\n * Get the sound spatial position.\n */\n getSpatialPosition(axis: 'x' | 'y' | 'z'): float {\n if (this._id === null) return 0;\n return this._howl.pos(this._id)[axis === 'x' ? 0 : axis === 'y' ? 1 : 2];\n }\n\n /**\n * Set the sound spatial position.\n * @returns The current instance for chaining.\n */\n setSpatialPosition(x: float, y: float, z: float): this {\n if (this._id !== null) this._howl.pos(x, y, z, this._id);\n return this;\n }\n\n /**\n * Fade the volume sound.\n * @returns The current instance for chaining.\n */\n fade(from: float, to: float, duration: float): this {\n if (this._id !== null)\n this._howl.fade(clampVolume(from), clampVolume(to), duration, this._id);\n return this;\n }\n\n /**\n * Adds an event listener to the howl.\n */\n on(event: HowlEvent, handler: HowlCallback): this {\n if (event === 'play') {\n if (this._id === null) {\n this._onPlay.push(handler);\n } else {\n this._howl.on(event, handler, this._id);\n }\n } else if (this._id === null)\n this.once('play', () => this.on(event, handler));\n else this._howl.on(event, handler, this._id);\n\n return this;\n }\n\n /**\n * Adds an event listener to the howl that removes itself after being called.\n * If the event is `play` and the sound is being played, the handler is\n * called synchronously.\n */\n once(event: HowlEvent, handler: HowlCallback): this {\n if (event === 'play') {\n if (this._id === null) {\n this._oncePlay.push(handler);\n } else if (this.playing()) {\n // Immediately call the handler if the sound is already playing.\n // This is useful for sounds that were just started and have a `.once('play', ...)`\n // handler added on them to set up the volume/rate/loop. If we don't do it\n // synchronously, the sound can play for a tiny bit at the default volume and rate.\n // See https://github.com/4ian/GDevelop/issues/2490.\n handler(this._id);\n } else {\n this._howl.once(event, handler, this._id);\n }\n } else if (this._id === null)\n this.once('play', () => this.once(event, handler));\n else this._howl.once(event, handler, this._id);\n\n return this;\n }\n\n /**\n * Removes an event listener to the howl.\n */\n off(event: HowlEvent, handler: HowlCallback): this {\n if (this._id !== null) this._howl.off(event, handler, this._id);\n return this;\n }\n }\n\n /**\n * HowlerSoundManager is used to manage the sounds and musics of a RuntimeScene.\n *\n * It is basically a container to associate channels to sounds and keep a list\n * of all sounds being played.\n */\n export class HowlerSoundManager {\n _loadedMusics = new gdjs.ResourceCache<Howl>();\n _loadedSounds = new gdjs.ResourceCache<Howl>();\n _availableResources: Record<string, ResourceData> = {};\n _globalVolume: float = 100;\n _sounds: Record<integer, HowlerSound> = {};\n _cachedSpatialPosition: Record<integer, [number, number, number]> = {};\n _musics: Record<integer, HowlerSound> = {};\n _freeSounds: HowlerSound[] = []; // Sounds without an assigned channel.\n _freeMusics: HowlerSound[] = []; // Musics without an assigned channel.\n\n /** Paused sounds or musics that should be played once the game is resumed. */\n _pausedSounds: HowlerSound[] = [];\n _paused: boolean = false;\n\n _resourceLoader: gdjs.ResourceLoader;\n\n /**\n * @param resourceLoader The resources loader of the game.\n */\n constructor(resourceLoader: gdjs.ResourceLoader) {\n this._resourceLoader = resourceLoader;\n\n gdjs.registerRuntimeScenePostEventsCallback(\n this._clearCachedSpatialPosition.bind(this)\n );\n const that = this;\n document.addEventListener('deviceready', function () {\n // pause/resume sounds in Cordova when the app is being paused/resumed\n document.addEventListener(\n 'pause',\n function () {\n that.pauseAllActiveSounds();\n },\n false\n );\n document.addEventListener(\n 'resume',\n function () {\n that.resumeAllActiveSounds();\n },\n false\n );\n });\n }\n\n pauseAllActiveSounds(): void {\n const soundList = this._freeSounds.concat(this._freeMusics);\n for (let key in this._sounds) {\n if (this._sounds.hasOwnProperty(key)) {\n soundList.push(this._sounds[key]);\n }\n }\n for (let key in this._musics) {\n if (this._musics.hasOwnProperty(key)) {\n soundList.push(this._musics[key]);\n }\n }\n for (let i = 0; i < soundList.length; i++) {\n const sound = soundList[i];\n if (!sound.paused() && !sound.stopped()) {\n sound.pause();\n this._pausedSounds.push(sound);\n }\n }\n this._paused = true;\n }\n\n resumeAllActiveSounds(): void {\n try {\n for (let i = 0; i < this._pausedSounds.length; i++) {\n const sound = this._pausedSounds[i];\n if (!sound.stopped()) {\n sound.play();\n }\n }\n } catch (error) {\n if (\n error.message &&\n typeof error.message === 'string' &&\n error.message.startsWith('Maximum call stack size exceeded')\n ) {\n console.warn(\n 'An error occurred when resuming paused sounds while the game was in background:',\n error\n );\n } else {\n throw error;\n }\n }\n this._pausedSounds.length = 0;\n this._paused = false;\n }\n\n getResourceKinds(): ResourceKind[] {\n return resourceKinds;\n }\n\n /**\n * Ensure rate is in a range valid for Howler.js\n * @return The clamped rate\n */\n static clampRate(rate: float): float {\n if (rate > 4.0) {\n return 4.0;\n }\n if (rate < 0.5) {\n return 0.5;\n }\n return rate;\n }\n\n /**\n * Return the file associated to the given sound name.\n *\n * Names and files are loaded from resources when preloadAudio is called. If no\n * file is associated to the given name, then the name will be considered as a\n * filename and will be returned.\n *\n * @return The associated resource\n */\n private _getAudioResource = (resourceName: string): ResourceData => {\n const resource = this._resourceLoader.getResource(resourceName);\n return resource && this.getResourceKinds().includes(resource.kind)\n ? resource\n : ({\n file: resourceName,\n kind: 'audio',\n metadata: '',\n name: resourceName,\n } as ResourceData);\n };\n\n /**\n * @param resource\n * @returns Resource files\n */\n private _getSoundUrlsFromResource(resource: ResourceData): string[] {\n return [this._resourceLoader.getFullUrl(resource.file)];\n }\n\n /**\n * @param resource\n * @returns Resource file\n */\n private _getDefaultSoundUrl(resource: ResourceData): string {\n return this._resourceLoader.getFullUrl(resource.file);\n }\n\n /**\n * Preload audio file\n * @param resource\n * @param isMusic\n */\n private _preloadAudioFile(\n resource: ResourceData,\n isMusic: boolean\n ): Promise<number> {\n const file = resource.file;\n return new Promise((resolve, reject) => {\n const container = isMusic ? this._loadedMusics : this._loadedSounds;\n container[file] = new Howl(\n Object.assign({}, HowlParameters, {\n src: this._getSoundUrlsFromResource(resource),\n onload: resolve,\n onloaderror: (soundId: number, error?: string) => reject(error),\n html5: isMusic,\n xhr: {\n withCredentials:\n this._resourceLoader.checkIfCredentialsRequired(file),\n },\n // Cache the sound with no volume. This avoids a bug where it plays at full volume\n // for a split second before setting its correct volume.\n volume: 0,\n })\n );\n });\n }\n\n /**\n * Store the sound in the specified array, put it at the first index that\n * is free, or add it at the end if no element is free\n * (\"free\" means that the gdjs.HowlerSound can be destroyed).\n *\n * @param arr The array containing the sounds.\n * @param arr The gdjs.HowlerSound to add.\n * @return The gdjs.HowlerSound that have been added (i.e: the second parameter).\n */\n private _storeSoundInArray(\n arr: Array<HowlerSound>,\n sound: HowlerSound\n ): HowlerSound {\n // Try to recycle an old sound.\n for (let i = 0, len = arr.length; i < len; ++i) {\n if (!arr[i] || arr[i].stopped()) {\n arr[i] = sound;\n return sound;\n }\n }\n\n arr.push(sound);\n return sound;\n }\n\n /**\n * Creates a new gdjs.HowlerSound using preloaded/cached Howl instances.\n * @param soundName The name of the file or resource to play.\n * @param isMusic True if a music, false if a sound.\n * @param volume Between 0 and 1.\n * @param loop True if it should be played looping.\n * @param rate speed at which it is played.\n */\n createHowlerSound(\n soundName: string,\n isMusic: boolean,\n volume: float,\n loop: boolean,\n rate: float\n ): HowlerSound {\n const cacheContainer = isMusic ? this._loadedMusics : this._loadedSounds;\n const resource = this._getAudioResource(soundName);\n\n let howl = cacheContainer.get(resource);\n if (!howl) {\n howl = new Howl(\n Object.assign(\n {\n src: this._getSoundUrlsFromResource(resource),\n html5: isMusic,\n xhr: {\n withCredentials:\n this._resourceLoader.checkIfCredentialsRequired(\n resource.file\n ),\n },\n // Cache the sound with no volume. This avoids a bug where it plays at full volume\n // for a split second before setting its correct volume.\n volume: 0,\n },\n HowlParameters\n )\n );\n cacheContainer.set(resource, howl);\n }\n\n return new gdjs.HowlerSound(howl, volume, loop, rate);\n }\n\n /**\n * Preloads a sound or a music in memory.\n * @param soundName The name of the file or resource to preload.\n * @param isMusic True if a music, false if a sound.\n */\n loadAudio(soundName: string, isMusic: boolean) {\n const cacheContainer = isMusic ? this._loadedMusics : this._loadedSounds;\n const resource = this._getAudioResource(soundName);\n\n // Do not reload if it is already loaded.\n if (cacheContainer.get(resource)) {\n return;\n }\n\n cacheContainer.set(\n resource,\n new Howl(\n Object.assign(\n {\n src: this._getSoundUrlsFromResource(resource),\n html5: isMusic,\n xhr: {\n withCredentials:\n this._resourceLoader.checkIfCredentialsRequired(\n resource.file\n ),\n },\n // Cache the sound with no volume. This avoids a bug where it plays at full volume\n // for a split second before setting its correct volume.\n volume: 0,\n },\n HowlParameters\n )\n )\n );\n }\n\n /**\n * Unloads a sound or a music from memory. This will stop any sound/music using it.\n * @param soundName The name of the file or resource to unload.\n * @param isMusic True if a music, false if a sound.\n */\n unloadAudio(soundName: string, isMusic: boolean) {\n const cacheContainer = isMusic ? this._loadedMusics : this._loadedSounds;\n const resource = this._getAudioResource(soundName);\n\n const howl = cacheContainer.get(resource);\n if (!howl) {\n return;\n }\n\n // Make sure any sound using the howl is deleted so\n // that the howl can be garbage collected\n // and no weird \"zombies\" using the unloaded howl can exist.\n function clearContainer(howlerSoundContainer: HowlerSound[]) {\n for (let i in howlerSoundContainer) {\n if (\n howlerSoundContainer[i] &&\n //@ts-ignore We really need to access the raw howl here.\n howlerSoundContainer[i]._howl === howl\n ) {\n howlerSoundContainer[i].stop();\n delete howlerSoundContainer[i];\n }\n }\n }\n\n clearContainer(this._freeMusics);\n clearContainer(this._freeSounds);\n clearContainer(Object.values(this._musics));\n clearContainer(Object.values(this._sounds));\n clearContainer(this._pausedSounds);\n\n howl.unload();\n cacheContainer.delete(resource);\n }\n\n /**\n * Unloads all audio from memory.\n * This will clear the Howl cache.\n * This will also stop any running music or sounds.\n */\n unloadAll() {\n Howler.unload();\n\n // Clean up old sounds that still have the dead Howl instances.\n this._freeSounds.length = 0;\n this._freeMusics.length = 0;\n this._sounds = {};\n this._musics = {};\n this._pausedSounds.length = 0;\n this._loadedMusics.clear();\n this._loadedSounds.clear();\n }\n\n playSound(soundName: string, loop: boolean, volume: float, pitch: float) {\n const sound = this.createHowlerSound(\n soundName,\n /* isMusic= */ false,\n volume / 100,\n loop,\n pitch\n );\n this._storeSoundInArray(this._freeSounds, sound);\n sound.once('play', () => {\n if (this._paused) {\n sound.pause();\n this._pausedSounds.push(sound);\n }\n });\n sound.play();\n }\n\n playSoundOnChannel(\n soundName: string,\n channel: integer,\n loop: boolean,\n volume: float,\n pitch: float\n ) {\n if (this._sounds[channel]) this._sounds[channel].stop();\n\n const sound = this.createHowlerSound(\n soundName,\n /* isMusic= */ false,\n volume / 100,\n loop,\n pitch\n );\n const spatialPosition = this._cachedSpatialPosition[channel];\n if (spatialPosition) {\n sound.once('play', () => {\n sound.setSpatialPosition(...spatialPosition);\n });\n }\n this._sounds[channel] = sound;\n sound.once('play', () => {\n if (this._paused) {\n sound.pause();\n this._pausedSounds.push(sound);\n }\n });\n sound.play();\n }\n\n getSoundOnChannel(channel: integer): HowlerSound | null {\n return this._sounds[channel] || null;\n }\n\n playMusic(soundName: string, loop: boolean, volume: float, pitch: float) {\n const music = this.createHowlerSound(\n soundName,\n /* isMusic= */ true,\n volume / 100,\n loop,\n pitch\n );\n this._storeSoundInArray(this._freeMusics, music);\n music.once('play', () => {\n if (this._paused) {\n music.pause();\n this._pausedSounds.push(music);\n }\n });\n music.play();\n }\n\n playMusicOnChannel(\n soundName: string,\n channel: integer,\n loop: boolean,\n volume: float,\n pitch: float\n ) {\n if (this._musics[channel]) this._musics[channel].stop();\n\n const music = this.createHowlerSound(\n soundName,\n /* isMusic= */ true,\n volume / 100,\n loop,\n pitch\n );\n // Musics are played with the html5 backend, that is not compatible with spatialization.\n this._musics[channel] = music;\n music.once('play', () => {\n if (this._paused) {\n music.pause();\n this._pausedSounds.push(music);\n }\n });\n music.play();\n }\n\n getMusicOnChannel(channel: integer): HowlerSound | null {\n return this._musics[channel] || null;\n }\n\n setSoundSpatialPositionOnChannel(\n channel: number,\n x: number,\n y: number,\n z: number\n ) {\n const sound = this.getSoundOnChannel(channel);\n if (sound && !sound.paused()) sound.setSpatialPosition(x, y, z);\n else {\n // If no sound is playing at the time the method is called, the\n // position is cached and will be used by the `playSoundOnChannel` method\n // to set the spatial position right after the sound starts playing.\n // This cached value is then cleared at the end of the frame.\n // Without this caching strategy, if actions are in the wrong order,\n // the spatial position will not apply to the sound because\n // it is not playing yet.\n this._cachedSpatialPosition[channel] = [x, y, z];\n }\n }\n\n _clearCachedSpatialPosition() {\n this._cachedSpatialPosition = {};\n }\n\n setGlobalVolume(volume: float): void {\n this._globalVolume = volume;\n if (this._globalVolume > 100) {\n this._globalVolume = 100;\n }\n if (this._globalVolume < 0) {\n this._globalVolume = 0;\n }\n Howler.volume(this._globalVolume / 100);\n }\n\n getGlobalVolume(): float {\n return this._globalVolume;\n }\n\n clearAll() {\n Howler.stop();\n\n this._freeSounds.length = 0;\n this._freeMusics.length = 0;\n this._sounds = {};\n this._musics = {};\n this._pausedSounds.length = 0;\n }\n\n async processResource(resourceName: string): Promise<void> {\n // Do nothing because sounds are light enough to be parsed in background.\n }\n\n async loadResource(resourceName: string): Promise<void> {\n const resource = this._resourceLoader.getResource(resourceName);\n if (!resource) {\n logger.warn(\n 'Unable to find audio for resource \"' + resourceName + '\".'\n );\n return;\n }\n if (resource.file) {\n if (this._availableResources[resource.name]) {\n return;\n }\n\n this._availableResources[resource.name] = resource;\n }\n\n if (resource.preloadAsMusic) {\n try {\n await this._preloadAudioFile(resource, /* isMusic= */ true);\n } catch (error) {\n logger.warn(\n 'There was an error while preloading an audio file: ' + error\n );\n }\n }\n\n if (resource.preloadAsSound) {\n try {\n await this._preloadAudioFile(resource, /* isMusic= */ false);\n } catch (error) {\n logger.warn(\n 'There was an error while preloading an audio file: ' + error\n );\n }\n } else if (\n resource.preloadInCache ||\n // Force downloading of sounds.\n // TODO Decide if sounds should be allowed to be downloaded after the scene starts.\n // - they should be requested automatically at the end of the scene loading\n // - they will be downloaded while the scene is playing\n // - other scenes will be pre-loaded only when all the sounds for the current scene are in cache\n !resource.preloadAsMusic\n ) {\n // preloading as sound already does a XHR request, hence \"else if\"\n try {\n const file = resource.file;\n await new Promise((resolve, reject) => {\n const sound = new XMLHttpRequest();\n sound.withCredentials =\n this._resourceLoader.checkIfCredentialsRequired(file);\n sound.addEventListener('load', resolve);\n sound.addEventListener('error', (_) =>\n reject('XHR error: ' + file)\n );\n sound.addEventListener('abort', (_) =>\n reject('XHR abort: ' + file)\n );\n sound.open('GET', this._getDefaultSoundUrl(resource));\n sound.send();\n });\n } catch (error) {\n logger.warn(\n 'There was an error while preloading an audio file: ' + error\n );\n }\n }\n }\n\n /**\n * To be called when the game is disposed.\n * Unloads all audio from memory, clear Howl cache and stop all audio.\n */\n dispose(): void {\n this.unloadAll();\n }\n\n /**\n * Unload the specified list of resources:\n * this unloads all audio from the specified resources from memory.\n *\n * Usually called when scene resoures are unloaded.\n *\n * @param resourcesList The list of specific resources\n */\n unloadResourcesList(resourcesList: ResourceData[]): void {\n resourcesList.forEach((resourceData) => {\n const musicRes = this._loadedMusics.get(resourceData);\n if (musicRes) {\n this.unloadAudio(resourceData.name, true);\n }\n\n const soundRes = this._loadedSounds.get(resourceData);\n if (soundRes) {\n this.unloadAudio(resourceData.name, false);\n }\n });\n }\n }\n\n // Register the class to let the engine use it.\n export const SoundManager = HowlerSoundManager;\n export type SoundManager = HowlerSoundManager;\n}\n"],
|
|
5
|
+
"mappings": "AAMA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,iBAEzB,EAAqC,CAAC,SAEtC,EAA8B,CAClC,QAAS,GACT,YAAa,CAAC,EAAG,IACf,EAAO,MAAM,6BAA+B,GAC9C,YAAa,CAAC,EAAG,IACf,EAAO,MAAM,sCAAwC,IAMnD,EAAc,AAAC,GACf,EAAS,EACJ,EAEL,EAAS,EACJ,EAEF,EAYF,OAAkB,CA6CvB,YAAY,EAAY,EAAe,EAAe,EAAa,CAzC3D,SAAsB,KAkCtB,eAAiC,GAKjC,aAA+B,GAGrC,KAAK,MAAQ,EACb,KAAK,eAAiB,EAAY,GAClC,KAAK,MAAQ,EACb,KAAK,MAAQ,EAMf,UAAoB,CAClB,MAAO,MAAK,MAAM,UAAY,SAOhC,MAAa,CACX,GAAI,KAAK,WAAY,CACnB,KAAM,GAAQ,KAAK,MAAM,KACvB,KAAK,MAAQ,KAAO,YAAc,KAAK,KAEzC,KAAK,IAAM,EAGX,KAAK,MAAM,OAAO,KAAK,eAAgB,GACvC,KAAK,MAAM,KAAK,KAAK,MAAO,GAG5B,KAAK,MAAM,KAAK,EAAK,mBAAmB,UAAU,KAAK,OAAQ,GAM/D,KAAK,QAAQ,QAAQ,AAAC,GAAS,CAE7B,KAAK,GAAG,OAAQ,GAChB,EAAK,KAEP,KAAK,UAAU,QAAQ,AAAC,GAAS,EAAK,IACtC,KAAK,QAAU,GACf,KAAK,UAAY,OACZ,MAAK,MAAM,KAAK,OAAQ,IAAM,KAAK,QAE1C,MAAO,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,EAG5C,GAAI,EAAS,eACX,GAAI,CACF,KAAM,MAAK,kBAAkB,EAAyB,UAC/C,EAAP,CACA,EAAO,KACL,sDAAwD,GAK9D,GAAI,EAAS,eACX,GAAI,CACF,KAAM,MAAK,kBAAkB,EAAyB,UAC/C,EAAP,CACA,EAAO,KACL,sDAAwD,WAI5D,EAAS,gBAMT,CAAC,EAAS,eAGV,GAAI,CACF,KAAM,GAAO,EAAS,KACtB,KAAM,IAAI,SAAQ,CAAC,EAAS,IAAW,CACrC,KAAM,GAAQ,GAAI,gBAClB,EAAM,gBACJ,KAAK,gBAAgB,2BAA2B,GAClD,EAAM,iBAAiB,OAAQ,GAC/B,EAAM,iBAAiB,QAAS,AAAC,GAC/B,EAAO,cAAgB,IAEzB,EAAM,iBAAiB,QAAS,AAAC,GAC/B,EAAO,cAAgB,IAEzB,EAAM,KAAK,MAAO,KAAK,oBAAoB,IAC3C,EAAM,eAED,EAAP,CACA,EAAO,KACL,sDAAwD,IAUhE,SAAgB,CACd,KAAK,YAWP,oBAAoB,EAAqC,CACvD,EAAc,QAAQ,AAAC,GAAiB,CAEtC,AAAI,AADa,KAAK,cAAc,IAAI,IAEtC,KAAK,YAAY,EAAa,KAAM,IAIlC,AADa,KAAK,cAAc,IAAI,IAEtC,KAAK,YAAY,EAAa,KAAM,OAhlBrC,EAAM,qBAulBA,eAAe,IAh8BpB",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(
|
|
1
|
+
var gdjs;(function(l){const c=new l.Logger("JSON Manager"),i=["json","tilemap","tileset"];class d{constructor(o){this._loadedJsons=new l.ResourceCache;this._callbacks=new l.ResourceCache;this._getJsonResource=o=>{const e=this._resourceLoader.getResource(o);return e&&this.getResourceKinds().includes(e.kind)?e:null};this._resourceLoader=o}getResourceKinds(){return i}async loadResource(o){const e=this._resourceLoader.getResource(o);if(!e){c.warn('Unable to find json for resource "'+o+'".');return}if(!e.disablePreload)try{await this.loadJsonAsync(e.name)}catch(s){c.error(`Error while preloading json resource ${e.name}:`,s)}}loadJsonAsync(o){const e=this;return new Promise((s,t)=>{e.loadJson(o,(r,n)=>{r&&t(r.message),s(n)})})}async processResource(o){}loadJson(o,e){const s=this._getJsonResource(o);if(!s){e(new Error(`Can't find resource with name: "`+o+'" (or is not a json resource).'),null);return}if(this._loadedJsons.get(s)){e(null,this._loadedJsons.get(s));return}{const n=this._callbacks.get(s);if(n){n.push(e);return}else this._callbacks.set(s,[e])}const t=this,r=new XMLHttpRequest;r.responseType="json",r.withCredentials=this._resourceLoader.checkIfCredentialsRequired(s.file),r.open("GET",this._resourceLoader.getFullUrl(s.file)),r.onload=function(){const n=t._callbacks.get(s);if(!!n){if(r.status!==200){for(const a of n)a(new Error("HTTP error: "+r.status+"("+r.statusText+")"),null);t._callbacks.delete(s);return}t._loadedJsons.set(s,r.response);for(const a of n)a(null,r.response);t._callbacks.delete(s)}},r.onerror=function(){const n=t._callbacks.get(s);if(!!n){for(const a of n)a(new Error("Network error"),null);t._callbacks.delete(s)}},r.onabort=function(){const n=t._callbacks.get(s);if(!!n){for(const a of n)a(new Error("Request aborted"),null);t._callbacks.delete(s)}},r.send()}isJsonLoaded(o){return!!this._loadedJsons.getFromName(o)}getLoadedJson(o){return this._loadedJsons.getFromName(o)||null}dispose(){this._loadedJsons.clear(),this._callbacks.clear()}unloadResourcesList(o){o.forEach(e=>{this._loadedJsons.get(e)&&this._loadedJsons.delete(e),this._callbacks.get(e)&&this._callbacks.delete(e)})}}l.JsonManager=d})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=jsonmanager.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../GDevelop/GDJS/Runtime/jsonmanager.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * GDevelop JS Platform\n * Copyright 2013-present 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('JSON Manager');\n\n /** The callback called when a json that was requested is loaded (or an error occurred). */\n export type JsonManagerRequestCallback = (\n error: Error | null,\n content: Object | null\n ) => void;\n\n const resourceKinds: Array<ResourceKind> = ['json', 'tilemap', 'tileset'];\n /**\n * JsonManager loads json files (using `XMLHttpRequest`), using the \"json\" resources\n * registered in the game resources.\n *\n * Contrary to audio/fonts, json files are loaded asynchronously, when requested.\n * You should properly handle errors, and give the developer/player a way to know\n * that loading failed.\n */\n export class JsonManager implements gdjs.ResourceManager {\n _resourceLoader: ResourceLoader;\n\n _loadedJsons = new gdjs.ResourceCache<Object>();\n _callbacks = new gdjs.ResourceCache<Array<JsonManagerRequestCallback>>();\n\n /**\n * @param resourceLoader The resources loader of the game.\n */\n constructor(resourceLoader: gdjs.ResourceLoader) {\n this._resourceLoader = resourceLoader;\n }\n\n getResourceKinds(): ResourceKind[] {\n return resourceKinds;\n }\n\n /**\n * Request all the json resources to be preloaded (unless they are marked as not preloaded).\n *\n * Note that even if a JSON is already loaded, it will be reloaded (useful for hot-reloading,\n * as JSON files can have been modified without the editor knowing).\n */\n async loadResource(resourceName: string): Promise<void> {\n const resource = this._resourceLoader.getResource(resourceName);\n if (!resource) {\n logger.warn('Unable to find json for resource \"' + resourceName + '\".');\n return;\n }\n if (resource.disablePreload) {\n return;\n }\n\n try {\n await this.loadJsonAsync(resource.name);\n } catch (error) {\n logger.error(\n `Error while preloading json resource ${resource.name}:`,\n error\n );\n }\n }\n\n loadJsonAsync(resourceName: string): Promise<Object | null> {\n const that = this;\n return new Promise((resolve, reject) => {\n that.loadJson(resourceName, (error, content) => {\n if (error) {\n reject(error.message);\n }\n resolve(content);\n });\n });\n }\n\n private _getJsonResource = (resourceName: string): ResourceData | null => {\n const resource = this._resourceLoader.getResource(resourceName);\n return resource && this.getResourceKinds().includes(resource.kind)\n ? resource\n : null;\n };\n\n async processResource(resourceName: string): Promise<void> {\n // Do nothing because json are light enough to be parsed in background.\n }\n\n /**\n * Request the json file from the given resource name.\n * This method is asynchronous. When loaded, the `callback` is called with the error\n * (null if none) and the loaded json (a JS Object).\n *\n * @param resourceName The resource pointing to the json file to load.\n * @param callback The callback function called when json is loaded (or an error occurred).\n */\n loadJson(resourceName: string, callback: JsonManagerRequestCallback): void {\n const resource = this._getJsonResource(resourceName);\n if (!resource) {\n callback(\n new Error(\n 'Can\\'t find resource with name: \"' +\n resourceName +\n '\" (or is not a json resource).'\n ),\n null\n );\n return;\n }\n\n // Don't fetch again an object that is already in memory\n if (this._loadedJsons.get(resource)) {\n callback(null, this._loadedJsons.get(resource));\n return;\n }\n // Don't fetch again an object that is already being fetched.\n {\n const callbacks = this._callbacks.get(resource);\n if (callbacks) {\n callbacks.push(callback);\n return;\n } else {\n this._callbacks.set(resource, [callback]);\n }\n }\n\n const that = this;\n const xhr = new XMLHttpRequest();\n xhr.responseType = 'json';\n xhr.withCredentials = this._resourceLoader.checkIfCredentialsRequired(\n resource.file\n );\n xhr.open('GET', this._resourceLoader.getFullUrl(resource.file));\n xhr.onload = function () {\n const callbacks = that._callbacks.get(resource);\n if (!callbacks) {\n return;\n }\n if (xhr.status !== 200) {\n for (const callback of callbacks) {\n callback(\n new Error(\n 'HTTP error: ' + xhr.status + '(' + xhr.statusText + ')'\n ),\n null\n );\n }\n that._callbacks.delete(resource);\n return;\n }\n\n // Cache the result\n that._loadedJsons.set(resource, xhr.response);\n for (const callback of callbacks) {\n callback(null, xhr.response);\n }\n that._callbacks.delete(resource);\n };\n xhr.onerror = function () {\n const callbacks = that._callbacks.get(resource);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n callback(new Error('Network error'), null);\n }\n that._callbacks.delete(resource);\n };\n xhr.onabort = function () {\n const callbacks = that._callbacks.get(resource);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n callback(new Error('Request aborted'), null);\n }\n that._callbacks.delete(resource);\n };\n xhr.send();\n }\n\n /**\n * Check if the given json resource was loaded (preloaded or loaded with `loadJson`).\n * @param resourceName The name of the json resource.\n * @returns true if the content of the json resource is loaded. false otherwise.\n */\n isJsonLoaded(resourceName: string): boolean {\n return !!this._loadedJsons.getFromName(resourceName);\n }\n\n /**\n * Get the object for the given resource that is already loaded (preloaded or loaded with `loadJson`).\n * If the resource is not loaded, `null` will be returned.\n *\n * @param resourceName The name of the json resource.\n * @returns the content of the json resource, if loaded. `null` otherwise.\n */\n getLoadedJson(resourceName: string): Object | null {\n return this._loadedJsons.getFromName(resourceName) || null;\n }\n\n /**\n * To be called when the game is disposed.\n * Clear the JSONs loaded in this manager.\n */\n dispose(): void {\n this._loadedJsons.clear();\n this._callbacks.clear();\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,gBAQzB,EAAqC,CAAC,OAAQ,UAAW,WASxD,OAAkD,CASvD,YAAY,EAAqC,CANjD,kBAAe,GAAI,GAAK,cACxB,gBAAa,GAAI,GAAK,cAmDd,sBAAmB,AAAC,GAA8C,CACxE,KAAM,GAAW,KAAK,gBAAgB,YAAY,GAClD,MAAO,IAAY,KAAK,mBAAmB,SAAS,EAAS,MACzD,EACA,MAjDJ,KAAK,gBAAkB,EAGzB,kBAAmC,CACjC,MAAO,QASH,cAAa,EAAqC,CACtD,KAAM,GAAW,KAAK,gBAAgB,YAAY,GAClD,GAAI,CAAC,EAAU,CACb,EAAO,KAAK,qCAAuC,EAAe,MAClE,OAEF,GAAI,GAAS,eAIb,GAAI,CACF,KAAM,MAAK,cAAc,EAAS,YAC3B,EAAP,CACA,EAAO,MACL,wCAAwC,EAAS,QACjD,IAKN,cAAc,EAA8C,CAC1D,KAAM,GAAO,KACb,MAAO,IAAI,SAAQ,CAAC,EAAS,IAAW,CACtC,EAAK,SAAS,EAAc,CAAC,EAAO,IAAY,CAC9C,AAAI,GACF,EAAO,EAAM,SAEf,EAAQ,YAYR,iBAAgB,EAA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aAAa,YAAY,IAAiB,KAOxD,SAAgB,CACd,KAAK,aAAa,QAClB,KAAK,WAAW,
|
|
4
|
+
"sourcesContent": ["/*\n * GDevelop JS Platform\n * Copyright 2013-present 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('JSON Manager');\n\n /** The callback called when a json that was requested is loaded (or an error occurred). */\n export type JsonManagerRequestCallback = (\n error: Error | null,\n content: Object | null\n ) => void;\n\n const resourceKinds: Array<ResourceKind> = ['json', 'tilemap', 'tileset'];\n /**\n * JsonManager loads json files (using `XMLHttpRequest`), using the \"json\" resources\n * registered in the game resources.\n *\n * Contrary to audio/fonts, json files are loaded asynchronously, when requested.\n * You should properly handle errors, and give the developer/player a way to know\n * that loading failed.\n */\n export class JsonManager implements gdjs.ResourceManager {\n _resourceLoader: ResourceLoader;\n\n _loadedJsons = new gdjs.ResourceCache<Object>();\n _callbacks = new gdjs.ResourceCache<Array<JsonManagerRequestCallback>>();\n\n /**\n * @param resourceLoader The resources loader of the game.\n */\n constructor(resourceLoader: gdjs.ResourceLoader) {\n this._resourceLoader = resourceLoader;\n }\n\n getResourceKinds(): ResourceKind[] {\n return resourceKinds;\n }\n\n /**\n * Request all the json resources to be preloaded (unless they are marked as not preloaded).\n *\n * Note that even if a JSON is already loaded, it will be reloaded (useful for hot-reloading,\n * as JSON files can have been modified without the editor knowing).\n */\n async loadResource(resourceName: string): Promise<void> {\n const resource = this._resourceLoader.getResource(resourceName);\n if (!resource) {\n logger.warn('Unable to find json for resource \"' + resourceName + '\".');\n return;\n }\n if (resource.disablePreload) {\n return;\n }\n\n try {\n await this.loadJsonAsync(resource.name);\n } catch (error) {\n logger.error(\n `Error while preloading json resource ${resource.name}:`,\n error\n );\n }\n }\n\n loadJsonAsync(resourceName: string): Promise<Object | null> {\n const that = this;\n return new Promise((resolve, reject) => {\n that.loadJson(resourceName, (error, content) => {\n if (error) {\n reject(error.message);\n }\n resolve(content);\n });\n });\n }\n\n private _getJsonResource = (resourceName: string): ResourceData | null => {\n const resource = this._resourceLoader.getResource(resourceName);\n return resource && this.getResourceKinds().includes(resource.kind)\n ? resource\n : null;\n };\n\n async processResource(resourceName: string): Promise<void> {\n // Do nothing because json are light enough to be parsed in background.\n }\n\n /**\n * Request the json file from the given resource name.\n * This method is asynchronous. When loaded, the `callback` is called with the error\n * (null if none) and the loaded json (a JS Object).\n *\n * @param resourceName The resource pointing to the json file to load.\n * @param callback The callback function called when json is loaded (or an error occurred).\n */\n loadJson(resourceName: string, callback: JsonManagerRequestCallback): void {\n const resource = this._getJsonResource(resourceName);\n if (!resource) {\n callback(\n new Error(\n 'Can\\'t find resource with name: \"' +\n resourceName +\n '\" (or is not a json resource).'\n ),\n null\n );\n return;\n }\n\n // Don't fetch again an object that is already in memory\n if (this._loadedJsons.get(resource)) {\n callback(null, this._loadedJsons.get(resource));\n return;\n }\n // Don't fetch again an object that is already being fetched.\n {\n const callbacks = this._callbacks.get(resource);\n if (callbacks) {\n callbacks.push(callback);\n return;\n } else {\n this._callbacks.set(resource, [callback]);\n }\n }\n\n const that = this;\n const xhr = new XMLHttpRequest();\n xhr.responseType = 'json';\n xhr.withCredentials = this._resourceLoader.checkIfCredentialsRequired(\n resource.file\n );\n xhr.open('GET', this._resourceLoader.getFullUrl(resource.file));\n xhr.onload = function () {\n const callbacks = that._callbacks.get(resource);\n if (!callbacks) {\n return;\n }\n if (xhr.status !== 200) {\n for (const callback of callbacks) {\n callback(\n new Error(\n 'HTTP error: ' + xhr.status + '(' + xhr.statusText + ')'\n ),\n null\n );\n }\n that._callbacks.delete(resource);\n return;\n }\n\n // Cache the result\n that._loadedJsons.set(resource, xhr.response);\n for (const callback of callbacks) {\n callback(null, xhr.response);\n }\n that._callbacks.delete(resource);\n };\n xhr.onerror = function () {\n const callbacks = that._callbacks.get(resource);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n callback(new Error('Network error'), null);\n }\n that._callbacks.delete(resource);\n };\n xhr.onabort = function () {\n const callbacks = that._callbacks.get(resource);\n if (!callbacks) {\n return;\n }\n for (const callback of callbacks) {\n callback(new Error('Request aborted'), null);\n }\n that._callbacks.delete(resource);\n };\n xhr.send();\n }\n\n /**\n * Check if the given json resource was loaded (preloaded or loaded with `loadJson`).\n * @param resourceName The name of the json resource.\n * @returns true if the content of the json resource is loaded. false otherwise.\n */\n isJsonLoaded(resourceName: string): boolean {\n return !!this._loadedJsons.getFromName(resourceName);\n }\n\n /**\n * Get the object for the given resource that is already loaded (preloaded or loaded with `loadJson`).\n * If the resource is not loaded, `null` will be returned.\n *\n * @param resourceName The name of the json resource.\n * @returns the content of the json resource, if loaded. `null` otherwise.\n */\n getLoadedJson(resourceName: string): Object | null {\n return this._loadedJsons.getFromName(resourceName) || null;\n }\n\n /**\n * To be called when the game is disposed.\n * Clear the JSONs loaded in this manager.\n */\n dispose(): void {\n this._loadedJsons.clear();\n this._callbacks.clear();\n }\n\n /**\n * Unload the specified list of resources:\n * this clears the JSONs loaded in this manager.\n *\n * Usually called when scene resoures are unloaded.\n * @param resourcesList The list of specific resources\n */\n unloadResourcesList(resourcesList: ResourceData[]): void {\n resourcesList.forEach((resourceData) => {\n const loadedJson = this._loadedJsons.get(resourceData);\n if (loadedJson) {\n this._loadedJsons.delete(resourceData);\n }\n\n const callback = this._callbacks.get(resourceData);\n if (callback) {\n this._callbacks.delete(resourceData);\n }\n });\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAKA,GAAU,MAAV,UAAU,EAAV,CACE,KAAM,GAAS,GAAI,GAAK,OAAO,gBAQzB,EAAqC,CAAC,OAAQ,UAAW,WASxD,OAAkD,CASvD,YAAY,EAAqC,CANjD,kBAAe,GAAI,GAAK,cACxB,gBAAa,GAAI,GAAK,cAmDd,sBAAmB,AAAC,GAA8C,CACxE,KAAM,GAAW,KAAK,gBAAgB,YAAY,GAClD,MAAO,IAAY,KAAK,mBAAmB,SAAS,EAAS,MACzD,EACA,MAjDJ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AAI,UAErB,EAAK,WAAW,OAAO,KAEzB,EAAI,QAAU,UAAY,CACxB,KAAM,GAAY,EAAK,WAAW,IAAI,GACtC,GAAI,EAAC,EAGL,UAAW,KAAY,GACrB,EAAS,GAAI,OAAM,iBAAkB,MAEvC,EAAK,WAAW,OAAO,KAEzB,EAAI,QAAU,UAAY,CACxB,KAAM,GAAY,EAAK,WAAW,IAAI,GACtC,GAAI,EAAC,EAGL,UAAW,KAAY,GACrB,EAAS,GAAI,OAAM,mBAAoB,MAEzC,EAAK,WAAW,OAAO,KAEzB,EAAI,OAQN,aAAa,EAA+B,CAC1C,MAAO,CAAC,CAAC,KAAK,aAAa,YAAY,GAUzC,cAAc,EAAqC,CACjD,MAAO,MAAK,aAAa,YAAY,IAAiB,KAOxD,SAAgB,CACd,KAAK,aAAa,QAClB,KAAK,WAAW,QAUlB,oBAAoB,EAAqC,CACvD,EAAc,QAAQ,AAAC,GAAiB,CAEtC,AAAI,AADe,KAAK,aAAa,IAAI,IAEvC,KAAK,aAAa,OAAO,GAIvB,AADa,KAAK,WAAW,IAAI,IAEnC,KAAK,WAAW,OAAO,MA5MxB,EAAM,gBAlBL",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/Runtime/logger.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var gdjs;(function(l){const
|
|
1
|
+
var gdjs;(function(l){const i={info:console.log,warning:console.warn,error:console.error};class g{constructor(){this.discardedConsoleGroups=new Set}discardGroup(r){this.discardedConsoleGroups.add(r)}enableGroup(r){this.discardedConsoleGroups.delete(r)}log(r,n,u="info",d=!0){if(this.discardedConsoleGroups.has(r))return;(i[u]||i.info)(`[${r}] ${n}`)}}const s=new g;let e=s;function o(t){return t.reduce((r,n)=>r+n.toString(),"")}class a{constructor(r){this.enabled=!0;this.group=r}log(...r){!this.enabled||e.log(this.group,o(r),"info")}info(...r){!this.enabled||e.log(this.group,o(r),"info")}warn(...r){!this.enabled||e.log(this.group,o(r),"warning")}error(...r){!this.enabled||e.log(this.group,o(r),"error")}enable(r){return this.enabled=r,this}static getDefaultConsoleLoggerOutput(){return s}static getLoggerOutput(){return e}static setLoggerOutput(r){e=r}}l.Logger=a})(gdjs||(gdjs={}));
|
|
2
2
|
//# sourceMappingURL=logger.js.map
|