@combos-fun/engine 0.1.21 → 0.1.23
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/engine.cjs.js +70 -12
- package/dist/engine.cjs.js.map +1 -1
- package/dist/engine.cjs.prod.js +1 -1
- package/dist/engine.d.ts +39 -8
- package/dist/engine.esm.js +69 -13
- package/dist/engine.esm.js.map +1 -1
- package/package.json +3 -3
package/dist/engine.cjs.prod.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("eventemitter3"),t=require("lodash-es"),s=require("resource-loader");function r(e){return e&&e.__esModule?e:{default:e}}var o,n=r(e);class a extends n.default{get game(){return this.gameObject?.scene?.game}constructor(e){super(),this.started=!1;const t=this.constructor;this.name=t.componentName,this.__componentDefaultParams=e}}exports.OBSERVER_TYPE=void 0,(o=exports.OBSERVER_TYPE||(exports.OBSERVER_TYPE={})).ADD="ADD",o.REMOVE="REMOVE",o.CHANGE="CHANGE";const i={},c={},p={},l={};function m(e,t){i[e.gameObject.id]||(i[e.gameObject.id]={});const s=i[e.gameObject.id],r=e.name+"_"+t.join(",");if(s[r])return s[r];const o=t.length-1;let n=e;for(let e=0;e<o;e++){if(void 0===n[t[e]]||null===n[t[e]])return{property:void 0,key:void 0};n=n[t[e]]}return s[r]={property:n,key:t[o]},s[r]}function u({systemName:e,componentName:t,component:s,prop:r,type:o,gameObject:n}){c[e]?.componentObserver?.add({component:s,prop:r,type:o,componentName:t,gameObject:n})}const h="GameObject";function d(e,t,s=exports.OBSERVER_TYPE.CHANGE){if(!e)return;const r={prop:[t],deep:!1};for(const o in p){const n=p[o]?.[h];n?.some(e=>e.prop[0]===t)&&u({systemName:o,componentName:h,component:void 0,gameObject:e,prop:r,type:s})}}function f({obj:e,key:s,prop:r,component:o,componentName:n}){if(void 0!==e)if(s in e){if(Object.defineProperty(e,`_${s}`,{enumerable:!1,writable:!0,value:e[s]}),r.deep&&t.isObject(e[s]))for(const t of Object.keys(e[s]))f({obj:e[s],key:t,prop:r,component:o,componentName:n});Object.defineProperty(e,s,{enumerable:!0,set(a){e[`_${s}`]!==a&&(e[`_${s}`]=a,function({prop:e,component:s,componentName:r}){for(const o in p){const n=(p[o]||{})[r];n&&(n.findIndex(s=>t.isEqual(s,e))>-1&&u({systemName:o,componentName:r,component:s,prop:e,type:exports.OBSERVER_TYPE.CHANGE}))}}({prop:r,component:o,componentName:n}))},get:()=>e[`_${s}`]})}else console.error(`prop ${s} not in component: ${n}, Can not observer`)}function y(e,t=e.name){for(const s in p){(p[s]||{})[t]&&c[s]?.componentObserver?.add({component:e,type:exports.OBSERVER_TYPE.REMOVE,componentName:t})}!function(e){e.gameObject&&delete i[e.gameObject.id]}(e)}let g=0;class E{constructor(e){this._parent=null,this._componentCache={},this.children=[],this.inScene=!1,this.components=[],this.destroyed=!1,this._name=e,this.id=++g}get parent(){return this._parent}get name(){return this._name}set scene(e){if(this._scene===e)return;const t=this._scene;this._scene=e;for(const t of this.children)t.scene=e;e?e.addGameObject(this):t&&t.removeGameObject(this)}get scene(){return this._scene}addChild(e){if(e&&e!==this){if(!(e instanceof E))throw new Error("addChild only receive GameObject");if(this.destroyed)throw new Error(`gameObject '${this.name}' has been destroy`);if(e.parent===this){const t=this.children.indexOf(e);return t>-1&&this.children.splice(t,1),void this.children.push(e)}e.parent&&e.parent.removeChild(e),e._parent=this,this.children.push(e),e.scene=this.scene,d(e,"parent",exports.OBSERVER_TYPE.CHANGE)}}removeChild(e){if(!(e instanceof E&&e.parent&&e.parent===this))return e;const t=this.children.indexOf(e);return t>-1&&this.children.splice(t,1),e._parent=null,e.scene=null,d(e,"parent",exports.OBSERVER_TYPE.CHANGE),e}addComponent(e,t){if(this.destroyed)return;const s=function(e){return e instanceof a?e.name:e instanceof Function?e.componentName:void 0}(e);if(this._componentCache[s])return;let r;if(e instanceof Function)r=new e(t);else{if(!(e instanceof a))throw new Error("addComponent recieve Component and Component Constructor");r=e}if(r.gameObject)throw new Error(`component has been added on gameObject ${r.gameObject.name}`);return r.gameObject=this,r.init&&r.init(r.__componentDefaultParams),function(e,t=e.name){for(const s in p)(p[s]||{})[t]&&c[s]?.componentObserver?.add({component:e,type:exports.OBSERVER_TYPE.ADD,componentName:t})}(r,r.name),function(e,t=e.name){if(t&&l[t]){if(!(e&&(s=e,s&&s.constructor&&"componentName"in s.constructor)))throw new Error("component param must be an instance of Component");var s;if(!e.gameObject||!e.gameObject.id)throw new Error("component should be add to a gameObject");for(const s of l[t]){const{property:r,key:o}=m(e,s.prop);f({obj:r,key:o,prop:s,component:e,componentName:t})}}}(r,r.name),this.components.push(r),this._componentCache[s]=r,r.awake&&r.awake(),r}removeComponent(e){let t;return"string"==typeof e?t=e:e instanceof a?t=e.name:e.componentName&&(t=e.componentName),this._removeComponent(t)}_removeComponent(e){const t=this.components.findIndex(({name:t})=>t===e);if(-1===t)return;const s=this.components.splice(t,1)[0];return delete this._componentCache[e],delete s.__componentDefaultParams,s.onDestroy&&s.onDestroy(),y(s,e),s.gameObject=void 0,s}getComponent(e){let t;return"string"==typeof e?t=e:e instanceof a?t=e.name:e.componentName&&(t=e.componentName),void 0!==this._componentCache[t]?this._componentCache[t]:void 0}remove(){if(this.parent)return this.parent.removeChild(this)}destroy(){if(this.destroyed)console.error("Cannot destroy gameObject that have already been destroyed.");else{Array.from(this.children).forEach(e=>{e.destroy()}),this.remove(),this.children.length=0;for(const e in this._componentCache)this._removeComponent(e);this.components.length=0,this.destroyed=!0}}}class b{constructor(){this.events=[]}add({component:e,prop:s,type:r,componentName:o,gameObject:n}){const a=n??e?.gameObject;if(r===exports.OBSERVER_TYPE.REMOVE){const t=t=>e?t.component===e:t.gameObject===a&&t.componentName===o;if(this.events.find(e=>t(e)&&e.type===exports.OBSERVER_TYPE.ADD))return void(this.events=this.events.filter(e=>!t(e)));this.events=this.events.filter(e=>!t(e))}const i=this.events.findIndex(n=>n.gameObject===a&&n.component===e&&n.componentName===o&&t.isEqual(n.prop,s)&&n.type===r);i>-1&&this.events.splice(i,1),this.events.push({gameObject:a,component:e,prop:s,type:r,componentName:o})}getChanged(){return this.events}get changed(){return this.events}clear(){const e=this.events;return this.events=[],e}}class R{constructor(e){this.started=!1,this.componentObserver=new b,this.__systemDefaultParams=e;const t=this.constructor;this.name=t.systemName}destroy(){this.componentObserver=null,this.__systemDefaultParams=null,this.onDestroy?.()}}const x=function(){let e=null;return e=Date.now?Date.now:()=>(new Date).getTime(),e}(),S={originTime:0,playbackRate:1};class _{constructor(e,t){e instanceof _&&(t=e,e={}),e=Object.assign({},S,e),t&&(this._parent=t),this._createTime=x(),this._timeMark=[{globalTime:this.globalTime,localTime:-e.originTime,entropy:-e.originTime,playbackRate:e.playbackRate,globalEntropy:0}],this._parent&&(this._timeMark[0].globalEntropy=this._parent.entropy),this._playbackRate=e.playbackRate}get globalTime(){return this.parent?this.parent.currentTime:x()-this._createTime}get parent(){return this._parent}get lastTimeMark(){return this._timeMark[this._timeMark.length-1]}markTime({time:e=this.currentTime,entropy:t=this.entropy,playbackRate:s=this.playbackRate}={}){const r={globalTime:this.globalTime,localTime:e,entropy:t,playbackRate:s,globalEntropy:this.globalEntropy};this._timeMark.push(r)}get currentTime(){const{localTime:e,globalTime:t}=this.lastTimeMark;return e+(this.globalTime-t)*this.playbackRate}set currentTime(e){this.markTime({time:e})}get globalEntropy(){return this._parent?this._parent.entropy:this.globalTime}get entropy(){const{entropy:e,globalEntropy:t}=this.lastTimeMark;return e+Math.abs((this.globalEntropy-t)*this.playbackRate)}set entropy(e){if(this.entropy>e){const t=this.seekTimeMark(e);this._timeMark.length=t+1}this.markTime({entropy:e})}fork(e){return new _(e,this)}seekGlobalTime(e){const t=this.seekTimeMark(e),s=this._timeMark[t],{entropy:r,playbackRate:o,globalTime:n}=s;return n+(e-r)/Math.abs(o)}seekLocalTime(e){const t=this.seekTimeMark(e),s=this._timeMark[t],{localTime:r,entropy:o,playbackRate:n}=s;return n>0?r+(e-o):r-(e-o)}seekTimeMark(e){const t=this._timeMark;let s=0,r=t.length-1;if(e<=t[s].entropy)return s;if(e>=t[r].entropy)return r;let o=Math.floor((s+r)/2);for(;o>s&&o<r;){if(e===t[o].entropy)return o;e<t[o].entropy?r=o:e>t[o].entropy&&(s=o),o=Math.floor((s+r)/2)}return s}get playbackRate(){return this._playbackRate}set playbackRate(e){e!==this.playbackRate&&(this.markTime({playbackRate:e}),this._playbackRate=e)}get paused(){if(0===this.playbackRate)return!0;let e=this.parent;for(;e;){if(0===e.playbackRate)return!0;e=e.parent}return!1}}const O={autoStart:!0,frameRate:60};class T{constructor(e){e=Object.assign({},O,e),this._frameCount=0,this._frameDuration=1e3/e.frameRate,this.autoStart=e.autoStart,this.frameRate=e.frameRate,this.timeline=new _({originTime:0,playbackRate:1}),this._lastFrameTime=this.timeline.currentTime,this._tickers=new Set,this._requestId=null,this._ticker=()=>{this._started&&(this._requestId=requestAnimationFrame(this._ticker),this.update())},this.autoStart&&this.start()}update(){const e=this.timeline.currentTime,t=e-this._lastFrameTime;if(t>=this._frameDuration){const s=e-t%this._frameDuration,r=s-this._lastFrameTime;this._lastFrameTime=s;const o={deltaTime:r,delta:r,time:s,currentTime:s,frameCount:++this._frameCount,fps:Math.round(1e3/r)};for(const e of this._tickers)"function"==typeof e&&e(o)}}add(e){this._tickers.add(e)}remove(e){this._tickers.delete(e)}start(){this._started||(this._started=!0,this.timeline.playbackRate=1,this._requestId=requestAnimationFrame(this._ticker))}pause(){this._started=!1,this.timeline.playbackRate=0}setPlaybackRate(e){this.timeline.playbackRate=e}}class k extends E{constructor(e){super(e),this.gameObjects=[],this.scene=this}addGameObject(e){this.gameObjects.push(e),e.inScene||(e.inScene=!0,d(e,"inScene",exports.OBSERVER_TYPE.CHANGE))}removeGameObject(e){const t=this.gameObjects.indexOf(e);-1!==t&&(e.inScene&&(e.inScene=!1,d(e,"inScene",exports.OBSERVER_TYPE.CHANGE)),this.gameObjects.splice(t,1))}destroy(){this.scene=null,super.destroy(),this.gameObjects=null,this.canvas=null}}const v="0.1.21",L="combos-game:plugin-init-success",w="combos-game:ready",M="combos-game:set-playing",A="combos-game:state-changed",C="combos-game:resource-progress",j="combos-game:resources-ready";let P="*";function N(e,t){if("undefined"!=typeof window&&window.parent&&window.parent!==window)try{window.parent.postMessage(e,t)}catch{}}function X(e,t="*"){N({type:L,systemName:e.systemName,engineVersion:v,...e.packageName?{packageName:e.packageName}:{},...e.packageVersion?{packageVersion:e.packageVersion}:{}},t)}function I(e,t="*"){N({type:w,engineVersion:v,...void 0===e?{}:{error:e instanceof Error?e.message:String(e)}},t)}function D(e,t=P){N({type:C,name:e.name,loaded:e.loaded,total:e.total,progress:e.progress,success:e.success,...e.success?{}:{error:e.error??"load failed"}},t)}function G(e,t=P){N({type:j,total:e.total,failed:e.failed},t)}function V(e,t="*"){N({type:A,playing:e.playing,started:e.started},t)}function B(e){if(!e||"object"!=typeof e)return null;const t=e;return t.type!==M||"boolean"!=typeof t.playing?null:t.playing}const $=["knoffice.tech","converge.ai"];function F(e,t){if(t.includes("*"))return!0;if(0===t.length)return!1;let s;try{s=new URL(e)}catch{return!1}const r=e.toLowerCase(),o=s.hostname.toLowerCase();for(const e of t){const t=e.trim();if(!t)continue;if(t.includes("://")){if(r===t.toLowerCase())return!0;continue}const s=t.toLowerCase().replace(/^\./,"");if(o===s||o.endsWith(`.${s}`))return!0}return!1}function U(e){if(!e?.length)return[...$];if(e.includes("*"))return["*"];const t=new Set,s=[];for(const r of[...$,...e]){const e=r.trim();e&&!t.has(e)&&(t.add(e),s.push(e))}return s}function H(e){if("systemName"in e){const t=e.systemName;if("string"==typeof t)return t}return"UnknownSystem"}function Y(e){const t=e;return{packageName:"string"==typeof t.packageName?t.packageName:void 0,packageVersion:"string"==typeof t.packageVersion?t.packageVersion:void 0}}var q;exports.LOAD_SCENE_MODE=void 0,(q=exports.LOAD_SCENE_MODE||(exports.LOAD_SCENE_MODE={})).SINGLE="SINGLE",q.MULTI_CANVAS="MULTI_CANVAS";const W=e=>{if((e instanceof R||e instanceof a)&&!e.started){e.started=!0;try{e.start&&e.start()}catch(t){e instanceof a?console.error(`${function(e){if("componentName"in e){const t=e.componentName;if("string"==typeof t)return t}return"UnknownComponent"}(e.constructor)} start error`,t):console.error(`${H(e.constructor)} start error`,t)}}};class z extends n.default{constructor({systems:e,frameRate:t=60,autoStart:s=!0,needScene:r=!0,onSystemsBootstrapComplete:o,pluginInitNotifyTargetOrigin:n="*",allowedMessageOrigins:a}={}){if(super(),this.playing=!1,this.started=!1,this.multiScenes=[],this.systems=[],this.pluginInitNotifyTargetOrigin="*",this.allowedMessageOrigins=U(),this.onHostMessage=e=>{if(!F(e.origin,this.allowedMessageOrigins))return;const t=B(e.data);null!==t&&this.setPlaying(t)},this.pluginInitNotifyTargetOrigin=n,P=n||"*",this.allowedMessageOrigins=U(a),this.ticker=new T({autoStart:!1,frameRate:t}),this.initTicker(),"undefined"!=typeof window&&window.addEventListener("message",this.onHostMessage),e&&e.length){const t=[...e];this.bootstrapSystemsAndMaybeStart(t,r,s,o)}else o?.(this),this.notifyReady()}setPlaying(e){e?this.started?this.resume():this.start():this.pause()}notifyReady(e){I(e,this.pluginInitNotifyTargetOrigin)}flushObservedComponents(){for(const e of this.systems)try{e.update?.()}catch(t){console.error(`${H(e.constructor)} update error`,t)}}notifyStateChanged(){V({playing:this.playing,started:this.started},this.pluginInitNotifyTargetOrigin)}async bootstrapSystemsAndMaybeStart(e,t,s,r){let o;try{for(const t of e)await this.addSystem(t);t&&this.loadScene({scene:new k("scene")})}catch(e){o=e,console.error("Game bootstrap failed",e)}try{await Promise.resolve(r?.(this,o))}catch(e){o=o??e,console.error("onSystemsBootstrapComplete failed",e)}if(!o)try{this.flushObservedComponents();for(const e of this.systems)await Promise.resolve(e.beforeReady?.())}catch(e){o=e,console.error("Game beforeReady failed",e)}!o&&s&&this.start(),this.notifyReady(o)}get scene(){return this._scene}set scene(e){this._scene=e}get gameObjects(){return(e=>{const t=e?.scene?.gameObjects||[],s=e?.multiScenes.map(({gameObjects:e})=>e);let r=[];for(const e of s)r=[...r,...e];return[...t,...r]})(this)}async addSystem(e,s){let r;if(e instanceof Function)r=new e(s);else{if(!(e instanceof R))return void console.warn("can only add System");r=e}if(!this.systems.find(e=>e.constructor===r.constructor)){r.game=this,r.init&&await Promise.resolve(r.init(r.__systemDefaultParams)),X({systemName:H(r.constructor),...Y(r.constructor)},this.pluginInitNotifyTargetOrigin),function(e,t){p[t.systemName]=t.observerInfo,c[t.systemName]=e}(r,r.constructor),function(e){const s=[];e instanceof Array?s.push(...e):s.push(e);for(const e of s)for(const s in e.observerInfo){l[s]=l[s]||[];const r=l[s];for(const o of e.observerInfo[s])-1===r.findIndex(e=>t.isEqual(e,o))&&l[s].push(o)}}(r.constructor);try{r.awake&&r.awake()}catch(e){console.error(`${H(r.constructor)} awake error`,e)}return this.systems.push(r),r}console.warn(`${H(r.constructor)} System has been added`)}removeSystem(e){if(!e)return;let t=-1;"string"==typeof e?t=this.systems.findIndex(t=>t.name===e):e instanceof Function?t=this.systems.findIndex(t=>t.constructor===e):e instanceof R&&(t=this.systems.findIndex(t=>t===e)),t>-1&&(this.systems[t].destroy&&this.systems[t].destroy(),this.systems.splice(t,1))}getSystem(e){return this.systems.find(t=>"string"==typeof e?t.name===e:t instanceof e)}pause(){this.playing&&(this.playing=!1,this.ticker.pause(),this.triggerPause(),this.notifyStateChanged())}start(){this.playing||(this.playing=!0,this.started=!0,this.ticker.start(),this.notifyStateChanged())}resume(){this.playing||(this.playing=!0,this.ticker.start(),this.triggerResume(),this.notifyStateChanged())}initTicker(){this.ticker.add(e=>{this.scene&&((e,t=[])=>{for(const s of t)for(const t of s.components)try{W(t),t.update&&t.update(e)}catch(e){console.error(`gameObject: ${s.name} ${t.name} update error`,e)}for(const s of t)for(const t of s.components)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`gameObject: ${s.name} ${t.name} lateUpdate error`,e)}})(e,this.gameObjects);for(const t of this.systems)try{W(t),t.update&&t.update(e)}catch(e){console.error(`${H(t.constructor)} update error`,e)}for(const t of this.systems)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`${H(t.constructor)} lateUpdate error`,e)}})}triggerResume(){(e=>{for(const t of e)for(const e of t.components)try{e.onResume&&e.onResume()}catch(s){console.error(`gameObject: ${t.name}, ${e.name}, onResume error`,s)}})(this.gameObjects);for(const e of this.systems)try{e.onResume&&e.onResume()}catch(t){console.error(`${H(e.constructor)}, onResume error`,t)}}triggerPause(){(e=>{for(const t of e)for(const e of t.components)try{e.onPause&&e.onPause()}catch(s){console.error(`gameObject: ${t.name}, ${e.name}, onPause error`,s)}})(this.gameObjects);for(const e of this.systems)try{e.onPause&&e.onPause()}catch(t){console.error(`${H(e.constructor)}, onPause error`,t)}}destroySystems(){for(const e of[...this.systems])this.removeSystem(e);this.systems.length=0}destroy(){"undefined"!=typeof window&&window.removeEventListener("message",this.onHostMessage),this.removeAllListeners(),this.pause(),this.scene.destroy(),this.destroySystems(),this.ticker=null,this.scene=null,this.canvas=null,this.multiScenes=null}loadScene({scene:e,mode:t=exports.LOAD_SCENE_MODE.SINGLE,params:s={}}){if(e){switch(e.game=this,t){case exports.LOAD_SCENE_MODE.SINGLE:this.scene=e;break;case exports.LOAD_SCENE_MODE.MULTI_CANVAS:this.multiScenes.push(e)}this.emit("sceneChanged",{scene:e,mode:t,params:s})}}}function J(e,t){e.constructor.IDEProps||(e.constructor.IDEProps=[]),e.constructor.IDEProps.push(t)}function K(e={}){return function(t){if(!t.observerInfo){for(const t in e)for(const s in e[t]){let r;"string"==typeof e[t][s]&&(e[t][s]=[e[t][s]]),Array.isArray(e[t][s])&&(r={prop:e[t][s],deep:!1},e[t][s]=r),r=e[t][s],"string"==typeof r.prop&&(r.prop=[r.prop])}t.observerInfo=e}}}var Q;exports.LOAD_EVENT=void 0,(Q=exports.LOAD_EVENT||(exports.LOAD_EVENT={})).START="start",Q.PROGRESS="progress",Q.LOADED="loaded",Q.COMPLETE="complete",Q.ERROR="error";class Z extends n.default{constructor({resource:e,resourceTotal:t}){super(),this.progress=0,this.resourceTotal=0,this.resourceLoadedCount=0,this.failed=[],this.resource=e,this.resourceTotal=t,0===t&&(this.resource.emit(exports.LOAD_EVENT.COMPLETE,this),this.notifyResourcesReady())}onStart(){this.resource.emit(exports.LOAD_EVENT.START,this)}onProgress(e){if(this.resourceLoadedCount++,this.progress=Math.floor(this.resourceLoadedCount/this.resourceTotal*100)/100,e.success)this.resource.emit(exports.LOAD_EVENT.LOADED,this,e);else{const t=e.errMsg||"load failed";this.failed.push({name:e.name,error:t}),this.resource.emit(exports.LOAD_EVENT.ERROR,this,e)}this.resource.emit(exports.LOAD_EVENT.PROGRESS,this,e),D({name:e.name,loaded:this.resourceLoadedCount,total:this.resourceTotal,progress:this.progress,success:e.success,...e.success?{}:{error:e.errMsg||"load failed"}}),this.resourceLoadedCount===this.resourceTotal&&(this.resource.emit(exports.LOAD_EVENT.COMPLETE,this),this.notifyResourcesReady())}notifyResourcesReady(){G({total:this.resourceTotal,failed:this.failed.slice()})}}const ee={image:"png",json:"json",tex:"tex",ske:"ske",audio:"audio",video:"video",model:"glb",mtl:"mtl",bin:"bin",vertex:"vert",fragment:"frag"},te={png:"png",jpg:"jpg",jpeg:"jpeg",webp:"webp",ktx2:"ktx2",json:"json",tex:"tex",ske:"ske",mp3:"audio",wav:"audio",aac:"audio",ogg:"audio",mp4:"video",webm:"video",glb:"glb",gltf:"gltf",fbx:"fbx",obj:"obj",mtl:"mtl",stl:"stl",dae:"dae",ply:"ply",bin:"bin",vert:"vert",frag:"frag",glsl:"glsl"};function se(e,t){return te[function(e){const t=e.split("?")[0].split("#")[0],s=t.lastIndexOf(".");return s<0?"":t.slice(s+1).toLowerCase()}(e)]||ee[t]||"png"}function re(e,t,s){if("string"==typeof t){const r=t.trim();if(!r)throw ie(s,e);return{type:se(r,e),url:r}}if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(`Resource "${s}" src.${e} must be a url string or { type, url }.`);const r=t;if("data"===r.type)return r;const o="string"==typeof r.url?r.url.trim():"";if(!o)throw ie(s,e);return{...r,type:r.type||se(o,e),url:o}}function oe(e){if("string"!=typeof e)return;return e.trim()||void 0}function ne(e){if(!e)return;if("ktx2"===e.type){const t=oe(e.url);if(t)return t}const t=oe(e.ktx2);if(t)return t;const s=Array.isArray(e.texture)?e.texture:e.texture?[e.texture]:[];for(const e of s){if("ktx2"!==e?.type)continue;const t=oe(e.url);if(t)return t}}function ae(e){return oe(e?.fallback?.url)}function ie(e,t){return new Error(`Resource "${e}" src.${t}.url is required. Use { type, url } (e.g. { type: "webp", url: "https://..." }). A flat path string is also accepted and will be normalized.`)}function ce(e,t,s="(unnamed)"){if(null==e)throw new Error(`Resource "${s}" src is required.`);if("string"==typeof e){const r=function(e){return"AUDIO"===e?"audio":"VIDEO"===e?"video":"MODEL"===e||"GLB"===e?"model":"SHADER"===e?"fragment":"image"}(t);return{[r]:re(r,e,s)}}if("object"!=typeof e||Array.isArray(e))throw new Error(`Resource "${s}" src must be a url string or a slot object.`);const r=function(e){return"SPRITE"===e||"SPRITE_ANIMATION"===e}(t)?function(e){const t={...e};return delete t.animation_json,null!=t.json?delete t.atlas_json:null!=t.atlas_json&&(t.json=t.atlas_json,delete t.atlas_json),t}(e):e,o={};for(const[e,t]of Object.entries(r))null!=t&&(o[e]=re(e,t,s));if(0===Object.keys(o).length)throw new Error(`Resource "${s}" src has no loadable slots.`);return o}function pe(e,t){if(e&&"ktx2"!==e)return e;const s=t.split("?")[0].split("#")[0],r=s.lastIndexOf("."),o=r>=0?s.slice(r+1).toLowerCase():"";return"png"===o||"jpg"===o||"jpeg"===o||"webp"===o?o:"png"}function le(e,t){e.image&&function(e,t){const s=ne(e);if(!s)return;if(t)return"ktx2"!==e.type&&e.url&&e.url!==s&&!ae(e)&&(e.fallback={type:e.type,url:e.url}),e.type="ktx2",void(e.url=s);if("ktx2"!==e.type)return;const r=ae(e);r&&(e.type=pe(e.fallback?.type,r),e.url=r)}(e.image,t)}const me=["WEBGL_compressed_texture_astc","EXT_texture_compression_bptc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_etc"],ue=["texture-compression-astc","texture-compression-bc","texture-compression-etc2"];let he=null;function de(){return he||(he=async function(){return!!function(){if("undefined"==typeof document)return!1;const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return!1;const s=me.some(e=>t.getExtension(e)),r=t.getExtension("WEBGL_lose_context");return r?.loseContext?.(),s}()||async function(){const e="undefined"==typeof navigator?void 0:navigator.gpu;if(!e?.requestAdapter)return!1;try{const t=await e.requestAdapter(),s=t?.features?.has;return!!s&&ue.some(e=>s.call(t.features,e))}catch{return!1}}()}()),he}const fe={AbstractLoadStrategy:s.AbstractLoadStrategy,AudioLoadStrategy:s.AudioLoadStrategy,ImageLoadStrategy:s.ImageLoadStrategy,XhrResponseType:s.XhrResponseType,MediaElementLoadStrategy:s.MediaElementLoadStrategy,VideoLoadStrategy:s.VideoLoadStrategy,XhrLoadStrategy:s.XhrLoadStrategy,Loader:s.Loader,Resource:s.Resource,ResourceType:s.ResourceType,ResourceState:s.ResourceState};function ye(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ge(e){const t=e.frame;return t&&"object"==typeof t?{...e,frame:t,rotated:Boolean(e.rotated),trimmed:Boolean(e.trimmed),spriteSourceSize:e.spriteSourceSize,sourceSize:e.sourceSize}:null}function Ee(e){const t={};if(!e||"object"!=typeof e)return t;for(const s of Object.keys(e)){const r=e[s];t[s]=Array.isArray(r)?r.map(e=>String(e)):[]}return t}function be(e,t,s){for(const r of e){if(!r||"object"!=typeof r)continue;const e=r,o=String(e.filename||e.name||"");if(!o)continue;const n=ge(e);if(!n)continue;t[o]=n;const a=o.lastIndexOf("/");if(a>0){const e=o.slice(0,a);s[e]||(s[e]=[]),s[e].includes(o)||s[e].push(o)}}}function Re(e){if(!e||"object"!=typeof e)return{frames:{},animations:{},meta:{scale:1}};const t=e;if(ye(t.frames)){const e=Ee(t.animations);return function(e,t){const s=new Set;for(const e of Object.values(t))for(const t of e)s.add(t);for(const r of e){if(!r||s.has(r))continue;const e=r.lastIndexOf("/");if(e<=0)continue;const o=r.slice(0,e);t[o]||(t[o]=[]),t[o].push(r),s.add(r)}}(Object.keys(t.frames),e),{...t,frames:t.frames,animations:e,meta:{scale:1,...t.meta||{}}}}const s={},r=Ee(t.animations);if(Array.isArray(t.textures)){for(const e of t.textures)e&&"object"==typeof e&&Array.isArray(e.frames)&&be(e.frames,s,r);const e=t.textures[0]||{},o=e.scale??t.meta?.scale??1;return{frames:s,animations:r,meta:{scale:"number"==typeof o||"string"==typeof o?o:1,image:"string"==typeof e.image?e.image:void 0,size:e.size,format:e.format,...t.meta||{}}}}return Array.isArray(t.frames)?(be(t.frames,s,r),{frames:s,animations:r,meta:{scale:1,...t.meta||{}}}):{frames:{},animations:r,meta:{scale:1,...t.meta||{}}}}function xe(e){if(!e||"object"!=typeof e)return"insertion";return ye(e.frames)?"lexical":"insertion"}var Se;exports.RESOURCE_TYPE=void 0,(Se=exports.RESOURCE_TYPE||(exports.RESOURCE_TYPE={})).IMAGE="IMAGE",Se.SPRITE="SPRITE",Se.SPRITE_ANIMATION="SPRITE_ANIMATION",Se.AUDIO="AUDIO",Se.VIDEO="VIDEO",Se.GLB="GLB",Se.MODEL="MODEL",Se.SHADER="SHADER",s.XhrLoadStrategy.setExtensionXhrType("json",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("tex",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("ske",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("mp3",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("wav",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("aac",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("ogg",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("glb",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("gltf",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("fbx",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("stl",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("ply",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("bin",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("obj",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("mtl",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("dae",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("vert",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("frag",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("glsl",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("ktx2",s.XhrResponseType.Buffer);const _e={png:s.ImageLoadStrategy,jpg:s.ImageLoadStrategy,jpeg:s.ImageLoadStrategy,webp:s.ImageLoadStrategy,ktx2:s.XhrLoadStrategy,json:s.XhrLoadStrategy,tex:s.XhrLoadStrategy,ske:s.XhrLoadStrategy,audio:s.XhrLoadStrategy,video:s.VideoLoadStrategy,glb:s.XhrLoadStrategy,gltf:s.XhrLoadStrategy,fbx:s.XhrLoadStrategy,obj:s.XhrLoadStrategy,mtl:s.XhrLoadStrategy,stl:s.XhrLoadStrategy,dae:s.XhrLoadStrategy,ply:s.XhrLoadStrategy,bin:s.XhrLoadStrategy,vert:s.XhrLoadStrategy,frag:s.XhrLoadStrategy,glsl:s.XhrLoadStrategy};class Oe extends n.default{constructor(e){super(),this.timeout=6e3,this.preProcessResourceHandlers=[],this.resourcesMap={},this.makeInstanceFunctions={},this.destroyInstanceFunctions={},this.promiseMap={},this.loaders=[],e&&"number"==typeof e.timeout&&(this.timeout=e.timeout)}loadConfig(e){this.addResource(e),this.preload()}loadSingle(e){return this.addResource([e]),this.getResource(e.name)}addResource(e){if(!e||e.length<1)console.warn("no resources");else for(const t of e)this.resourcesMap[t.name]?console.warn(t.name+" was already added"):this.resourcesMap[t.name]={...t,src:ce(t.src,String(t.type),t.name),data:{}}}addPreProcessResourceHandler(e){this.preProcessResourceHandlers.push(e)}removePreProcessResourceHandler(e){this.preProcessResourceHandlers.splice(this.preProcessResourceHandlers.indexOf(e),1)}preload(){const e=[];for(const t in this.resourcesMap){const s=this.resourcesMap[t];!s.preload||s.complete||this.promiseMap[t]||e.push(s.name)}this.progress=new Z({resource:this,resourceTotal:e.length}),this.loadResource({names:e,preload:!0})}async getResource(e){return this.loadResource({names:[e]}),this.promiseMap[e]||Promise.resolve({})}async instance(e){const t=this.resourcesMap[e];return this.makeInstanceFunctions[t.type]&&await this.makeInstanceFunctions[t.type](t)}async destroy(e){await this._destroy(e)}async _destroy(e,t=!1){const s=this.resourcesMap[e];if(s){if(!t)try{this.destroyInstanceFunctions[s.type]&&await this.destroyInstanceFunctions[s.type](s)}catch(e){console.warn(`destroy resource ${s.name} error with '${e.message}'`)}delete this.promiseMap[e],s.data={},s.complete=!1,s.instance=void 0}}registerResourceType(e,t=e){if(exports.RESOURCE_TYPE[e])throw new Error(`The type ${e} already exists in RESOURCE_TYPE`);exports.RESOURCE_TYPE[e]=t}registerInstance(e,t){this.makeInstanceFunctions[e]=t}registerDestroy(e,t){this.destroyInstanceFunctions[e]=t}loadResource({names:e=[],preload:t=!1}){const s=e.filter(e=>!this.promiseMap[e]&&this.resourcesMap[e]);if(!s.length)return;const r={};s.forEach(e=>{this.promiseMap[e]=new Promise(t=>r[e]=t)}),this.beginLoad(s,r,t)}async beginLoad(e,t,s){let r=!1;try{r=await de()}catch{r=!1}const o=this.getLoader(s);for(const n of e){const e=this.resourcesMap[n];if(e){try{for(const t of this.preProcessResourceHandlers)t(e);e.src=ce(e.src,String(e.type),e.name),le(e.src,r)}catch(e){console.error(e),t[n]?.({});continue}for(const r in e.src){const a=e.src[r].type;"data"===a?(e.data[r]=e.src[r].data,this.doComplete(n,t[n],s)):o.add({url:e.src[r].url,name:`${e.name}_${r}`,strategy:_e[a],metadata:{key:r,name:e.name,resolves:t}})}}else t[n]?.({})}o.load()}async doComplete(e,t,s=!1){const r=this.resourcesMap[e],o={name:e,resource:this.resourcesMap[e],success:!0};if(this.checkAllLoaded(e))try{r.instance=await this.instance(e),r.complete=!0,s&&this.progress.onProgress(o),t(r)}catch(e){console.error(e),r.complete=!1,s&&(o.errMsg=e.message,o.success=!1,this.progress.onProgress(o)),t({})}}checkAllLoaded(e){const t=this.resourcesMap[e];return Array.from(Object.keys(t.src)).every(e=>t.data[e])}getLoader(e=!1){let t=this.loaders.find(e=>!e.loading&&!Te.has(e));return t||(t=new s.Loader,this.loaders.push(t)),Te.add(t),e&&t.onStart.once(()=>{this.progress.onStart()}),t.onLoad.add((t,s)=>{this.onLoad({preload:e,resource:s})}),t.onError.add((t,s,r)=>{this.onError({errMsg:t,resource:r,preload:e})}),t.onComplete.once(()=>{Te.delete(t),t.onLoad.detachAll(),t.onError.detachAll(),t.reset()}),t}async onLoad({preload:e=!1,resource:t}){const{metadata:{key:s,name:r,resolves:o},data:n}=t;this.resourcesMap[r].data[s]=n,this.doComplete(r,o[r],e)}async onError({errMsg:e,preload:t=!1,resource:s}){const{metadata:{key:r,name:o,resolves:n}}=s,a=this.resourcesMap[o];if("image"===r&&function(e){if(!e||"ktx2"!==e.type)return!1;const t=ae(e);return!(!t||t===e.url||(e.type=pe(e.fallback?.type,t),e.url=t,0))}(a?.src?.image)){const e=a.src.image,s=this.getLoader(t);return s.add({url:e.url,name:`${o}_image_fallback`,strategy:_e[e.type],metadata:{key:r,name:o,resolves:n}}),void s.load()}if(this._destroy(o,!0),n[o]({}),t){const t={name:o,resource:this.resourcesMap[o],success:!1,errMsg:e};this.progress.onProgress(t)}}}const Te=new WeakSet,ke=new Oe;ke.registerInstance(exports.RESOURCE_TYPE.SHADER,e=>({vertex:"string"==typeof e.data?.vertex?e.data.vertex:"",fragment:"string"==typeof e.data?.fragment?e.data.fragment:""}));function ve(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function Le(e){return Math.round(2*e)/2}const we={IDEProp:J,componentObserver:K};console.log(`@combos-fun/engine version: ${v}`),exports.AdaptivePixelRatio=class{constructor(e){this.elapsedMs=0,this.slowFrames=0,this.fastFrames=0,this.pixelRatio=e.pixelRatio,this.ceiling=e.ceiling,this.enabled=e.enabled}sample(e){if(!this.enabled)return null;if(!(e>0&&Number.isFinite(e)))return null;if(this.elapsedMs+=e,this.elapsedMs<3e3)return null;if(e>20){if(this.fastFrames=0,this.slowFrames+=1,this.slowFrames>=30&&this.pixelRatio>1){this.slowFrames=0;const e=Math.max(1,Le(this.pixelRatio-.5));if(e<this.pixelRatio)return this.pixelRatio=e,e}return null}if(e<12){if(this.slowFrames=0,this.fastFrames+=1,this.fastFrames>=120&&this.pixelRatio<this.ceiling){this.fastFrames=0;const e=Math.min(this.ceiling,Le(this.pixelRatio+.5));if(e>this.pixelRatio)return this.pixelRatio=e,e}return null}return this.slowFrames=0,this.fastFrames=0,null}},exports.COMBOS_GAME_PLUGIN_INIT_SUCCESS=L,exports.COMBOS_GAME_READY=w,exports.COMBOS_GAME_RESOURCES_READY=j,exports.COMBOS_GAME_RESOURCE_PROGRESS=C,exports.COMBOS_GAME_SET_PLAYING=M,exports.COMBOS_GAME_STATE_CHANGED=A,exports.Component=a,exports.DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES=$,exports.Game=z,exports.GameObject=E,exports.IDEProp=J,exports.RESOURCE_TYPE_STRATEGY=_e,exports.Scene=k,exports.System=R,exports.applyCompressedImagePreference=le,exports.componentObserver=K,exports.compressedTextureUrl=ne,exports.decorators=we,exports.gpuSupportsCompressedTexture=de,exports.imageFallbackUrl=ae,exports.isAllowedMessageOrigin=F,exports.mergeAllowedMessageOrigins=U,exports.normalizeResourceSrc=ce,exports.normalizeSpritesheetData=Re,exports.parseSetPlayingMessage=B,exports.postParentGameReady=I,exports.postParentGameState=V,exports.postParentPluginInitSuccess=X,exports.postParentResourceProgress=D,exports.postParentResourcesReady=G,exports.readSpriteClipSheet=function(e,t=xe(e)){const s=Re(e),r=Object.keys(s.frames);"lexical"===t&&r.sort();const o=r.map(e=>({...s.frames[e],name:e})),n=new Map(o.map(e=>[e.name,e])),a={},i=s.animations||{};for(const e of Object.keys(i)){const s=i[e]||[],r="lexical"===t?[...s].sort():s,o=[];for(const e of r){const t=n.get(e);t&&o.push(t)}o.length&&(a[e]=o)}if(0===Object.keys(a).length)for(const e of o){const t=e.name.lastIndexOf("/");if(t<=0)continue;const s=e.name.slice(0,t);a[s]||(a[s]=[]),a[s].push(e)}return{frames:o,animations:a,meta:s.meta}},exports.resolveRenderQuality=function(e={},t={}){const s=ve(e.maxPixelRatio)?e.maxPixelRatio:2,r=ve(e.resolution)?e.resolution:ve(e.pixelRatio)?e.pixelRatio:void 0,o=function(e){return ve(e)?e:"undefined"!=typeof window&&ve(window.devicePixelRatio)?window.devicePixelRatio:1}(e.devicePixelRatio??t.devicePixelRatio),n=r??Math.min(o,s);return{pixelRatio:n,pixelRatioCeiling:n,antialias:"boolean"==typeof e.antialias?e.antialias:n<2,pauseWhenHidden:"boolean"!=typeof e.pauseWhenHidden||e.pauseWhenHidden,adaptivePixelRatio:"boolean"==typeof e.adaptivePixelRatio?e.adaptivePixelRatio:t.adaptivePixelRatio??!1,powerPreference:e.powerPreference??"high-performance",autoDensity:"boolean"==typeof e.autoDensity&&e.autoDensity,explicitPixelRatio:null!=r}},exports.resolveSpriteClip=function(e,t,s){const r=String(s??"").trim();if(!r)return{frames:[...e],clip:"",missing:!1};const o=t[r];return o&&0!==o.length?{frames:[...o],clip:r,missing:!1}:{frames:[],clip:r,missing:!0}},exports.resource=ke,exports.resourceLoader=fe,exports.shouldPauseRendering=function(e){return e&&"undefined"!=typeof document&&!0===document.hidden},exports.spriteClipKeyOrder=xe,exports.version=v;
|
|
1
|
+
"use strict";var e=require("eventemitter3"),t=require("lodash-es"),s=require("resource-loader");function r(e){return e&&e.__esModule?e:{default:e}}var o,n=r(e);class a extends n.default{get game(){return this.gameObject?.scene?.game}constructor(e){super(),this.started=!1;const t=this.constructor;this.name=t.componentName,this.__componentDefaultParams=e}}exports.OBSERVER_TYPE=void 0,(o=exports.OBSERVER_TYPE||(exports.OBSERVER_TYPE={})).ADD="ADD",o.REMOVE="REMOVE",o.CHANGE="CHANGE";const i={},c={},p={},u={};function l(e,t){i[e.gameObject.id]||(i[e.gameObject.id]={});const s=i[e.gameObject.id],r=e.name+"_"+t.join(",");if(s[r])return s[r];const o=t.length-1;let n=e;for(let e=0;e<o;e++){if(void 0===n[t[e]]||null===n[t[e]])return{property:void 0,key:void 0};n=n[t[e]]}return s[r]={property:n,key:t[o]},s[r]}function m({systemName:e,componentName:t,component:s,prop:r,type:o,gameObject:n}){c[e]?.componentObserver?.add({component:s,prop:r,type:o,componentName:t,gameObject:n})}const h="GameObject";function d(e,t,s=exports.OBSERVER_TYPE.CHANGE){if(!e)return;const r={prop:[t],deep:!1};for(const o in p){const n=p[o]?.[h];n?.some(e=>e.prop[0]===t)&&m({systemName:o,componentName:h,component:void 0,gameObject:e,prop:r,type:s})}}function f({obj:e,key:s,prop:r,component:o,componentName:n}){if(void 0!==e)if(s in e){if(Object.defineProperty(e,`_${s}`,{enumerable:!1,writable:!0,value:e[s]}),r.deep&&t.isObject(e[s]))for(const t of Object.keys(e[s]))f({obj:e[s],key:t,prop:r,component:o,componentName:n});Object.defineProperty(e,s,{enumerable:!0,set(a){e[`_${s}`]!==a&&(e[`_${s}`]=a,function({prop:e,component:s,componentName:r}){for(const o in p){const n=(p[o]||{})[r];n&&(n.findIndex(s=>t.isEqual(s,e))>-1&&m({systemName:o,componentName:r,component:s,prop:e,type:exports.OBSERVER_TYPE.CHANGE}))}}({prop:r,component:o,componentName:n}))},get:()=>e[`_${s}`]})}else console.error(`prop ${s} not in component: ${n}, Can not observer`)}function y(e,t=e.name){for(const s in p){(p[s]||{})[t]&&c[s]?.componentObserver?.add({component:e,type:exports.OBSERVER_TYPE.REMOVE,componentName:t})}!function(e){e.gameObject&&delete i[e.gameObject.id]}(e)}let g=0;class E{constructor(e){this._parent=null,this._componentCache={},this.children=[],this.inScene=!1,this.components=[],this.destroyed=!1,this._name=e,this.id=++g}get parent(){return this._parent}get name(){return this._name}set scene(e){if(this._scene===e)return;const t=this._scene;this._scene=e;for(const t of this.children)t.scene=e;e?e.addGameObject(this):t&&t.removeGameObject(this)}get scene(){return this._scene}addChild(e){if(e&&e!==this){if(!(e instanceof E))throw new Error("addChild only receive GameObject");if(this.destroyed)throw new Error(`gameObject '${this.name}' has been destroy`);if(e.parent===this){const t=this.children.indexOf(e);return t>-1&&this.children.splice(t,1),void this.children.push(e)}e.parent&&e.parent.removeChild(e),e._parent=this,this.children.push(e),e.scene=this.scene,d(e,"parent",exports.OBSERVER_TYPE.CHANGE)}}removeChild(e){if(!(e instanceof E&&e.parent&&e.parent===this))return e;const t=this.children.indexOf(e);return t>-1&&this.children.splice(t,1),e._parent=null,e.scene=null,d(e,"parent",exports.OBSERVER_TYPE.CHANGE),e}addComponent(e,t){if(this.destroyed)return;const s=function(e){return e instanceof a?e.name:e instanceof Function?e.componentName:void 0}(e);if(this._componentCache[s])return;let r;if(e instanceof Function)r=new e(t);else{if(!(e instanceof a))throw new Error("addComponent recieve Component and Component Constructor");r=e}if(r.gameObject)throw new Error(`component has been added on gameObject ${r.gameObject.name}`);return r.gameObject=this,r.init&&r.init(r.__componentDefaultParams),function(e,t=e.name){for(const s in p)(p[s]||{})[t]&&c[s]?.componentObserver?.add({component:e,type:exports.OBSERVER_TYPE.ADD,componentName:t})}(r,r.name),function(e,t=e.name){if(t&&u[t]){if(!(e&&(s=e,s&&s.constructor&&"componentName"in s.constructor)))throw new Error("component param must be an instance of Component");var s;if(!e.gameObject||!e.gameObject.id)throw new Error("component should be add to a gameObject");for(const s of u[t]){const{property:r,key:o}=l(e,s.prop);f({obj:r,key:o,prop:s,component:e,componentName:t})}}}(r,r.name),this.components.push(r),this._componentCache[s]=r,r.awake&&r.awake(),r}removeComponent(e){let t;return"string"==typeof e?t=e:e instanceof a?t=e.name:e.componentName&&(t=e.componentName),this._removeComponent(t)}_removeComponent(e){const t=this.components.findIndex(({name:t})=>t===e);if(-1===t)return;const s=this.components.splice(t,1)[0];return delete this._componentCache[e],delete s.__componentDefaultParams,s.onDestroy&&s.onDestroy(),y(s,e),s.gameObject=void 0,s}getComponent(e){let t;return"string"==typeof e?t=e:e instanceof a?t=e.name:e.componentName&&(t=e.componentName),void 0!==this._componentCache[t]?this._componentCache[t]:void 0}remove(){if(this.parent)return this.parent.removeChild(this)}destroy(){if(this.destroyed)console.error("Cannot destroy gameObject that have already been destroyed.");else{Array.from(this.children).forEach(e=>{e.destroy()}),this.remove(),this.children.length=0;for(const e in this._componentCache)this._removeComponent(e);this.components.length=0,this.destroyed=!0}}}class b{constructor(){this.events=[]}add({component:e,prop:s,type:r,componentName:o,gameObject:n}){const a=n??e?.gameObject;if(r===exports.OBSERVER_TYPE.REMOVE){const t=t=>e?t.component===e:t.gameObject===a&&t.componentName===o;if(this.events.find(e=>t(e)&&e.type===exports.OBSERVER_TYPE.ADD))return void(this.events=this.events.filter(e=>!t(e)));this.events=this.events.filter(e=>!t(e))}const i=this.events.findIndex(n=>n.gameObject===a&&n.component===e&&n.componentName===o&&t.isEqual(n.prop,s)&&n.type===r);i>-1&&this.events.splice(i,1),this.events.push({gameObject:a,component:e,prop:s,type:r,componentName:o})}getChanged(){return this.events}get changed(){return this.events}clear(){const e=this.events;return this.events=[],e}}class R{constructor(e){this.started=!1,this.componentObserver=new b,this.__systemDefaultParams=e;const t=this.constructor;this.name=t.systemName}destroy(){this.componentObserver=null,this.__systemDefaultParams=null,this.onDestroy?.()}}const x=function(){let e=null;return e=Date.now?Date.now:()=>(new Date).getTime(),e}(),S={originTime:0,playbackRate:1};class _{constructor(e,t){e instanceof _&&(t=e,e={}),e=Object.assign({},S,e),t&&(this._parent=t),this._createTime=x(),this._timeMark=[{globalTime:this.globalTime,localTime:-e.originTime,entropy:-e.originTime,playbackRate:e.playbackRate,globalEntropy:0}],this._parent&&(this._timeMark[0].globalEntropy=this._parent.entropy),this._playbackRate=e.playbackRate}get globalTime(){return this.parent?this.parent.currentTime:x()-this._createTime}get parent(){return this._parent}get lastTimeMark(){return this._timeMark[this._timeMark.length-1]}markTime({time:e=this.currentTime,entropy:t=this.entropy,playbackRate:s=this.playbackRate}={}){const r={globalTime:this.globalTime,localTime:e,entropy:t,playbackRate:s,globalEntropy:this.globalEntropy};this._timeMark.push(r)}get currentTime(){const{localTime:e,globalTime:t}=this.lastTimeMark;return e+(this.globalTime-t)*this.playbackRate}set currentTime(e){this.markTime({time:e})}get globalEntropy(){return this._parent?this._parent.entropy:this.globalTime}get entropy(){const{entropy:e,globalEntropy:t}=this.lastTimeMark;return e+Math.abs((this.globalEntropy-t)*this.playbackRate)}set entropy(e){if(this.entropy>e){const t=this.seekTimeMark(e);this._timeMark.length=t+1}this.markTime({entropy:e})}fork(e){return new _(e,this)}seekGlobalTime(e){const t=this.seekTimeMark(e),s=this._timeMark[t],{entropy:r,playbackRate:o,globalTime:n}=s;return n+(e-r)/Math.abs(o)}seekLocalTime(e){const t=this.seekTimeMark(e),s=this._timeMark[t],{localTime:r,entropy:o,playbackRate:n}=s;return n>0?r+(e-o):r-(e-o)}seekTimeMark(e){const t=this._timeMark;let s=0,r=t.length-1;if(e<=t[s].entropy)return s;if(e>=t[r].entropy)return r;let o=Math.floor((s+r)/2);for(;o>s&&o<r;){if(e===t[o].entropy)return o;e<t[o].entropy?r=o:e>t[o].entropy&&(s=o),o=Math.floor((s+r)/2)}return s}get playbackRate(){return this._playbackRate}set playbackRate(e){e!==this.playbackRate&&(this.markTime({playbackRate:e}),this._playbackRate=e)}get paused(){if(0===this.playbackRate)return!0;let e=this.parent;for(;e;){if(0===e.playbackRate)return!0;e=e.parent}return!1}}const O={autoStart:!0,frameRate:60};class T{constructor(e){e=Object.assign({},O,e),this._frameCount=0,this._frameDuration=1e3/e.frameRate,this.autoStart=e.autoStart,this.frameRate=e.frameRate,this.timeline=new _({originTime:0,playbackRate:1}),this._lastFrameTime=this.timeline.currentTime,this._tickers=new Set,this._requestId=null,this._ticker=()=>{this._started&&(this._requestId=requestAnimationFrame(this._ticker),this.update())},this.autoStart&&this.start()}update(){const e=this.timeline.currentTime,t=e-this._lastFrameTime;if(t>=this._frameDuration){const s=e-t%this._frameDuration,r=s-this._lastFrameTime;this._lastFrameTime=s;const o={deltaTime:r,delta:r,time:s,currentTime:s,frameCount:++this._frameCount,fps:Math.round(1e3/r)};for(const e of this._tickers)"function"==typeof e&&e(o)}}add(e){this._tickers.add(e)}remove(e){this._tickers.delete(e)}start(){this._started||(this._started=!0,this.timeline.playbackRate=1,this._requestId=requestAnimationFrame(this._ticker))}pause(){this._started=!1,this.timeline.playbackRate=0}setPlaybackRate(e){this.timeline.playbackRate=e}}class k extends E{constructor(e){super(e),this.gameObjects=[],this.scene=this}addGameObject(e){this.gameObjects.push(e),e.inScene||(e.inScene=!0,d(e,"inScene",exports.OBSERVER_TYPE.CHANGE))}removeGameObject(e){const t=this.gameObjects.indexOf(e);-1!==t&&(e.inScene&&(e.inScene=!1,d(e,"inScene",exports.OBSERVER_TYPE.CHANGE)),this.gameObjects.splice(t,1))}destroy(){this.scene=null,super.destroy(),this.gameObjects=null,this.canvas=null}}const v="0.1.23",w="combos-game:plugin-init-success",L="combos-game:ready",M="combos-game:set-playing",A="combos-game:state-changed",C="combos-game:resource-progress",j="combos-game:resources-ready";let P="*";function N(e,t){if("undefined"==typeof window)return;const s=window.parent;if(s&&s!==window)try{s.postMessage(e,t)}catch{}else try{const t=JSON.stringify(e),s=window,r=s.CombosRuntimeBridge;if("function"==typeof r?.postMessage)return void r.postMessage(t);s.webkit?.messageHandlers?.combosRuntime?.postMessage(t)}catch{}}function X(e,t="*"){N({type:w,systemName:e.systemName,engineVersion:v,...e.packageName?{packageName:e.packageName}:{},...e.packageVersion?{packageVersion:e.packageVersion}:{}},t)}function I(e,t="*"){N({type:L,engineVersion:v,...void 0===e?{}:{error:e instanceof Error?e.message:String(e)}},t)}function D(e,t=P){N({type:C,name:e.name,loaded:e.loaded,total:e.total,progress:e.progress,success:e.success,...e.success?{}:{error:e.error??"load failed"}},t)}function G(e,t=P){N({type:j,total:e.total,failed:e.failed},t)}function V(e,t="*"){N({type:A,playing:e.playing,started:e.started},t)}function B(e){if(!e||"object"!=typeof e)return null;const t=e;return t.type!==M||"boolean"!=typeof t.playing?null:t.playing}const $=["knoffice.tech","converge.ai"];function F(e,t){if(t.includes("*"))return!0;if(0===t.length)return!1;let s;try{s=new URL(e)}catch{return!1}const r=e.toLowerCase(),o=s.hostname.toLowerCase();for(const e of t){const t=e.trim();if(!t)continue;if(t.includes("://")){if(r===t.toLowerCase())return!0;continue}const s=t.toLowerCase().replace(/^\./,"");if(o===s||o.endsWith(`.${s}`))return!0}return!1}function H(e){if(!e?.length)return[...$];if(e.includes("*"))return["*"];const t=new Set,s=[];for(const r of[...$,...e]){const e=r.trim();e&&!t.has(e)&&(t.add(e),s.push(e))}return s}function U(e){if("systemName"in e){const t=e.systemName;if("string"==typeof t)return t}return"UnknownSystem"}function Y(e){const t=e;return{packageName:"string"==typeof t.packageName?t.packageName:void 0,packageVersion:"string"==typeof t.packageVersion?t.packageVersion:void 0}}var q;exports.LOAD_SCENE_MODE=void 0,(q=exports.LOAD_SCENE_MODE||(exports.LOAD_SCENE_MODE={})).SINGLE="SINGLE",q.MULTI_CANVAS="MULTI_CANVAS";const W=e=>{if((e instanceof R||e instanceof a)&&!e.started){e.started=!0;try{e.start&&e.start()}catch(t){e instanceof a?console.error(`${function(e){if("componentName"in e){const t=e.componentName;if("string"==typeof t)return t}return"UnknownComponent"}(e.constructor)} start error`,t):console.error(`${U(e.constructor)} start error`,t)}}};class z extends n.default{constructor({systems:e,frameRate:t=60,autoStart:s=!0,needScene:r=!0,onSystemsBootstrapComplete:o,pluginInitNotifyTargetOrigin:n="*",allowedMessageOrigins:a}={}){if(super(),this.playing=!1,this.started=!1,this.multiScenes=[],this.systems=[],this.pluginInitNotifyTargetOrigin="*",this.allowedMessageOrigins=H(),this.onHostMessage=e=>{if(!F(e.origin,this.allowedMessageOrigins))return;const t=B(e.data);null!==t&&this.setPlaying(t)},this.pluginInitNotifyTargetOrigin=n,P=n||"*",this.allowedMessageOrigins=H(a),this.ticker=new T({autoStart:!1,frameRate:t}),this.initTicker(),"undefined"!=typeof window&&window.addEventListener("message",this.onHostMessage),e&&e.length){const t=[...e];this.bootstrapSystemsAndMaybeStart(t,r,s,o)}else o?.(this),this.notifyReady()}setPlaying(e){e?this.started?this.resume():this.start():this.pause()}notifyReady(e){I(e,this.pluginInitNotifyTargetOrigin)}flushObservedComponents(){for(const e of this.systems)try{e.update?.()}catch(t){console.error(`${U(e.constructor)} update error`,t)}}notifyStateChanged(){V({playing:this.playing,started:this.started},this.pluginInitNotifyTargetOrigin)}async bootstrapSystemsAndMaybeStart(e,t,s,r){let o;try{for(const t of e)await this.addSystem(t);t&&this.loadScene({scene:new k("scene")})}catch(e){o=e,console.error("Game bootstrap failed",e)}try{await Promise.resolve(r?.(this,o))}catch(e){o=o??e,console.error("onSystemsBootstrapComplete failed",e)}if(!o)try{this.flushObservedComponents();for(const e of this.systems)await Promise.resolve(e.beforeReady?.())}catch(e){o=e,console.error("Game beforeReady failed",e)}!o&&s&&this.start(),this.notifyReady(o)}get scene(){return this._scene}set scene(e){this._scene=e}get gameObjects(){return(e=>{const t=e?.scene?.gameObjects||[],s=e?.multiScenes.map(({gameObjects:e})=>e);let r=[];for(const e of s)r=[...r,...e];return[...t,...r]})(this)}async addSystem(e,s){let r;if(e instanceof Function)r=new e(s);else{if(!(e instanceof R))return void console.warn("can only add System");r=e}if(!this.systems.find(e=>e.constructor===r.constructor)){r.game=this,r.init&&await Promise.resolve(r.init(r.__systemDefaultParams)),X({systemName:U(r.constructor),...Y(r.constructor)},this.pluginInitNotifyTargetOrigin),function(e,t){p[t.systemName]=t.observerInfo,c[t.systemName]=e}(r,r.constructor),function(e){const s=[];e instanceof Array?s.push(...e):s.push(e);for(const e of s)for(const s in e.observerInfo){u[s]=u[s]||[];const r=u[s];for(const o of e.observerInfo[s])-1===r.findIndex(e=>t.isEqual(e,o))&&u[s].push(o)}}(r.constructor);try{r.awake&&r.awake()}catch(e){console.error(`${U(r.constructor)} awake error`,e)}return this.systems.push(r),r}console.warn(`${U(r.constructor)} System has been added`)}removeSystem(e){if(!e)return;let t=-1;"string"==typeof e?t=this.systems.findIndex(t=>t.name===e):e instanceof Function?t=this.systems.findIndex(t=>t.constructor===e):e instanceof R&&(t=this.systems.findIndex(t=>t===e)),t>-1&&(this.systems[t].destroy&&this.systems[t].destroy(),this.systems.splice(t,1))}getSystem(e){return this.systems.find(t=>"string"==typeof e?t.name===e:t instanceof e)}pause(){this.playing&&(this.playing=!1,this.ticker.pause(),this.triggerPause(),this.notifyStateChanged())}start(){this.playing||(this.playing=!0,this.started=!0,this.ticker.start(),this.notifyStateChanged())}resume(){this.playing||(this.playing=!0,this.ticker.start(),this.triggerResume(),this.notifyStateChanged())}initTicker(){this.ticker.add(e=>{this.scene&&((e,t=[])=>{for(const s of t)for(const t of s.components)try{W(t),t.update&&t.update(e)}catch(e){console.error(`gameObject: ${s.name} ${t.name} update error`,e)}for(const s of t)for(const t of s.components)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`gameObject: ${s.name} ${t.name} lateUpdate error`,e)}})(e,this.gameObjects);for(const t of this.systems)try{W(t),t.update&&t.update(e)}catch(e){console.error(`${U(t.constructor)} update error`,e)}for(const t of this.systems)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`${U(t.constructor)} lateUpdate error`,e)}})}triggerResume(){(e=>{for(const t of e)for(const e of t.components)try{e.onResume&&e.onResume()}catch(s){console.error(`gameObject: ${t.name}, ${e.name}, onResume error`,s)}})(this.gameObjects);for(const e of this.systems)try{e.onResume&&e.onResume()}catch(t){console.error(`${U(e.constructor)}, onResume error`,t)}}triggerPause(){(e=>{for(const t of e)for(const e of t.components)try{e.onPause&&e.onPause()}catch(s){console.error(`gameObject: ${t.name}, ${e.name}, onPause error`,s)}})(this.gameObjects);for(const e of this.systems)try{e.onPause&&e.onPause()}catch(t){console.error(`${U(e.constructor)}, onPause error`,t)}}destroySystems(){for(const e of[...this.systems])this.removeSystem(e);this.systems.length=0}destroy(){"undefined"!=typeof window&&window.removeEventListener("message",this.onHostMessage),this.removeAllListeners(),this.pause(),this.scene.destroy(),this.destroySystems(),this.ticker=null,this.scene=null,this.canvas=null,this.multiScenes=null}loadScene({scene:e,mode:t=exports.LOAD_SCENE_MODE.SINGLE,params:s={}}){if(e){switch(e.game=this,t){case exports.LOAD_SCENE_MODE.SINGLE:this.scene=e;break;case exports.LOAD_SCENE_MODE.MULTI_CANVAS:this.multiScenes.push(e)}this.emit("sceneChanged",{scene:e,mode:t,params:s})}}}function J(e,t){e.constructor.IDEProps||(e.constructor.IDEProps=[]),e.constructor.IDEProps.push(t)}function K(e={}){return function(t){if(!t.observerInfo){for(const t in e)for(const s in e[t]){let r;"string"==typeof e[t][s]&&(e[t][s]=[e[t][s]]),Array.isArray(e[t][s])&&(r={prop:e[t][s],deep:!1},e[t][s]=r),r=e[t][s],"string"==typeof r.prop&&(r.prop=[r.prop])}t.observerInfo=e}}}var Q;exports.LOAD_EVENT=void 0,(Q=exports.LOAD_EVENT||(exports.LOAD_EVENT={})).START="start",Q.PROGRESS="progress",Q.LOADED="loaded",Q.COMPLETE="complete",Q.ERROR="error";class Z extends n.default{constructor({resource:e,resourceTotal:t}){super(),this.progress=0,this.resourceTotal=0,this.resourceLoadedCount=0,this.failed=[],this.resource=e,this.resourceTotal=t,0===t&&(this.resource.emit(exports.LOAD_EVENT.COMPLETE,this),this.notifyResourcesReady())}onStart(){this.resource.emit(exports.LOAD_EVENT.START,this)}onProgress(e){if(this.resourceLoadedCount++,this.progress=Math.floor(this.resourceLoadedCount/this.resourceTotal*100)/100,e.success)this.resource.emit(exports.LOAD_EVENT.LOADED,this,e);else{const t=e.errMsg||"load failed";this.failed.push({name:e.name,error:t}),this.resource.emit(exports.LOAD_EVENT.ERROR,this,e)}this.resource.emit(exports.LOAD_EVENT.PROGRESS,this,e),D({name:e.name,loaded:this.resourceLoadedCount,total:this.resourceTotal,progress:this.progress,success:e.success,...e.success?{}:{error:e.errMsg||"load failed"}}),this.resourceLoadedCount===this.resourceTotal&&(this.resource.emit(exports.LOAD_EVENT.COMPLETE,this),this.notifyResourcesReady())}notifyResourcesReady(){G({total:this.resourceTotal,failed:this.failed.slice()})}}const ee={image:"png",json:"json",tex:"tex",ske:"ske",audio:"audio",video:"video",model:"glb",mtl:"mtl",bin:"bin",vertex:"vert",fragment:"frag"},te={png:"png",jpg:"jpg",jpeg:"jpeg",webp:"webp",ktx2:"ktx2",json:"json",tex:"tex",ske:"ske",mp3:"audio",wav:"audio",aac:"audio",ogg:"audio",mp4:"video",webm:"video",glb:"glb",gltf:"gltf",fbx:"fbx",obj:"obj",mtl:"mtl",stl:"stl",dae:"dae",ply:"ply",bin:"bin",vert:"vert",frag:"frag",glsl:"glsl"};function se(e,t){return te[function(e){const t=e.split("?")[0].split("#")[0],s=t.lastIndexOf(".");return s<0?"":t.slice(s+1).toLowerCase()}(e)]||ee[t]||"png"}function re(e,t,s){if("string"==typeof t){const r=t.trim();if(!r)throw ie(s,e);return{type:se(r,e),url:r}}if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(`Resource "${s}" src.${e} must be a url string or { type, url }.`);const r=t;if("data"===r.type)return r;const o="string"==typeof r.url?r.url.trim():"";if(!o)throw ie(s,e);return{...r,type:r.type||se(o,e),url:o}}function oe(e){if("string"!=typeof e)return;return e.trim()||void 0}function ne(e){if(!e)return;if("ktx2"===e.type){const t=oe(e.url);if(t)return t}const t=oe(e.ktx2);if(t)return t;const s=Array.isArray(e.texture)?e.texture:e.texture?[e.texture]:[];for(const e of s){if("ktx2"!==e?.type)continue;const t=oe(e.url);if(t)return t}}function ae(e){return oe(e?.fallback?.url)}function ie(e,t){return new Error(`Resource "${e}" src.${t}.url is required. Use { type, url } (e.g. { type: "webp", url: "https://..." }). A flat path string is also accepted and will be normalized.`)}function ce(e,t,s="(unnamed)"){if(null==e)throw new Error(`Resource "${s}" src is required.`);if("string"==typeof e){const r=function(e){return"AUDIO"===e?"audio":"VIDEO"===e?"video":"MODEL"===e||"GLB"===e?"model":"SHADER"===e?"fragment":"image"}(t);return{[r]:re(r,e,s)}}if("object"!=typeof e||Array.isArray(e))throw new Error(`Resource "${s}" src must be a url string or a slot object.`);const r=function(e){return"SPRITE"===e||"SPRITE_ANIMATION"===e}(t)?function(e){const t={...e};return delete t.animation_json,null!=t.json?delete t.atlas_json:null!=t.atlas_json&&(t.json=t.atlas_json,delete t.atlas_json),t}(e):e,o={};for(const[e,t]of Object.entries(r))null!=t&&(o[e]=re(e,t,s));if(0===Object.keys(o).length)throw new Error(`Resource "${s}" src has no loadable slots.`);return o}function pe(e,t){if(e&&"ktx2"!==e)return e;const s=t.split("?")[0].split("#")[0],r=s.lastIndexOf("."),o=r>=0?s.slice(r+1).toLowerCase():"";return"png"===o||"jpg"===o||"jpeg"===o||"webp"===o?o:"png"}function ue(e,t){e.image&&function(e,t){const s=ne(e);if(!s)return;if(t)return"ktx2"!==e.type&&e.url&&e.url!==s&&!ae(e)&&(e.fallback={type:e.type,url:e.url}),e.type="ktx2",void(e.url=s);if("ktx2"!==e.type)return;const r=ae(e);r&&(e.type=pe(e.fallback?.type,r),e.url=r)}(e.image,t)}const le=["WEBGL_compressed_texture_astc","EXT_texture_compression_bptc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_etc"],me=["texture-compression-astc","texture-compression-bc","texture-compression-etc2"];let he=null;function de(){return he||(he=async function(){return!!function(){if("undefined"==typeof document)return!1;const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return!1;const s=le.some(e=>t.getExtension(e)),r=t.getExtension("WEBGL_lose_context");return r?.loseContext?.(),s}()||async function(){const e="undefined"==typeof navigator?void 0:navigator.gpu;if(!e?.requestAdapter)return!1;try{const t=await e.requestAdapter(),s=t?.features?.has;return!!s&&me.some(e=>s.call(t.features,e))}catch{return!1}}()}()),he}const fe={AbstractLoadStrategy:s.AbstractLoadStrategy,AudioLoadStrategy:s.AudioLoadStrategy,ImageLoadStrategy:s.ImageLoadStrategy,XhrResponseType:s.XhrResponseType,MediaElementLoadStrategy:s.MediaElementLoadStrategy,VideoLoadStrategy:s.VideoLoadStrategy,XhrLoadStrategy:s.XhrLoadStrategy,Loader:s.Loader,Resource:s.Resource,ResourceType:s.ResourceType,ResourceState:s.ResourceState};function ye(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ge(e){const t=e.frame;return t&&"object"==typeof t?{...e,frame:t,rotated:Boolean(e.rotated),trimmed:Boolean(e.trimmed),spriteSourceSize:e.spriteSourceSize,sourceSize:e.sourceSize}:null}function Ee(e){const t={};if(!e||"object"!=typeof e)return t;for(const s of Object.keys(e)){const r=e[s];t[s]=Array.isArray(r)?r.map(e=>String(e)):[]}return t}function be(e,t,s){for(const r of e){if(!r||"object"!=typeof r)continue;const e=r,o=String(e.filename||e.name||"");if(!o)continue;const n=ge(e);if(!n)continue;t[o]=n;const a=o.lastIndexOf("/");if(a>0){const e=o.slice(0,a);s[e]||(s[e]=[]),s[e].includes(o)||s[e].push(o)}}}function Re(e){if(!e||"object"!=typeof e)return{frames:{},animations:{},meta:{scale:1}};const t=e;if(ye(t.frames)){const e=Ee(t.animations);return function(e,t){const s=new Set;for(const e of Object.values(t))for(const t of e)s.add(t);for(const r of e){if(!r||s.has(r))continue;const e=r.lastIndexOf("/");if(e<=0)continue;const o=r.slice(0,e);t[o]||(t[o]=[]),t[o].push(r),s.add(r)}}(Object.keys(t.frames),e),{...t,frames:t.frames,animations:e,meta:{scale:1,...t.meta||{}}}}const s={},r=Ee(t.animations);if(Array.isArray(t.textures)){for(const e of t.textures)e&&"object"==typeof e&&Array.isArray(e.frames)&&be(e.frames,s,r);const e=t.textures[0]||{},o=e.scale??t.meta?.scale??1;return{frames:s,animations:r,meta:{scale:"number"==typeof o||"string"==typeof o?o:1,image:"string"==typeof e.image?e.image:void 0,size:e.size,format:e.format,...t.meta||{}}}}return Array.isArray(t.frames)?(be(t.frames,s,r),{frames:s,animations:r,meta:{scale:1,...t.meta||{}}}):{frames:{},animations:r,meta:{scale:1,...t.meta||{}}}}function xe(e){if(!e||"object"!=typeof e)return"insertion";return ye(e.frames)?"lexical":"insertion"}var Se;exports.RESOURCE_TYPE=void 0,(Se=exports.RESOURCE_TYPE||(exports.RESOURCE_TYPE={})).IMAGE="IMAGE",Se.SPRITE="SPRITE",Se.SPRITE_ANIMATION="SPRITE_ANIMATION",Se.AUDIO="AUDIO",Se.VIDEO="VIDEO",Se.GLB="GLB",Se.MODEL="MODEL",Se.SHADER="SHADER",s.XhrLoadStrategy.setExtensionXhrType("json",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("tex",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("ske",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("mp3",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("wav",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("aac",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("ogg",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("glb",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("gltf",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("fbx",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("stl",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("ply",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("bin",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("obj",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("mtl",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("dae",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("vert",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("frag",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("glsl",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("ktx2",s.XhrResponseType.Buffer);const _e={png:s.ImageLoadStrategy,jpg:s.ImageLoadStrategy,jpeg:s.ImageLoadStrategy,webp:s.ImageLoadStrategy,ktx2:s.XhrLoadStrategy,json:s.XhrLoadStrategy,tex:s.XhrLoadStrategy,ske:s.XhrLoadStrategy,audio:s.XhrLoadStrategy,video:s.VideoLoadStrategy,glb:s.XhrLoadStrategy,gltf:s.XhrLoadStrategy,fbx:s.XhrLoadStrategy,obj:s.XhrLoadStrategy,mtl:s.XhrLoadStrategy,stl:s.XhrLoadStrategy,dae:s.XhrLoadStrategy,ply:s.XhrLoadStrategy,bin:s.XhrLoadStrategy,vert:s.XhrLoadStrategy,frag:s.XhrLoadStrategy,glsl:s.XhrLoadStrategy};class Oe extends n.default{constructor(e){super(),this.timeout=6e3,this.preProcessResourceHandlers=[],this.resourcesMap={},this.makeInstanceFunctions={},this.destroyInstanceFunctions={},this.promiseMap={},this.loaders=[],e&&"number"==typeof e.timeout&&(this.timeout=e.timeout)}loadConfig(e){this.addResource(e),this.preload()}loadSingle(e){return this.addResource([e]),this.getResource(e.name)}addResource(e){if(!e||e.length<1)console.warn("no resources");else for(const t of e)this.resourcesMap[t.name]?console.warn(t.name+" was already added"):this.resourcesMap[t.name]={...t,src:ce(t.src,String(t.type),t.name),data:{}}}addPreProcessResourceHandler(e){this.preProcessResourceHandlers.push(e)}removePreProcessResourceHandler(e){this.preProcessResourceHandlers.splice(this.preProcessResourceHandlers.indexOf(e),1)}preload(){const e=[];for(const t in this.resourcesMap){const s=this.resourcesMap[t];!s.preload||s.complete||this.promiseMap[t]||e.push(s.name)}this.progress=new Z({resource:this,resourceTotal:e.length}),this.loadResource({names:e,preload:!0})}async getResource(e){return this.loadResource({names:[e]}),this.promiseMap[e]||Promise.resolve({})}async instance(e){const t=this.resourcesMap[e];return this.makeInstanceFunctions[t.type]&&await this.makeInstanceFunctions[t.type](t)}async destroy(e){await this._destroy(e)}async _destroy(e,t=!1){const s=this.resourcesMap[e];if(s){if(!t)try{this.destroyInstanceFunctions[s.type]&&await this.destroyInstanceFunctions[s.type](s)}catch(e){console.warn(`destroy resource ${s.name} error with '${e.message}'`)}delete this.promiseMap[e],s.data={},s.complete=!1,s.instance=void 0}}registerResourceType(e,t=e){if(exports.RESOURCE_TYPE[e])throw new Error(`The type ${e} already exists in RESOURCE_TYPE`);exports.RESOURCE_TYPE[e]=t}registerInstance(e,t){this.makeInstanceFunctions[e]=t}registerDestroy(e,t){this.destroyInstanceFunctions[e]=t}loadResource({names:e=[],preload:t=!1}){const s=e.filter(e=>!this.promiseMap[e]&&this.resourcesMap[e]);if(!s.length)return;const r={};s.forEach(e=>{this.promiseMap[e]=new Promise(t=>r[e]=t)}),this.beginLoad(s,r,t)}async beginLoad(e,t,s){let r=!1;try{r=await de()}catch{r=!1}const o=this.getLoader(s);for(const n of e){const e=this.resourcesMap[n];if(e){try{for(const t of this.preProcessResourceHandlers)t(e);e.src=ce(e.src,String(e.type),e.name),ue(e.src,r)}catch(e){console.error(e),t[n]?.({});continue}for(const r in e.src){const a=e.src[r].type;"data"===a?(e.data[r]=e.src[r].data,this.doComplete(n,t[n],s)):o.add({url:e.src[r].url,name:`${e.name}_${r}`,strategy:_e[a],metadata:{key:r,name:e.name,resolves:t}})}}else t[n]?.({})}o.load()}async doComplete(e,t,s=!1){const r=this.resourcesMap[e],o={name:e,resource:this.resourcesMap[e],success:!0};if(this.checkAllLoaded(e))try{r.instance=await this.instance(e),r.complete=!0,s&&this.progress.onProgress(o),t(r)}catch(e){console.error(e),r.complete=!1,s&&(o.errMsg=e.message,o.success=!1,this.progress.onProgress(o)),t({})}}checkAllLoaded(e){const t=this.resourcesMap[e];return Array.from(Object.keys(t.src)).every(e=>t.data[e])}getLoader(e=!1){let t=this.loaders.find(e=>!e.loading&&!Te.has(e));return t||(t=new s.Loader,this.loaders.push(t)),Te.add(t),e&&t.onStart.once(()=>{this.progress.onStart()}),t.onLoad.add((t,s)=>{this.onLoad({preload:e,resource:s})}),t.onError.add((t,s,r)=>{this.onError({errMsg:t,resource:r,preload:e})}),t.onComplete.once(()=>{Te.delete(t),t.onLoad.detachAll(),t.onError.detachAll(),t.reset()}),t}async onLoad({preload:e=!1,resource:t}){const{metadata:{key:s,name:r,resolves:o},data:n}=t;this.resourcesMap[r].data[s]=n,this.doComplete(r,o[r],e)}async onError({errMsg:e,preload:t=!1,resource:s}){const{metadata:{key:r,name:o,resolves:n}}=s,a=this.resourcesMap[o];if("image"===r&&function(e){if(!e||"ktx2"!==e.type)return!1;const t=ae(e);return!(!t||t===e.url||(e.type=pe(e.fallback?.type,t),e.url=t,0))}(a?.src?.image)){const e=a.src.image,s=this.getLoader(t);return s.add({url:e.url,name:`${o}_image_fallback`,strategy:_e[e.type],metadata:{key:r,name:o,resolves:n}}),void s.load()}if(this._destroy(o,!0),n[o]({}),t){const t={name:o,resource:this.resourcesMap[o],success:!1,errMsg:e};this.progress.onProgress(t)}}}const Te=new WeakSet,ke=new Oe;ke.registerInstance(exports.RESOURCE_TYPE.SHADER,e=>({vertex:"string"==typeof e.data?.vertex?e.data.vertex:"",fragment:"string"==typeof e.data?.fragment?e.data.fragment:""}));function ve(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function we(e){return Math.round(2*e)/2}function Le(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function Me(e,t){if(!Le(e.width)||!Le(e.height)||!Le(t))return null;if(e.width<1||e.height<1)return null;const s=Math.round(e.width*t),r=Math.round(e.height*t);return s<1||r<1?null:{bufferWidth:s,bufferHeight:r}}const Ae={IDEProp:J,componentObserver:K};console.log(`@combos-fun/engine version: ${v}`),exports.AdaptivePixelRatio=class{constructor(e){this.elapsedMs=0,this.slowFrames=0,this.fastFrames=0,this.pixelRatio=e.pixelRatio,this.ceiling=e.ceiling,this.enabled=e.enabled}sample(e){if(!this.enabled)return null;if(!(e>0&&Number.isFinite(e)))return null;if(this.elapsedMs+=e,this.elapsedMs<3e3)return null;if(e>20){if(this.fastFrames=0,this.slowFrames+=1,this.slowFrames>=30&&this.pixelRatio>1){this.slowFrames=0;const e=Math.max(1,we(this.pixelRatio-.5));if(e<this.pixelRatio)return this.pixelRatio=e,e}return null}if(e<12){if(this.slowFrames=0,this.fastFrames+=1,this.fastFrames>=120&&this.pixelRatio<this.ceiling){this.fastFrames=0;const e=Math.min(this.ceiling,we(this.pixelRatio+.5));if(e>this.pixelRatio)return this.pixelRatio=e,e}return null}return this.slowFrames=0,this.fastFrames=0,null}},exports.COMBOS_GAME_PLUGIN_INIT_SUCCESS=w,exports.COMBOS_GAME_READY=L,exports.COMBOS_GAME_RESOURCES_READY=j,exports.COMBOS_GAME_RESOURCE_PROGRESS=C,exports.COMBOS_GAME_SET_PLAYING=M,exports.COMBOS_GAME_STATE_CHANGED=A,exports.Component=a,exports.DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES=$,exports.Game=z,exports.GameObject=E,exports.IDEProp=J,exports.RESOURCE_TYPE_STRATEGY=_e,exports.Scene=k,exports.System=R,exports.applyCompressedImagePreference=ue,exports.componentObserver=K,exports.compressedTextureUrl=ne,exports.decorators=Ae,exports.displayBufferSize=Me,exports.fitOrthographicDisplay=function(e){if(!Le(e.width)||!Le(e.height))return null;const t=Me(e.box,e.resolution);if(!t)return null;const s=e.height,r=t.bufferHeight/s,o=t.bufferWidth/r;return{bufferWidth:t.bufferWidth,bufferHeight:t.bufferHeight,visibleWidth:o,visibleHeight:s,pixelRatio:r,originX:e.width/2-o/2,originY:0}},exports.gpuSupportsCompressedTexture=de,exports.imageFallbackUrl=ae,exports.isAllowedMessageOrigin=F,exports.mergeAllowedMessageOrigins=H,exports.normalizeResourceSrc=ce,exports.normalizeSpritesheetData=Re,exports.parseSetPlayingMessage=B,exports.postParentGameReady=I,exports.postParentGameState=V,exports.postParentPluginInitSuccess=X,exports.postParentResourceProgress=D,exports.postParentResourcesReady=G,exports.readSpriteClipSheet=function(e,t=xe(e)){const s=Re(e),r=Object.keys(s.frames);"lexical"===t&&r.sort();const o=r.map(e=>({...s.frames[e],name:e})),n=new Map(o.map(e=>[e.name,e])),a={},i=s.animations||{};for(const e of Object.keys(i)){const s=i[e]||[],r="lexical"===t?[...s].sort():s,o=[];for(const e of r){const t=n.get(e);t&&o.push(t)}o.length&&(a[e]=o)}if(0===Object.keys(a).length)for(const e of o){const t=e.name.lastIndexOf("/");if(t<=0)continue;const s=e.name.slice(0,t);a[s]||(a[s]=[]),a[s].push(e)}return{frames:o,animations:a,meta:s.meta}},exports.resolveRenderQuality=function(e={},t={}){const s=ve(e.maxPixelRatio)?e.maxPixelRatio:2,r=ve(e.resolution)?e.resolution:ve(e.pixelRatio)?e.pixelRatio:void 0,o=function(e){return ve(e)?e:"undefined"!=typeof window&&ve(window.devicePixelRatio)?window.devicePixelRatio:1}(e.devicePixelRatio??t.devicePixelRatio),n=r??Math.min(o,s);return{pixelRatio:n,pixelRatioCeiling:n,antialias:"boolean"==typeof e.antialias?e.antialias:n<2,pauseWhenHidden:"boolean"!=typeof e.pauseWhenHidden||e.pauseWhenHidden,adaptivePixelRatio:"boolean"==typeof e.adaptivePixelRatio?e.adaptivePixelRatio:t.adaptivePixelRatio??!1,powerPreference:e.powerPreference??"high-performance",autoDensity:"boolean"==typeof e.autoDensity&&e.autoDensity,explicitPixelRatio:null!=r}},exports.resolveSpriteClip=function(e,t,s){const r=String(s??"").trim();if(!r)return{frames:[...e],clip:"",missing:!1};const o=t[r];return o&&0!==o.length?{frames:[...o],clip:r,missing:!1}:{frames:[],clip:r,missing:!0}},exports.resource=ke,exports.resourceLoader=fe,exports.shouldPauseRendering=function(e){return e&&"undefined"!=typeof document&&!0===document.hidden},exports.spriteClipKeyOrder=xe,exports.version=v;
|
package/dist/engine.d.ts
CHANGED
|
@@ -247,7 +247,8 @@ interface GameParams {
|
|
|
247
247
|
* `postMessage` targetOrigin when notifying `window.parent` of lifecycle events
|
|
248
248
|
* (`combos-game:plugin-init-success`, `combos-game:ready`, `combos-game:state-changed`,
|
|
249
249
|
* `combos-game:resource-progress`, `combos-game:resources-ready`).
|
|
250
|
-
* Default `'*'`.
|
|
250
|
+
* Default `'*'`. Iframes use it as `postMessage` `targetOrigin`. Top-level pages
|
|
251
|
+
* deliver the same payloads through the native runtime bridge.
|
|
251
252
|
*/
|
|
252
253
|
pluginInitNotifyTargetOrigin?: string;
|
|
253
254
|
/**
|
|
@@ -922,7 +923,7 @@ interface RenderQualityInput {
|
|
|
922
923
|
antialias?: boolean;
|
|
923
924
|
/** Skip the GPU draw while `document.hidden`. Default true. */
|
|
924
925
|
pauseWhenHidden?: boolean;
|
|
925
|
-
/** Raise or lower pixel ratio from frame time. Default
|
|
926
|
+
/** Raise or lower pixel ratio from frame time. Default false. */
|
|
926
927
|
adaptivePixelRatio?: boolean;
|
|
927
928
|
powerPreference?: PowerPreference;
|
|
928
929
|
/** Keep the CSS canvas size at `width` / `height` when resolution is not 1. Default false. */
|
|
@@ -931,7 +932,7 @@ interface RenderQualityInput {
|
|
|
931
932
|
devicePixelRatio?: number;
|
|
932
933
|
}
|
|
933
934
|
interface RenderQualityDefaults {
|
|
934
|
-
/** Used when `adaptivePixelRatio` is omitted. 2D
|
|
935
|
+
/** Used when `adaptivePixelRatio` is omitted. 2D and 3D both leave this false. */
|
|
935
936
|
adaptivePixelRatio?: boolean;
|
|
936
937
|
devicePixelRatio?: number;
|
|
937
938
|
}
|
|
@@ -968,12 +969,42 @@ declare class AdaptivePixelRatio {
|
|
|
968
969
|
sample(deltaMs: number): number | null;
|
|
969
970
|
}
|
|
970
971
|
|
|
972
|
+
interface BoxSize {
|
|
973
|
+
width: number;
|
|
974
|
+
height: number;
|
|
975
|
+
}
|
|
976
|
+
interface DisplayBufferSize {
|
|
977
|
+
bufferWidth: number;
|
|
978
|
+
bufferHeight: number;
|
|
979
|
+
}
|
|
980
|
+
interface OrthographicDisplayFrame extends DisplayBufferSize {
|
|
981
|
+
visibleWidth: number;
|
|
982
|
+
visibleHeight: number;
|
|
983
|
+
pixelRatio: number;
|
|
984
|
+
originX: number;
|
|
985
|
+
originY: number;
|
|
986
|
+
}
|
|
987
|
+
/** Backing store for the canvas box, using the caller-supplied pixel ratio. */
|
|
988
|
+
declare function displayBufferSize(box: BoxSize, resolution: number): DisplayBufferSize | null;
|
|
989
|
+
/**
|
|
990
|
+
* Unity orthographic camera: vertical extent stays `height`, the view stays
|
|
991
|
+
* centered on `(width / 2, height / 2)`, and the horizontal extent follows the
|
|
992
|
+
* backing-store aspect.
|
|
993
|
+
*/
|
|
994
|
+
declare function fitOrthographicDisplay(input: {
|
|
995
|
+
box: BoxSize;
|
|
996
|
+
width: number;
|
|
997
|
+
height: number;
|
|
998
|
+
resolution: number;
|
|
999
|
+
}): OrthographicDisplayFrame | null;
|
|
1000
|
+
|
|
971
1001
|
/** True when the GPU can take ASTC, BC7, BC3, or ETC2. Cached for the page. */
|
|
972
1002
|
declare function gpuSupportsCompressedTexture(): Promise<boolean>;
|
|
973
1003
|
|
|
974
1004
|
/**
|
|
975
|
-
* Sent
|
|
976
|
-
*
|
|
1005
|
+
* Sent after each `System.init` completes during `Game.addSystem`.
|
|
1006
|
+
* An iframe posts to `window.parent`. A top-level page hands the same payload
|
|
1007
|
+
* to the native runtime bridge as a string.
|
|
977
1008
|
*/
|
|
978
1009
|
declare const COMBOS_GAME_PLUGIN_INIT_SUCCESS: "combos-game:plugin-init-success";
|
|
979
1010
|
interface CombosGamePluginInitSuccessMessage {
|
|
@@ -1092,7 +1123,7 @@ declare function isAllowedMessageOrigin(origin: string, allowed: readonly string
|
|
|
1092
1123
|
declare function mergeAllowedMessageOrigins(extra?: string[]): string[];
|
|
1093
1124
|
|
|
1094
1125
|
/** Generated at build from package.json */
|
|
1095
|
-
declare const version = "0.1.
|
|
1126
|
+
declare const version = "0.1.23";
|
|
1096
1127
|
|
|
1097
1128
|
/** Decorators util */
|
|
1098
1129
|
declare const decorators: {
|
|
@@ -1100,5 +1131,5 @@ declare const decorators: {
|
|
|
1100
1131
|
componentObserver: typeof componentObserver;
|
|
1101
1132
|
};
|
|
1102
1133
|
|
|
1103
|
-
export { AdaptivePixelRatio, COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_RESOURCES_READY, COMBOS_GAME_RESOURCE_PROGRESS, COMBOS_GAME_SET_PLAYING, COMBOS_GAME_STATE_CHANGED, Component, DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES, Game, GameObject, IDEProp, LOAD_EVENT, LOAD_SCENE_MODE, ObserverType as OBSERVER_TYPE, RESOURCE_TYPE, RESOURCE_TYPE_STRATEGY, Scene, System, applyCompressedImagePreference, componentObserver, compressedTextureUrl, decorators, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, postParentResourceProgress, postParentResourcesReady, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, shouldPauseRendering, spriteClipKeyOrder, version };
|
|
1104
|
-
export type { CombosGamePluginInitSuccessMessage, CombosGameReadyMessage, CombosGameResourceFailure, CombosGameResourceProgressMessage, CombosGameResourcesReadyMessage, CombosGameSetPlayingMessage, CombosGameStateChangedMessage, ObserverEvent as ComponentChanged, ComponentParams, GameParams, NormalizedSrcSlot, ObserverInfo, PixiSpritesheetData, PluginStruct, PowerPreference, PureObserverInfo, RenderQualityInput, ResolvedRenderQuality, ResourceBase, ResourceStruct, ShaderResourceInstance, SpriteClipFrame, SpriteClipKeyOrder, SpriteClipSheet, SystemConstructor, UpdateParams };
|
|
1134
|
+
export { AdaptivePixelRatio, COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_RESOURCES_READY, COMBOS_GAME_RESOURCE_PROGRESS, COMBOS_GAME_SET_PLAYING, COMBOS_GAME_STATE_CHANGED, Component, DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES, Game, GameObject, IDEProp, LOAD_EVENT, LOAD_SCENE_MODE, ObserverType as OBSERVER_TYPE, RESOURCE_TYPE, RESOURCE_TYPE_STRATEGY, Scene, System, applyCompressedImagePreference, componentObserver, compressedTextureUrl, decorators, displayBufferSize, fitOrthographicDisplay, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, postParentResourceProgress, postParentResourcesReady, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, shouldPauseRendering, spriteClipKeyOrder, version };
|
|
1135
|
+
export type { BoxSize, CombosGamePluginInitSuccessMessage, CombosGameReadyMessage, CombosGameResourceFailure, CombosGameResourceProgressMessage, CombosGameResourcesReadyMessage, CombosGameSetPlayingMessage, CombosGameStateChangedMessage, ObserverEvent as ComponentChanged, ComponentParams, DisplayBufferSize, GameParams, NormalizedSrcSlot, ObserverInfo, OrthographicDisplayFrame, PixiSpritesheetData, PluginStruct, PowerPreference, PureObserverInfo, RenderQualityInput, ResolvedRenderQuality, ResourceBase, ResourceStruct, ShaderResourceInstance, SpriteClipFrame, SpriteClipKeyOrder, SpriteClipSheet, SystemConstructor, UpdateParams };
|
package/dist/engine.esm.js
CHANGED
|
@@ -885,11 +885,12 @@ class Scene extends GameObject {
|
|
|
885
885
|
}
|
|
886
886
|
|
|
887
887
|
/** Generated at build from package.json */
|
|
888
|
-
const version = "0.1.
|
|
888
|
+
const version = "0.1.23";
|
|
889
889
|
|
|
890
890
|
/**
|
|
891
|
-
* Sent
|
|
892
|
-
*
|
|
891
|
+
* Sent after each `System.init` completes during `Game.addSystem`.
|
|
892
|
+
* An iframe posts to `window.parent`. A top-level page hands the same payload
|
|
893
|
+
* to the native runtime bridge as a string.
|
|
893
894
|
*/
|
|
894
895
|
const COMBOS_GAME_PLUGIN_INIT_SUCCESS = "combos-game:plugin-init-success";
|
|
895
896
|
/**
|
|
@@ -928,13 +929,28 @@ function setParentNotifyTargetOrigin(targetOrigin) {
|
|
|
928
929
|
function postToParent(payload, targetOrigin) {
|
|
929
930
|
if (typeof window === "undefined")
|
|
930
931
|
return;
|
|
931
|
-
|
|
932
|
+
const parent = window.parent;
|
|
933
|
+
if (parent && parent !== window) {
|
|
934
|
+
try {
|
|
935
|
+
parent.postMessage(payload, targetOrigin);
|
|
936
|
+
}
|
|
937
|
+
catch {
|
|
938
|
+
/* ignore cross-origin or detached frame */
|
|
939
|
+
}
|
|
932
940
|
return;
|
|
941
|
+
}
|
|
933
942
|
try {
|
|
934
|
-
|
|
943
|
+
const body = JSON.stringify(payload);
|
|
944
|
+
const host = window;
|
|
945
|
+
const bridge = host.CombosRuntimeBridge;
|
|
946
|
+
if (typeof bridge?.postMessage === "function") {
|
|
947
|
+
bridge.postMessage(body);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
host.webkit?.messageHandlers?.combosRuntime?.postMessage(body);
|
|
935
951
|
}
|
|
936
952
|
catch {
|
|
937
|
-
/*
|
|
953
|
+
/* no native bridge */
|
|
938
954
|
}
|
|
939
955
|
}
|
|
940
956
|
/**
|
|
@@ -2436,25 +2452,25 @@ const ADAPTIVE_SLOW_FRAME_COUNT = 30;
|
|
|
2436
2452
|
const ADAPTIVE_FAST_FRAME_COUNT = 120;
|
|
2437
2453
|
const ADAPTIVE_STEP = 0.5;
|
|
2438
2454
|
const MIN_PIXEL_RATIO = 1;
|
|
2439
|
-
function isPositive(value) {
|
|
2455
|
+
function isPositive$1(value) {
|
|
2440
2456
|
return typeof value === 'number' && Number.isFinite(value) && value > 0;
|
|
2441
2457
|
}
|
|
2442
2458
|
function roundToHalf(value) {
|
|
2443
2459
|
return Math.round(value * 2) / 2;
|
|
2444
2460
|
}
|
|
2445
2461
|
function readDevicePixelRatio(devicePixelRatio) {
|
|
2446
|
-
if (isPositive(devicePixelRatio))
|
|
2462
|
+
if (isPositive$1(devicePixelRatio))
|
|
2447
2463
|
return devicePixelRatio;
|
|
2448
|
-
if (typeof window !== 'undefined' && isPositive(window.devicePixelRatio)) {
|
|
2464
|
+
if (typeof window !== 'undefined' && isPositive$1(window.devicePixelRatio)) {
|
|
2449
2465
|
return window.devicePixelRatio;
|
|
2450
2466
|
}
|
|
2451
2467
|
return 1;
|
|
2452
2468
|
}
|
|
2453
2469
|
function resolveRenderQuality(input = {}, defaults = {}) {
|
|
2454
|
-
const maxPixelRatio = isPositive(input.maxPixelRatio) ? input.maxPixelRatio : DEFAULT_MAX_PIXEL_RATIO;
|
|
2455
|
-
const explicit = isPositive(input.resolution)
|
|
2470
|
+
const maxPixelRatio = isPositive$1(input.maxPixelRatio) ? input.maxPixelRatio : DEFAULT_MAX_PIXEL_RATIO;
|
|
2471
|
+
const explicit = isPositive$1(input.resolution)
|
|
2456
2472
|
? input.resolution
|
|
2457
|
-
: isPositive(input.pixelRatio)
|
|
2473
|
+
: isPositive$1(input.pixelRatio)
|
|
2458
2474
|
? input.pixelRatio
|
|
2459
2475
|
: undefined;
|
|
2460
2476
|
const devicePixelRatio = readDevicePixelRatio(input.devicePixelRatio ?? defaults.devicePixelRatio);
|
|
@@ -2529,6 +2545,46 @@ class AdaptivePixelRatio {
|
|
|
2529
2545
|
}
|
|
2530
2546
|
}
|
|
2531
2547
|
|
|
2548
|
+
function isPositive(value) {
|
|
2549
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0;
|
|
2550
|
+
}
|
|
2551
|
+
/** Backing store for the canvas box, using the caller-supplied pixel ratio. */
|
|
2552
|
+
function displayBufferSize(box, resolution) {
|
|
2553
|
+
if (!isPositive(box.width) || !isPositive(box.height) || !isPositive(resolution))
|
|
2554
|
+
return null;
|
|
2555
|
+
if (box.width < 1 || box.height < 1)
|
|
2556
|
+
return null;
|
|
2557
|
+
const bufferWidth = Math.round(box.width * resolution);
|
|
2558
|
+
const bufferHeight = Math.round(box.height * resolution);
|
|
2559
|
+
if (bufferWidth < 1 || bufferHeight < 1)
|
|
2560
|
+
return null;
|
|
2561
|
+
return { bufferWidth, bufferHeight };
|
|
2562
|
+
}
|
|
2563
|
+
/**
|
|
2564
|
+
* Unity orthographic camera: vertical extent stays `height`, the view stays
|
|
2565
|
+
* centered on `(width / 2, height / 2)`, and the horizontal extent follows the
|
|
2566
|
+
* backing-store aspect.
|
|
2567
|
+
*/
|
|
2568
|
+
function fitOrthographicDisplay(input) {
|
|
2569
|
+
if (!isPositive(input.width) || !isPositive(input.height))
|
|
2570
|
+
return null;
|
|
2571
|
+
const buffer = displayBufferSize(input.box, input.resolution);
|
|
2572
|
+
if (!buffer)
|
|
2573
|
+
return null;
|
|
2574
|
+
const visibleHeight = input.height;
|
|
2575
|
+
const pixelRatio = buffer.bufferHeight / visibleHeight;
|
|
2576
|
+
const visibleWidth = buffer.bufferWidth / pixelRatio;
|
|
2577
|
+
return {
|
|
2578
|
+
bufferWidth: buffer.bufferWidth,
|
|
2579
|
+
bufferHeight: buffer.bufferHeight,
|
|
2580
|
+
visibleWidth,
|
|
2581
|
+
visibleHeight,
|
|
2582
|
+
pixelRatio,
|
|
2583
|
+
originX: input.width / 2 - visibleWidth / 2,
|
|
2584
|
+
originY: 0,
|
|
2585
|
+
};
|
|
2586
|
+
}
|
|
2587
|
+
|
|
2532
2588
|
/** Decorators util */
|
|
2533
2589
|
const decorators = {
|
|
2534
2590
|
IDEProp,
|
|
@@ -2536,5 +2592,5 @@ const decorators = {
|
|
|
2536
2592
|
};
|
|
2537
2593
|
console.log(`@combos-fun/engine version: ${version}`);
|
|
2538
2594
|
|
|
2539
|
-
export { AdaptivePixelRatio, COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_RESOURCES_READY, COMBOS_GAME_RESOURCE_PROGRESS, COMBOS_GAME_SET_PLAYING, COMBOS_GAME_STATE_CHANGED, Component, DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES, Game, GameObject, IDEProp, LOAD_EVENT, LOAD_SCENE_MODE, ObserverType as OBSERVER_TYPE, RESOURCE_TYPE, RESOURCE_TYPE_STRATEGY, Scene, System, applyCompressedImagePreference, componentObserver, compressedTextureUrl, decorators, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, postParentResourceProgress, postParentResourcesReady, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, shouldPauseRendering, spriteClipKeyOrder, version };
|
|
2595
|
+
export { AdaptivePixelRatio, COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_RESOURCES_READY, COMBOS_GAME_RESOURCE_PROGRESS, COMBOS_GAME_SET_PLAYING, COMBOS_GAME_STATE_CHANGED, Component, DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES, Game, GameObject, IDEProp, LOAD_EVENT, LOAD_SCENE_MODE, ObserverType as OBSERVER_TYPE, RESOURCE_TYPE, RESOURCE_TYPE_STRATEGY, Scene, System, applyCompressedImagePreference, componentObserver, compressedTextureUrl, decorators, displayBufferSize, fitOrthographicDisplay, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, postParentResourceProgress, postParentResourcesReady, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, shouldPauseRendering, spriteClipKeyOrder, version };
|
|
2540
2596
|
//# sourceMappingURL=engine.esm.js.map
|