@combos-fun/engine 0.1.24 → 0.1.26
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/README.md +7 -0
- package/dist/engine.cjs.js +270 -26
- package/dist/engine.cjs.js.map +1 -1
- package/dist/engine.cjs.prod.js +1 -1
- package/dist/engine.d.ts +112 -10
- package/dist/engine.esm.js +265 -27
- package/dist/engine.esm.js.map +1 -1
- package/package.json +2 -2
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={},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.24",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?.({deltaTime:0,delta:0,time:0,currentTime:0,frameCount:0,fps:0})}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&&"gpu"in navigator?navigator.gpu:void 0;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;
|
|
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 i 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 a={},c={},p={},u={};function h(e,t){a[e.gameObject.id]||(a[e.gameObject.id]={});const s=a[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 l({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 m="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]?.[m];n?.some(e=>e.prop[0]===t)&&l({systemName:o,componentName:m,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(i){e[`_${s}`]!==i&&(e[`_${s}`]=i,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&&l({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 g(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 a[e.gameObject.id]}(e)}let y=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=++y}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 i?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 i))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}=h(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 i?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(),g(s,e),s.gameObject=void 0,s}getComponent(e){let t;return"string"==typeof e?t=e:e instanceof i?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 i=n??e?.gameObject;if(r===exports.OBSERVER_TYPE.REMOVE){const t=t=>e?t.component===e:t.gameObject===i&&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 a=this.events.findIndex(n=>n.gameObject===i&&n.component===e&&n.componentName===o&&t.isEqual(n.prop,s)&&n.type===r);a>-1&&this.events.splice(a,1),this.events.push({gameObject:i,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}(),T={originTime:0,playbackRate:1};class S{constructor(e,t){e instanceof S&&(t=e,e={}),e=Object.assign({},T,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 S(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 _=()=>globalThis.performance?.now()??Date.now();class O{constructor(){this.providers=new Map,this.observers=new Set}get active(){return this.observers.size>0}get samplingOptions(){return{gpuTiming:[...this.observers].some(e=>e.gpuTiming)}}startProvider(e){try{e.start(this.samplingOptions)}catch(e){console.warn("Runtime metrics provider failed to start",e)}}register(e){if(this.providers.has(e.id))throw new Error(`Duplicate renderer id: ${e.id}`);return this.providers.set(e.id,e),this.active&&this.startProvider(e),this.notify(t=>t.providerChanged?.(e,!0)),()=>{this.providers.get(e.id)===e&&(this.active&&e.stop(),this.providers.delete(e.id),this.notify(t=>t.providerChanged?.(e,!1)))}}subscribe(e){const t=this.active,s=this.samplingOptions.gpuTiming;if(this.observers.add(e),t){if(s!==this.samplingOptions.gpuTiming)for(const e of this.providers.values())e.stop(),this.startProvider(e)}else for(const e of this.providers.values())this.startProvider(e);return()=>{const t=this.samplingOptions.gpuTiming;if(this.observers.delete(e),this.active){if(t!==this.samplingOptions.gpuTiming)for(const e of this.providers.values())e.stop(),this.startProvider(e)}else for(const e of this.providers.values())e.stop()}}notify(e){for(const t of this.observers)try{e(t)}catch(e){console.warn("Runtime diagnostics observer failed",e)}}recordRaf(e){this.active&&this.notify(t=>t.raf?.(e))}recordUpdate(e){if(this.active){const t=_();this.notify(s=>s.update?.(t,t-e))}}measureRender(e,t){const s=this.providers.get(e);if(!this.active||!s)return void t();let r={drawCalls:null,canvasDrawOps:null,triangles:null,gpuMs:null};try{s.beginFrame()}catch(e){console.warn("Runtime metrics beginFrame failed",e)}const o=_();try{t()}finally{const e=_();try{r=s.endFrame()}catch(e){console.warn("Runtime metrics endFrame failed",e)}const t={provider:s,at:e,submitMs:e-o,metrics:r};this.notify(e=>e.render?.(t))}}measureInput(e,t){if(!this.active)return t();const s=_(),r=e>1e12?e-(performance.timeOrigin||Date.now()-s):e,o=Number.isFinite(r)?Math.max(0,s-r):0;try{return t()}finally{this.notify(e=>e.input?.(s,o,_()-s))}}destroy(){if(this.active)for(const e of this.providers.values())e.stop();this.observers.clear(),this.providers.clear()}}const v={autoStart:!0,frameRate:60};class w{constructor(e){e=Object.assign({},v,e),this._frameCount=0,this._frameDuration=1e3/e.frameRate,this.autoStart=e.autoStart,this.frameRate=e.frameRate,this.timeline=new S({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.onRaf?.(_()),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 L 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 k="0.1.26",M=new Set;let A;function P(e,t="*"){if("combos-game:resources-ready"===e.type&&(A=e),"undefined"!=typeof window)try{if(window.parent&&window.parent!==window)window.parent.postMessage(e,t);else{const t=window,s="function"==typeof t.CombosRuntimeBridge?.postMessage?t.CombosRuntimeBridge:t.webkit?.messageHandlers?.combosRuntime;"function"==typeof s?.postMessage&&s.postMessage(JSON.stringify(e))}}catch{}for(const t of M)try{t(e)}catch(e){console.warn("Runtime message observer failed",e)}}const C="combos-game:plugin-init-success",j="combos-game:ready",X="combos-game:set-playing",N="combos-game:state-changed",I="combos-game:resource-progress",D="combos-game:resources-ready";let G="*";function U(e,t){const s="undefined"==typeof window?void 0:window.startTime;P({...e,..."number"==typeof s&&Number.isFinite(s)?{duration:Math.max(0,Date.now()-s)}:{}},t)}function B(e,t="*"){U({type:C,systemName:e.systemName,engineVersion:k,...e.packageName?{packageName:e.packageName}:{},...e.packageVersion?{packageVersion:e.packageVersion}:{}},t)}function V(e,t="*"){U({type:j,engineVersion:k,...void 0===e?{}:{error:e instanceof Error?e.message:String(e)}},t)}function F(e,t=G){U({type:I,name:e.name,loaded:e.loaded,total:e.total,progress:e.progress,success:e.success,...e.success?{}:{error:e.error??"load failed"}},t)}function $(e,t=G){U({type:D,total:e.total,failed:e.failed},t)}function H(e,t="*"){U({type:N,playing:e.playing,started:e.started},t)}function Y(e){if(!e||"object"!=typeof e)return null;const t=e;return t.type!==X||"boolean"!=typeof t.playing?null:t.playing}const Q=["knoffice.tech","converge.ai"];function q(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 W(e){if(!e?.length)return[...Q];if(e.includes("*"))return["*"];const t=new Set,s=[];for(const r of[...Q,...e]){const e=r.trim();e&&!t.has(e)&&(t.add(e),s.push(e))}return s}function z(e){if("systemName"in e){const t=e.systemName;if("string"==typeof t)return t}return"UnknownSystem"}function J(e){const t=e;return{packageName:"string"==typeof t.packageName?t.packageName:void 0,packageVersion:"string"==typeof t.packageVersion?t.packageVersion:void 0}}var K;exports.LOAD_SCENE_MODE=void 0,(K=exports.LOAD_SCENE_MODE||(exports.LOAD_SCENE_MODE={})).SINGLE="SINGLE",K.MULTI_CANVAS="MULTI_CANVAS";const Z=e=>{if((e instanceof R||e instanceof i)&&!e.started){e.started=!0;try{e.start&&e.start()}catch(t){e instanceof i?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(`${z(e.constructor)} start error`,t)}}};class ee extends n.default{constructor({systems:e,frameRate:t=60,autoStart:s=!0,needScene:r=!0,onSystemsBootstrapComplete:o,pluginInitNotifyTargetOrigin:n="*",allowedMessageOrigins:i}={}){if(super(),this.diagnostics=new O,this.ready=!1,this.playing=!1,this.started=!1,this.multiScenes=[],this.systems=[],this.pluginInitNotifyTargetOrigin="*",this.allowedMessageOrigins=W(),this.onHostMessage=e=>{if(!q(e.origin,this.allowedMessageOrigins))return;const t=Y(e.data);null!==t&&this.setPlaying(t)},this.pluginInitNotifyTargetOrigin=n,G=n||"*",this.allowedMessageOrigins=W(i),this.ticker=new w({autoStart:!1,frameRate:t}),this.ticker.onRaf=e=>this.diagnostics.recordRaf(e),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){this.ready=!0,this.readyError=e,V(e,this.pluginInitNotifyTargetOrigin),this.emit(j,{error:e})}flushObservedComponents(){for(const e of this.systems)try{e.update?.({deltaTime:0,delta:0,time:0,currentTime:0,frameCount:0,fps:0})}catch(t){console.error(`${z(e.constructor)} update error`,t)}}notifyStateChanged(){H({playing:this.playing,started:this.started},this.pluginInitNotifyTargetOrigin),this.emit(N,{playing:this.playing,started:this.started})}async bootstrapSystemsAndMaybeStart(e,t,s,r){let o;try{for(const t of e)await this.addSystem(t);t&&this.loadScene({scene:new L("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)),B({systemName:z(r.constructor),...J(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(`${z(r.constructor)} awake error`,e)}return this.systems.push(r),r}console.warn(`${z(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=>{const t=this.diagnostics.active?_():null;this.scene&&((e,t=[])=>{for(const s of t)for(const t of s.components)try{Z(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{Z(t),t.update&&t.update(e)}catch(e){console.error(`${z(t.constructor)} update error`,e)}for(const t of this.systems)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`${z(t.constructor)} lateUpdate error`,e)}null!==t&&this.diagnostics.active&&this.diagnostics.recordUpdate(t)})}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(`${z(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(`${z(e.constructor)}, onPause error`,t)}}destroySystems(){for(const e of[...this.systems])this.removeSystem(e);this.systems.length=0}destroy(){this.diagnostics.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 te(e,t){e.constructor.IDEProps||(e.constructor.IDEProps=[]),e.constructor.IDEProps.push(t)}function se(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 re;exports.LOAD_EVENT=void 0,(re=exports.LOAD_EVENT||(exports.LOAD_EVENT={})).START="start",re.PROGRESS="progress",re.LOADED="loaded",re.COMPLETE="complete",re.ERROR="error";class oe 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),F({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(){$({total:this.resourceTotal,failed:this.failed.slice()})}}const ne={image:"png",json:"json",tex:"tex",ske:"ske",audio:"audio",video:"video",model:"glb",mtl:"mtl",bin:"bin",vertex:"vert",fragment:"frag"},ie={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 ae(e,t){return ie[function(e){const t=e.split("?")[0].split("#")[0],s=t.lastIndexOf(".");return s<0?"":t.slice(s+1).toLowerCase()}(e)]||ne[t]||"png"}function ce(e,t,s){if("string"==typeof t){const r=t.trim();if(!r)throw le(s,e);return{type:ae(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 le(s,e);return{...r,type:r.type||ae(o,e),url:o}}function pe(e){if("string"!=typeof e)return;return e.trim()||void 0}function ue(e){if(!e)return;if("ktx2"===e.type){const t=pe(e.url);if(t)return t}const t=pe(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=pe(e.url);if(t)return t}}function he(e){return pe(e?.fallback?.url)}function le(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 me(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]:ce(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]=ce(e,t,s));if(0===Object.keys(o).length)throw new Error(`Resource "${s}" src has no loadable slots.`);return o}function de(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 fe(e,t){e.image&&function(e,t){const s=ue(e);if(!s)return;if(t)return"ktx2"!==e.type&&e.url&&e.url!==s&&!he(e)&&(e.fallback={type:e.type,url:e.url}),e.type="ktx2",void(e.url=s);if("ktx2"!==e.type)return;const r=he(e);r&&(e.type=de(e.fallback?.type,r),e.url=r)}(e.image,t)}const ge=["WEBGL_compressed_texture_astc","EXT_texture_compression_bptc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_etc"],ye=["texture-compression-astc","texture-compression-bc","texture-compression-etc2"];let Ee=null;function be(){return Ee||(Ee=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=ge.some(e=>t.getExtension(e)),r=t.getExtension("WEBGL_lose_context");return r?.loseContext?.(),s}()||async function(){const e="undefined"!=typeof navigator&&"gpu"in navigator?navigator.gpu:void 0;if(!e?.requestAdapter)return!1;try{const t=await e.requestAdapter(),s=t?.features?.has;return!!s&&ye.some(e=>s.call(t.features,e))}catch{return!1}}()}()),Ee}const Re={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 xe(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function Te(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 Se(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 _e(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=Te(e);if(!n)continue;t[o]=n;const i=o.lastIndexOf("/");if(i>0){const e=o.slice(0,i);s[e]||(s[e]=[]),s[e].includes(o)||s[e].push(o)}}}function Oe(e){if(!e||"object"!=typeof e)return{frames:{},animations:{},meta:{scale:1}};const t=e;if(xe(t.frames)){const e=Se(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=Se(t.animations);if(Array.isArray(t.textures)){for(const e of t.textures)e&&"object"==typeof e&&Array.isArray(e.frames)&&_e(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)?(_e(t.frames,s,r),{frames:s,animations:r,meta:{scale:1,...t.meta||{}}}):{frames:{},animations:r,meta:{scale:1,...t.meta||{}}}}function ve(e){if(!e||"object"!=typeof e)return"insertion";return xe(e.frames)?"lexical":"insertion"}var we;exports.RESOURCE_TYPE=void 0,(we=exports.RESOURCE_TYPE||(exports.RESOURCE_TYPE={})).IMAGE="IMAGE",we.SPRITE="SPRITE",we.SPRITE_ANIMATION="SPRITE_ANIMATION",we.AUDIO="AUDIO",we.VIDEO="VIDEO",we.GLB="GLB",we.MODEL="MODEL",we.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 Le={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 ke 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:me(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 oe({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 be()}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=me(e.src,String(e.type),e.name),fe(e.src,r)}catch(e){console.error(e),t[n]?.({});continue}for(const r in e.src){const i=e.src[r].type;"data"===i?(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:Le[i],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&&!Me.has(e));return t||(t=new s.Loader,this.loaders.push(t)),Me.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(()=>{Me.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,i=this.resourcesMap[o];if("image"===r&&function(e){if(!e||"ktx2"!==e.type)return!1;const t=he(e);return!(!t||t===e.url||(e.type=de(e.fallback?.type,t),e.url=t,0))}(i?.src?.image)){const e=i.src.image,s=this.getLoader(t);return s.add({url:e.url,name:`${o}_image_fallback`,strategy:Le[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 Me=new WeakSet,Ae=new ke;Ae.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 Pe(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function Ce(e){return Math.round(2*e)/2}function je(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function Xe(e,t){if(!je(e.width)||!je(e.height)||!je(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 Ne={IDEProp:te,componentObserver:se};console.log(`@combos-fun/engine version: ${k}`),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,Ce(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,Ce(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=C,exports.COMBOS_GAME_READY=j,exports.COMBOS_GAME_RESOURCES_READY=D,exports.COMBOS_GAME_RESOURCE_PROGRESS=I,exports.COMBOS_GAME_SET_PLAYING=X,exports.COMBOS_GAME_STATE_CHANGED=N,exports.Component=i,exports.DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES=Q,exports.Game=ee,exports.GameObject=E,exports.IDEProp=te,exports.RESOURCE_TYPE_STRATEGY=Le,exports.RuntimeDiagnostics=O,exports.Scene=L,exports.System=R,exports.WebGLGpuTimer=class{constructor(e){this.gl=e,this.pending=[],this.current=null,this.frame=0,this.latest=null,this.webgl2="function"==typeof e?.createQuery,this.ext=e?.getExtension(this.webgl2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")}get supported(){return!!this.ext}begin(){if(!this.ext||this.gl.isContextLost?.())return;const e=this.frame++%30==0;if(!e&&!this.pending.length)return;const t=this.gl,s=this.ext;if(t.getParameter(s.GPU_DISJOINT_EXT))return void this.clear();if(this.latest=null,this.pending=this.pending.filter(e=>{if(!(this.webgl2?t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE):s.getQueryObjectEXT(e,s.QUERY_RESULT_AVAILABLE_EXT)))return!0;const r=this.webgl2?t.getQueryParameter(e,t.QUERY_RESULT):s.getQueryObjectEXT(e,s.QUERY_RESULT_EXT);return Number.isFinite(r)&&r>=0&&(this.latest=r/1e6),this.remove(e),!1}),!e||this.pending.length>=4)return;(this.webgl2?t.getQuery(s.TIME_ELAPSED_EXT,t.CURRENT_QUERY):s.getQueryEXT(s.TIME_ELAPSED_EXT,s.CURRENT_QUERY_EXT))||(this.current=this.webgl2?t.createQuery():s.createQueryEXT(),this.current&&(this.webgl2?t.beginQuery(s.TIME_ELAPSED_EXT,this.current):s.beginQueryEXT(s.TIME_ELAPSED_EXT,this.current)))}end(){this.current&&(this.webgl2?this.gl.endQuery(this.ext.TIME_ELAPSED_EXT):this.ext.endQueryEXT(this.ext.TIME_ELAPSED_EXT),this.pending.push(this.current),this.current=null);const e=this.latest;return this.latest=null,e}remove(e){this.webgl2?this.gl.deleteQuery(e):this.ext.deleteQueryEXT(e)}clear(){this.current&&this.end();for(const e of this.pending)this.remove(e);this.pending=[],this.latest=null}},exports.applyCompressedImagePreference=fe,exports.componentObserver=se,exports.compressedTextureUrl=ue,exports.decorators=Ne,exports.displayBufferSize=Xe,exports.fitOrthographicDisplay=function(e){if(!je(e.width)||!je(e.height))return null;const t=Xe(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.getLatestResourcesReady=function(){return A},exports.gpuSupportsCompressedTexture=be,exports.imageFallbackUrl=he,exports.isAllowedMessageOrigin=q,exports.mergeAllowedMessageOrigins=W,exports.normalizeResourceSrc=me,exports.normalizeSpritesheetData=Oe,exports.observeRuntimeMessages=function(e){return M.add(e),()=>M.delete(e)},exports.parseSetPlayingMessage=Y,exports.postParentGameReady=V,exports.postParentGameState=H,exports.postParentPluginInitSuccess=B,exports.postParentResourceProgress=F,exports.postParentResourcesReady=$,exports.postRuntimeMessage=P,exports.readSpriteClipSheet=function(e,t=ve(e)){const s=Oe(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])),i={},a=s.animations||{};for(const e of Object.keys(a)){const s=a[e]||[],r="lexical"===t?[...s].sort():s,o=[];for(const e of r){const t=n.get(e);t&&o.push(t)}o.length&&(i[e]=o)}if(0===Object.keys(i).length)for(const e of o){const t=e.name.lastIndexOf("/");if(t<=0)continue;const s=e.name.slice(0,t);i[s]||(i[s]=[]),i[s].push(e)}return{frames:o,animations:i,meta:s.meta}},exports.resolveRenderQuality=function(e={},t={}){const s=Pe(e.maxPixelRatio)?e.maxPixelRatio:2,r=Pe(e.resolution)?e.resolution:Pe(e.pixelRatio)?e.pixelRatio:void 0,o=function(e){return Pe(e)?e:"undefined"!=typeof window&&Pe(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=Ae,exports.resourceLoader=Re,exports.runtimeNow=_,exports.shouldPauseRendering=function(e){return e&&"undefined"!=typeof document&&!0===document.hidden},exports.spriteClipKeyOrder=ve,exports.version=k;
|
package/dist/engine.d.ts
CHANGED
|
@@ -29,6 +29,8 @@ declare class Ticker {
|
|
|
29
29
|
private _ticker;
|
|
30
30
|
/** Represents the status of the Ticker, If ticker has started, the value is true */
|
|
31
31
|
private _started;
|
|
32
|
+
/** Optional physical RAF observer; separate from target-rate game updates. */
|
|
33
|
+
onRaf?: (at: number) => void;
|
|
32
34
|
/**
|
|
33
35
|
* @param autoStart - auto start game
|
|
34
36
|
* @param frameRate - game frame rate
|
|
@@ -229,6 +231,73 @@ declare class System<T extends {} = {}> {
|
|
|
229
231
|
destroy(): void;
|
|
230
232
|
}
|
|
231
233
|
|
|
234
|
+
/** Optional runtime probes. No renderer or stats package is imported by the kernel. */
|
|
235
|
+
type RenderBackend = 'webgl' | 'webgpu' | 'canvas';
|
|
236
|
+
interface MetricCapability {
|
|
237
|
+
supported: boolean;
|
|
238
|
+
reason?: string;
|
|
239
|
+
coverage?: string;
|
|
240
|
+
}
|
|
241
|
+
type MetricCapabilities = Record<string, MetricCapability>;
|
|
242
|
+
interface RenderSamplingOptions {
|
|
243
|
+
gpuTiming?: boolean;
|
|
244
|
+
}
|
|
245
|
+
interface RenderFrameMetrics {
|
|
246
|
+
drawCalls: number | null;
|
|
247
|
+
canvasDrawOps: number | null;
|
|
248
|
+
triangles: number | null;
|
|
249
|
+
gpuMs: number | null;
|
|
250
|
+
}
|
|
251
|
+
interface RenderResourceMetrics {
|
|
252
|
+
textures: number | null;
|
|
253
|
+
geometries: number | null;
|
|
254
|
+
programs: number | null;
|
|
255
|
+
bufferWidth: number;
|
|
256
|
+
bufferHeight: number;
|
|
257
|
+
}
|
|
258
|
+
interface RenderMetricsProvider {
|
|
259
|
+
id: string;
|
|
260
|
+
dimension: '2d' | '3d';
|
|
261
|
+
backend: RenderBackend;
|
|
262
|
+
canvas?: HTMLCanvasElement;
|
|
263
|
+
capabilities: MetricCapabilities;
|
|
264
|
+
start(options?: RenderSamplingOptions): void;
|
|
265
|
+
stop(): void;
|
|
266
|
+
beginFrame(): void;
|
|
267
|
+
endFrame(): RenderFrameMetrics;
|
|
268
|
+
resources(): RenderResourceMetrics;
|
|
269
|
+
}
|
|
270
|
+
interface RenderSample {
|
|
271
|
+
provider: RenderMetricsProvider;
|
|
272
|
+
at: number;
|
|
273
|
+
submitMs: number;
|
|
274
|
+
metrics: RenderFrameMetrics;
|
|
275
|
+
}
|
|
276
|
+
interface RuntimeObserver {
|
|
277
|
+
gpuTiming?: boolean;
|
|
278
|
+
raf?(at: number): void;
|
|
279
|
+
update?(at: number, durationMs: number): void;
|
|
280
|
+
render?(sample: RenderSample): void;
|
|
281
|
+
input?(at: number, delayMs: number, dispatchMs: number): void;
|
|
282
|
+
providerChanged?(provider: RenderMetricsProvider, added: boolean): void;
|
|
283
|
+
}
|
|
284
|
+
declare const runtimeNow: () => number;
|
|
285
|
+
declare class RuntimeDiagnostics {
|
|
286
|
+
readonly providers: Map<string, RenderMetricsProvider>;
|
|
287
|
+
private observers;
|
|
288
|
+
get active(): boolean;
|
|
289
|
+
private get samplingOptions();
|
|
290
|
+
private startProvider;
|
|
291
|
+
register(provider: RenderMetricsProvider): () => void;
|
|
292
|
+
subscribe(observer: RuntimeObserver): () => void;
|
|
293
|
+
private notify;
|
|
294
|
+
recordRaf(at: number): void;
|
|
295
|
+
recordUpdate(start: number): void;
|
|
296
|
+
measureRender(id: string, render: () => void): void;
|
|
297
|
+
measureInput<T>(timestamp: number, dispatch: () => T): T;
|
|
298
|
+
destroy(): void;
|
|
299
|
+
}
|
|
300
|
+
|
|
232
301
|
/** Plugin registration shape */
|
|
233
302
|
interface PluginStruct {
|
|
234
303
|
Components?: (typeof Component)[];
|
|
@@ -301,6 +370,9 @@ interface LoadSceneParams {
|
|
|
301
370
|
};
|
|
302
371
|
}
|
|
303
372
|
declare class Game extends EventEmitter {
|
|
373
|
+
readonly diagnostics: RuntimeDiagnostics;
|
|
374
|
+
ready: boolean;
|
|
375
|
+
readyError?: unknown;
|
|
304
376
|
_scene: Scene;
|
|
305
377
|
canvas: HTMLCanvasElement;
|
|
306
378
|
/**
|
|
@@ -1001,13 +1073,43 @@ declare function fitOrthographicDisplay(input: {
|
|
|
1001
1073
|
/** True when the GPU can take ASTC, BC7, BC3, or ETC2. Cached for the page. */
|
|
1002
1074
|
declare function gpuSupportsCompressedTexture(): Promise<boolean>;
|
|
1003
1075
|
|
|
1076
|
+
/** Sparse asynchronous GPU queries, never waits for completion. */
|
|
1077
|
+
declare class WebGLGpuTimer {
|
|
1078
|
+
private gl;
|
|
1079
|
+
private ext;
|
|
1080
|
+
private webgl2;
|
|
1081
|
+
private pending;
|
|
1082
|
+
private current;
|
|
1083
|
+
private frame;
|
|
1084
|
+
private latest;
|
|
1085
|
+
constructor(gl: any);
|
|
1086
|
+
get supported(): boolean;
|
|
1087
|
+
begin(): void;
|
|
1088
|
+
end(): number | null;
|
|
1089
|
+
private remove;
|
|
1090
|
+
clear(): void;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
/** Shared iframe / native transport, also observable in the originating runtime. */
|
|
1094
|
+
interface RuntimeMessage {
|
|
1095
|
+
type: string;
|
|
1096
|
+
[key: string]: unknown;
|
|
1097
|
+
}
|
|
1098
|
+
declare function observeRuntimeMessages(listener: (message: RuntimeMessage) => void): () => void;
|
|
1099
|
+
declare function getLatestResourcesReady(): RuntimeMessage | undefined;
|
|
1100
|
+
declare function postRuntimeMessage(message: RuntimeMessage, targetOrigin?: string): void;
|
|
1101
|
+
|
|
1102
|
+
interface TimedMessage {
|
|
1103
|
+
/** Milliseconds since `window.startTime` (a Date.now() timestamp); omitted if unavailable or invalid. */
|
|
1104
|
+
duration?: number;
|
|
1105
|
+
}
|
|
1004
1106
|
/**
|
|
1005
1107
|
* Sent after each `System.init` completes during `Game.addSystem`.
|
|
1006
1108
|
* An iframe posts to `window.parent`. A top-level page hands the same payload
|
|
1007
1109
|
* to the native runtime bridge as a string.
|
|
1008
1110
|
*/
|
|
1009
1111
|
declare const COMBOS_GAME_PLUGIN_INIT_SUCCESS: "combos-game:plugin-init-success";
|
|
1010
|
-
interface CombosGamePluginInitSuccessMessage {
|
|
1112
|
+
interface CombosGamePluginInitSuccessMessage extends TimedMessage {
|
|
1011
1113
|
type: typeof COMBOS_GAME_PLUGIN_INIT_SUCCESS;
|
|
1012
1114
|
/** Resolved from `System.systemName` on the constructor, or `"UnknownSystem"`. */
|
|
1013
1115
|
systemName: string;
|
|
@@ -1039,13 +1141,13 @@ declare const COMBOS_GAME_SET_PLAYING: "combos-game:set-playing";
|
|
|
1039
1141
|
* iframe → parent: current run state after a `start` / `pause` / `resume`.
|
|
1040
1142
|
*/
|
|
1041
1143
|
declare const COMBOS_GAME_STATE_CHANGED: "combos-game:state-changed";
|
|
1042
|
-
interface CombosGameReadyMessage {
|
|
1144
|
+
interface CombosGameReadyMessage extends TimedMessage {
|
|
1043
1145
|
type: typeof COMBOS_GAME_READY;
|
|
1044
1146
|
engineVersion: string;
|
|
1045
1147
|
/** Set when bootstrap threw (serialized error message). */
|
|
1046
1148
|
error?: string;
|
|
1047
1149
|
}
|
|
1048
|
-
interface CombosGameStateChangedMessage {
|
|
1150
|
+
interface CombosGameStateChangedMessage extends TimedMessage {
|
|
1049
1151
|
type: typeof COMBOS_GAME_STATE_CHANGED;
|
|
1050
1152
|
/** Loop currently running. */
|
|
1051
1153
|
playing: boolean;
|
|
@@ -1067,7 +1169,7 @@ declare const COMBOS_GAME_RESOURCE_PROGRESS: "combos-game:resource-progress";
|
|
|
1067
1169
|
* `total: 0` means that call had no `preload: true` resources.
|
|
1068
1170
|
*/
|
|
1069
1171
|
declare const COMBOS_GAME_RESOURCES_READY: "combos-game:resources-ready";
|
|
1070
|
-
interface CombosGameResourceProgressMessage {
|
|
1172
|
+
interface CombosGameResourceProgressMessage extends TimedMessage {
|
|
1071
1173
|
type: typeof COMBOS_GAME_RESOURCE_PROGRESS;
|
|
1072
1174
|
name: string;
|
|
1073
1175
|
loaded: number;
|
|
@@ -1082,7 +1184,7 @@ interface CombosGameResourceFailure {
|
|
|
1082
1184
|
name: string;
|
|
1083
1185
|
error: string;
|
|
1084
1186
|
}
|
|
1085
|
-
interface CombosGameResourcesReadyMessage {
|
|
1187
|
+
interface CombosGameResourcesReadyMessage extends TimedMessage {
|
|
1086
1188
|
type: typeof COMBOS_GAME_RESOURCES_READY;
|
|
1087
1189
|
total: number;
|
|
1088
1190
|
failed: CombosGameResourceFailure[];
|
|
@@ -1094,9 +1196,9 @@ declare function postParentPluginInitSuccess(input: CombosGamePluginInitSuccessI
|
|
|
1094
1196
|
/** Notifies the embedding page that game bootstrap finished. */
|
|
1095
1197
|
declare function postParentGameReady(error?: unknown, targetOrigin?: string): void;
|
|
1096
1198
|
/** Notifies the embedding page that one preload-batch resource settled. */
|
|
1097
|
-
declare function postParentResourceProgress(input: Omit<CombosGameResourceProgressMessage, "type">, targetOrigin?: string): void;
|
|
1199
|
+
declare function postParentResourceProgress(input: Omit<CombosGameResourceProgressMessage, "type" | "duration">, targetOrigin?: string): void;
|
|
1098
1200
|
/** Notifies the embedding page that the current preload batch finished. */
|
|
1099
|
-
declare function postParentResourcesReady(input: Omit<CombosGameResourcesReadyMessage, "type">, targetOrigin?: string): void;
|
|
1201
|
+
declare function postParentResourcesReady(input: Omit<CombosGameResourcesReadyMessage, "type" | "duration">, targetOrigin?: string): void;
|
|
1100
1202
|
/** Notifies the embedding page of the current play/pause state. */
|
|
1101
1203
|
declare function postParentGameState(state: {
|
|
1102
1204
|
playing: boolean;
|
|
@@ -1123,7 +1225,7 @@ declare function isAllowedMessageOrigin(origin: string, allowed: readonly string
|
|
|
1123
1225
|
declare function mergeAllowedMessageOrigins(extra?: string[]): string[];
|
|
1124
1226
|
|
|
1125
1227
|
/** Generated at build from package.json */
|
|
1126
|
-
declare const version = "0.1.
|
|
1228
|
+
declare const version = "0.1.26";
|
|
1127
1229
|
|
|
1128
1230
|
/** Decorators util */
|
|
1129
1231
|
declare const decorators: {
|
|
@@ -1131,5 +1233,5 @@ declare const decorators: {
|
|
|
1131
1233
|
componentObserver: typeof componentObserver;
|
|
1132
1234
|
};
|
|
1133
1235
|
|
|
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 };
|
|
1236
|
+
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, RuntimeDiagnostics, Scene, System, WebGLGpuTimer, applyCompressedImagePreference, componentObserver, compressedTextureUrl, decorators, displayBufferSize, fitOrthographicDisplay, getLatestResourcesReady, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, observeRuntimeMessages, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, postParentResourceProgress, postParentResourcesReady, postRuntimeMessage, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, runtimeNow, shouldPauseRendering, spriteClipKeyOrder, version };
|
|
1237
|
+
export type { BoxSize, CombosGamePluginInitSuccessMessage, CombosGameReadyMessage, CombosGameResourceFailure, CombosGameResourceProgressMessage, CombosGameResourcesReadyMessage, CombosGameSetPlayingMessage, CombosGameStateChangedMessage, ObserverEvent as ComponentChanged, ComponentParams, DisplayBufferSize, GameParams, MetricCapabilities, MetricCapability, NormalizedSrcSlot, ObserverInfo, OrthographicDisplayFrame, PixiSpritesheetData, PluginStruct, PowerPreference, PureObserverInfo, RenderBackend, RenderFrameMetrics, RenderMetricsProvider, RenderQualityInput, RenderResourceMetrics, RenderSample, RenderSamplingOptions, ResolvedRenderQuality, ResourceBase, ResourceStruct, RuntimeMessage, RuntimeObserver, ShaderResourceInstance, SpriteClipFrame, SpriteClipKeyOrder, SpriteClipSheet, SystemConstructor, UpdateParams };
|