UNPKG

@esengine/ai

Version:

用于Laya、Cocos Creator等JavaScript游戏引擎的高性能AI系统库:行为树、实用AI和有限状态机

1 lines 58.1 kB
class t{static setSeed(t){void 0===t&&(t=Date.now()),this._x=t>>>0,this._y=1812433253*t+1>>>0,this._z=1812433253*this._y+1>>>0,this._w=1812433253*this._z+1>>>0,0===this._x&&(this._x=1),0===this._y&&(this._y=1),0===this._z&&(this._z=1),0===this._w&&(this._w=1),this._initialized=!0;for(let t=0;t<10;t++)this.next()}static next(){this._initialized||this.setSeed();const t=this._x^this._x<<11;return this._x=this._y,this._y=this._z,this._z=this._w,this._w=this._w^this._w>>>19^t^t>>>8,this._w>>>0}static value(){return this.next()/4294967296}static range(t=0,e=1){if(t>=e)throw new Error(`最小值(${t})必须小于最大值(${e})`);return t+(e-t)*this.value()}static integer(t,e){if(!Number.isInteger(t)||!Number.isInteger(e))throw new Error("最小值和最大值必须是整数");if(t>e)throw new Error(`最小值(${t})必须小于等于最大值(${e})`);return Math.floor(this.range(t,e+1))}static boolean(){return this.value()<.5}static chance(t){if(t<0||t>1)throw new Error(`概率值必须在0-1之间,当前值: ${t}`);return this.value()<t}static choice(t){if(0===t.length)throw new Error("数组不能为空");return t[this.integer(0,t.length-1)]}static sample(t,e){if(e<0||e>t.length)throw new Error(`选择数量(${e})必须在0-${t.length}之间`);if(0===e)return[];if(e===t.length)return[...t];if(e<=t.length/2){const i=[],s=new Set;for(;i.length<e;){const e=this.integer(0,t.length-1);s.has(e)||(s.add(e),i.push(t[e]))}return i}{const i=[...t];for(let t=0;t<e;t++){const e=this.integer(t,i.length-1);[i[t],i[e]]=[i[e],i[t]]}return i.slice(0,e)}}static gaussian(t=0,e=1){const i=this.value(),s=this.value();return Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s)*e+t}static getState(){return this._initialized||this.setSeed(),{x:this._x,y:this._y,z:this._z,w:this._w}}static setState(t){this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._initialized=!0}}t._x=123456789,t._y=362436069,t._z=521288629,t._w=88675123,t._initialized=!1;class e{static shuffle(e){if(!e)throw new Error("数组不能为null或undefined");for(let i=e.length-1;i>0;i--){const s=t.integer(0,i);[e[i],e[s]]=[e[s],e[i]]}}static peek(t){if(0===t.length)throw new Error("无法从空数组中获取元素");return t[0]}static unshift(t,e){t.unshift(e)}static pop(t){return t.shift()}static append(t,e){t.push(e)}static removeLast(t){return t.pop()}static isEmpty(t){return 0===t.length}static size(t){return t.length}static clear(t){t.length=0}}class i{constructor(t=16){if(this._head=0,this._tail=0,this._size=0,t<=0)throw new Error("初始容量必须大于0");this._capacity=Math.max(t,4),this._buffer=new Array(this._capacity)}unshift(t){this._size===this._capacity&&this._resize(),this._head=(this._head-1+this._capacity)%this._capacity,this._buffer[this._head]=t,this._size++}push(t){this._size===this._capacity&&this._resize(),this._buffer[this._tail]=t,this._tail=(this._tail+1)%this._capacity,this._size++}shift(){if(0===this._size)return;const t=this._buffer[this._head];return this._buffer[this._head]=void 0,this._head=(this._head+1)%this._capacity,this._size--,t}pop(){if(0===this._size)return;this._tail=(this._tail-1+this._capacity)%this._capacity;const t=this._buffer[this._tail];return this._buffer[this._tail]=void 0,this._size--,t}peekFirst(){return this._size>0?this._buffer[this._head]:void 0}peekLast(){if(0===this._size)return;const t=(this._tail-1+this._capacity)%this._capacity;return this._buffer[t]}get size(){return this._size}get isEmpty(){return 0===this._size}clear(){for(let t=0;t<this._capacity;t++)this._buffer[t]=void 0;this._head=0,this._tail=0,this._size=0}_resize(){const t=2*this._capacity,e=new Array(t);for(let t=0;t<this._size;t++)e[t]=this._buffer[(this._head+t)%this._capacity];this._buffer=e,this._head=0,this._tail=this._size,this._capacity=t}toArray(){const t=[];for(let e=0;e<this._size;e++){const i=this._buffer[(this._head+e)%this._capacity];void 0!==i&&t.push(i)}return t}}class s{static setEnabled(t){this._enabled=t}static setThrowOnFailure(t){this._throwOnFailure=t}static fail(t,...e){const i=t||"断言失败";throw this._throwOnFailure||console.assert(!1,i,...e),new Error(i)}static isTrue(t,e,...i){this._enabled&&(t||this.fail(e||"条件必须为真",...i))}static isFalse(t,e,...i){this._enabled&&t&&this.fail(e||"条件必须为假",...i)}static isNotNull(t,e,...i){this._enabled&&null==t&&this.fail(e||"对象不能为null或undefined",...i)}static isNull(t,e,...i){this._enabled&&null!=t&&this.fail(e||"对象必须为null或undefined",...i)}static isNumber(t,e,...i){this._enabled&&("number"!=typeof t||isNaN(t))&&this.fail(e||"值必须是有效数字",...i)}static isString(t,e,...i){this._enabled&&"string"!=typeof t&&this.fail(e||"值必须是字符串",...i)}static isBoolean(t,e,...i){this._enabled&&"boolean"!=typeof t&&this.fail(e||"值必须是布尔值",...i)}static isFunction(t,e,...i){this._enabled&&"function"!=typeof t&&this.fail(e||"值必须是函数",...i)}static isObject(t,e,...i){this._enabled&&("object"==typeof t&&null!==t||this.fail(e||"值必须是对象",...i))}static isNotEmpty(t,e,...i){this._enabled&&(this.isNotNull(t,e,...i),0===t.length&&this.fail(e||"数组不能为空",...i))}static isNotEmptyString(t,e,...i){this._enabled&&(this.isNotNull(t,e,...i),0===t.trim().length&&this.fail(e||"字符串不能为空",...i))}static inRange(t,e,i,s,...r){this._enabled&&(this.isNumber(t,s,...r),(t<e||t>i)&&this.fail(s||`值必须在 ${e} 到 ${i} 之间`,...r))}static isInstanceOf(t,e,i,...s){this._enabled&&(t instanceof e||this.fail(i||`值必须是 ${e.name} 的实例`,...s))}static contains(t,e,i,...s){this._enabled&&(this.isNotNull(t,i,...s),t.includes(e)||this.fail(i||"数组必须包含指定元素",...s))}static getConfig(){return{enabled:this._enabled,throwOnFailure:this._throwOnFailure}}}var r,n,a,o,h;s._enabled=!0,s._throwOnFailure=!1,function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warn=2]="Warn",t[t.Error=3]="Error",t[t.None=4]="None"}(r||(r={}));class l{static configure(t){this._config={...this._config,...t},void 0!==t.batchMode&&(this._batchConfig.enabled=t.batchMode),void 0!==t.batchSize&&(this._batchConfig.maxSize=Math.max(1,t.batchSize)),void 0!==t.batchFlushInterval&&(this._batchConfig.flushInterval=Math.max(100,t.batchFlushInterval)),this._initializePerformanceMode()}static _initializePerformanceMode(){this._config.performanceMode?this._fastLog=(t,e)=>{void 0!==e?console.log(t,e):console.log(t)}:this._fastLog=null}static setMinLevel(t){this._config.minLevel=t}static setPerformanceMode(t){this._config.performanceMode=t,this._initializePerformanceMode()}static setBatchMode(t,e=50,i=1e3){this._batchConfig.enabled=t,this._batchConfig.maxSize=Math.max(1,e),this._batchConfig.flushInterval=Math.max(100,i),t||this.flushLogs()}static debug(t,e){this._log(r.Debug,t,e)}static info(t,e){this._log(r.Info,t,e)}static warn(t,e){this._log(r.Warn,t,e)}static error(t,e){this._log(r.Error,t,e)}static _log(t,e,i){t<this._config.minLevel||this._config.minLevel===r.None||(this._config.performanceMode&&this._fastLog?this._fastLog(e,i):this._batchConfig.enabled?this._addToBatch(t,e,i):this._config.performanceMode?this._performanceLog(t,e,i):this._standardLog(t,e,i))}static _addToBatch(t,e,i){const s={level:t,message:e,data:i,timestamp:Date.now(),prefix:this._config.prefix};this._logBuffer.push(s);const r=Date.now(),n=this._logBuffer.length>=this._batchConfig.maxSize,a=r-this._batchConfig.lastFlushTime>=this._batchConfig.flushInterval;(n||a)&&this.flushLogs()}static flushLogs(){if(0!==this._logBuffer.length){for(const t of this._logBuffer)this._config.performanceMode?this._performanceLogEntry(t):this._standardLogEntry(t);this._logBuffer.length=0,this._batchConfig.lastFlushTime=Date.now()}}static _performanceLogEntry(t){const e=this._levelNames[t.level],i=t.prefix?`[${t.prefix}] `:"";void 0!==t.data?console.log(`${i}[${e}] ${t.message}`,t.data):console.log(`${i}[${e}] ${t.message}`)}static _standardLogEntry(t){const e=this._config.enableTimestamp?this._formatTimestamp(t.timestamp):"",i=this._levelNames[t.level],s=t.prefix?`[${t.prefix}] `:"",n=this._levelStyles[t.level];let a=`${s}${e}[${i}] ${t.message}`;const o=this._getConsoleMethod(t.level);void 0!==t.data?n&&"function"==typeof console.log?o(`%c${a}`,n,t.data):o(a,t.data):n&&"function"==typeof console.log?o(`%c${a}`,n):o(a),t.level===r.Error&&this._config.enableStackTrace&&t.data instanceof Error&&console.trace(t.data)}static _formatTimestamp(t){const e=new Date(t);return`[${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds().toString().padStart(3,"0")}] `}static _performanceLog(t,e,i){const s=this._levelNames[t],r=this._config.prefix?`[${this._config.prefix}] `:"";void 0!==i?console.log(`${r}[${s}] ${e}`,i):console.log(`${r}[${s}] ${e}`)}static _standardLog(t,e,i){const s=this._config.enableTimestamp?this._getTimestamp():"",n=this._levelNames[t],a=this._config.prefix?`[${this._config.prefix}] `:"",o=this._levelStyles[t];let h=`${a}${s}[${n}] ${e}`;const l=this._getConsoleMethod(t);void 0!==i?o&&"function"==typeof console.log?l(`%c${h}`,o,i):l(h,i):o&&"function"==typeof console.log?l(`%c${h}`,o):l(h),t===r.Error&&this._config.enableStackTrace&&i instanceof Error&&console.trace(i)}static _getTimestamp(){const t=new Date;return`[${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}:${t.getSeconds().toString().padStart(2,"0")}.${t.getMilliseconds().toString().padStart(3,"0")}] `}static _getConsoleMethod(t){switch(t){case r.Debug:return console.debug||console.log;case r.Info:return console.info||console.log;case r.Warn:return console.warn||console.log;case r.Error:return console.error||console.log;default:return console.log}}static getConfig(){return{...this._config}}static createPrefixed(t){return new c(t)}}l._config={minLevel:r.Debug,enableTimestamp:!0,enableStackTrace:!0,performanceMode:!1,prefix:""},l._logBuffer=[],l._batchConfig={enabled:!1,maxSize:50,flushInterval:1e3,lastFlushTime:0},l._fastLog=null,l._levelNames={[r.Debug]:"DEBUG",[r.Info]:"INFO",[r.Warn]:"WARN",[r.Error]:"ERROR",[r.None]:"NONE"},l._levelStyles={[r.Debug]:"color: #888",[r.Info]:"color: #007acc",[r.Warn]:"color: #ff8c00",[r.Error]:"color: #ff4444; font-weight: bold",[r.None]:""};class c{constructor(t){this._prefix=t}debug(t,e){l.debug(`[${this._prefix}] ${t}`,e)}info(t,e){l.info(`[${this._prefix}] ${t}`,e)}warn(t,e){l.warn(`[${this._prefix}] ${t}`,e)}error(t,e){l.error(`[${this._prefix}] ${t}`,e)}}class u{static configure(t){void 0!==t.maxDeltaTime&&(this._maxDeltaTime=Math.max(.001,t.maxDeltaTime)),void 0!==t.timeScale&&(this._timeScale=Math.max(0,t.timeScale)),void 0!==t.useHighPrecision&&(this._useHighPrecision=t.useHighPrecision)}static initialize(){if(this._initialized)return;const t=this._getSystemTime();this._startTime=t,this._currentTime=0,this._lastTime=0,this._deltaTime=0,this._unscaledDeltaTime=0,this._frameCount=0,this._initialized=!0}static updateFrame(t){if(this._initialized||this.initialize(),this._frameCount++,void 0!==t)this._unscaledDeltaTime=Math.max(0,t);else{const t=(this._getSystemTime()-this._startTime)/1e3;1===this._frameCount?(this._lastTime=t,this._unscaledDeltaTime=0):this._unscaledDeltaTime=t-this._lastTime}this._unscaledDeltaTime=Math.min(this._unscaledDeltaTime,this._maxDeltaTime),this._deltaTime=this._unscaledDeltaTime*this._timeScale,this._lastTime=this._currentTime,this._currentTime+=this._deltaTime,this._triggerUpdateCallbacks()}static _getSystemTime(){return this._useHighPrecision?performance.now():Date.now()}static _triggerUpdateCallbacks(){for(let t=0;t<this._updateCallbacks.length;t++)try{this._updateCallbacks[t](this._deltaTime)}catch(t){console.error("时间更新回调执行失败:",t)}}static getCurrentTime(){return this._currentTime}static getDeltaTime(){return this._deltaTime}static getUnscaledDeltaTime(){return this._unscaledDeltaTime}static getTimeScale(){return this._timeScale}static setTimeScale(t){this._timeScale=Math.max(0,t)}static getFrameCount(){return this._frameCount}static getAverageFPS(){return this._currentTime<=0?0:this._frameCount/this._currentTime}static getCurrentFPS(){return this._deltaTime<=0?0:1/this._unscaledDeltaTime}static addUpdateCallback(t){-1===this._updateCallbacks.indexOf(t)&&this._updateCallbacks.push(t)}static removeUpdateCallback(t){const e=this._updateCallbacks.indexOf(t);-1!==e&&this._updateCallbacks.splice(e,1)}static clearUpdateCallbacks(){this._updateCallbacks.length=0}static reset(){this._initialized=!1,this._frameCount=0,this._currentTime=0,this._lastTime=0,this._deltaTime=0,this._unscaledDeltaTime=0,this.clearUpdateCallbacks()}static getStats(){return{currentTime:this._currentTime,deltaTime:this._deltaTime,unscaledDeltaTime:this._unscaledDeltaTime,timeScale:this._timeScale,frameCount:this._frameCount,averageFPS:this.getAverageFPS(),currentFPS:this.getCurrentFPS(),maxDeltaTime:this._maxDeltaTime,useHighPrecision:this._useHighPrecision}}}u._currentTime=0,u._lastTime=0,u._deltaTime=0,u._unscaledDeltaTime=0,u._timeScale=1,u._maxDeltaTime=.1,u._useHighPrecision=!0,u._initialized=!1,u._frameCount=0,u._startTime=0,u._updateCallbacks=[],function(t){t[t.Development=0]="Development",t[t.Testing=1]="Testing",t[t.Production=2]="Production",t[t.Silent=3]="Silent"}(n||(n={}));class _{static configure(t){this._config={...this._config,...t}}static setLevel(t){switch(this._config.level=t,t){case n.Development:this._config.enableAssertions=!0,this._config.enableTypeChecking=!0;break;case n.Testing:this._config.enableAssertions=!0,this._config.enableTypeChecking=!1;break;case n.Production:this._config.enableAssertions=!1,this._config.enableTypeChecking=!1;break;case n.Silent:this._config.enableAssertions=!1,this._config.enableTypeChecking=!1,this._config.enablePerformanceMonitoring=!1}}static assert(t,e,i){if(this._config.enableAssertions&&this._config.level!==n.Silent&&(this._errorStats.totalAssertions++,!t)){const t=new Error(`断言失败: ${e}`);this._handleError(t,i)}}static checkType(t,e,i,s){if(!this._config.enableTypeChecking||this._config.level===n.Silent)return;this._errorStats.totalTypeChecks++;const r=typeof t;if(r!==e){const t=new Error(i||`类型检查失败: 期望 ${e}, 实际 ${r}`);this._handleError(t,s)}}static checkNotNull(t,e,i){if(this._config.enableTypeChecking&&this._config.level!==n.Silent&&(this._errorStats.totalTypeChecks++,null==t)){const t=new Error(e||"值不能为null或undefined");this._handleError(t,i)}}static checkRange(t,e,i,s,r){if(this._config.enableAssertions&&this._config.level!==n.Silent&&(this._errorStats.totalAssertions++,t<e||t>i)){const n=new Error(s||`值 ${t} 超出范围 [${e}, ${i}]`);this._handleError(n,r)}}static checkArrayBounds(t,e,i,s){if(this._config.enableAssertions&&this._config.level!==n.Silent&&(this._errorStats.totalAssertions++,e<0||e>=t.length)){const r=i||`数组索引 ${e} 超出边界 [0, ${t.length-1}]`,n=new Error(r);this._handleError(n,s)}}static monitor(t,e){if(!this._config.enablePerformanceMonitoring||this._config.level===n.Silent)return e();const i=performance.now();try{const s=e(),r=performance.now();return this._recordPerformance(t,r-i),s}catch(e){const s=performance.now();throw this._recordPerformance(t,s-i),e}}static async monitorAsync(t,e){if(!this._config.enablePerformanceMonitoring||this._config.level===n.Silent)return e();const i=performance.now();try{const s=await e(),r=performance.now();return this._recordPerformance(t,r-i),s}catch(e){const s=performance.now();throw this._recordPerformance(t,s-i),e}}static _recordPerformance(t,e){let i=this._performanceData.get(t);i||(i={functionName:t,executionTime:0,callCount:0,averageTime:0,maxTime:0,minTime:1/0},this._performanceData.set(t,i)),i.callCount++,i.executionTime+=e,i.averageTime=i.executionTime/i.callCount,i.maxTime=Math.max(i.maxTime,e),i.minTime=Math.min(i.minTime,e)}static _handleError(t,e){if(this._errorStats.totalErrors++,this._config.onError)try{this._config.onError(t,e)}catch(t){console.error("错误回调执行失败:",t)}switch(this._config.level){case n.Development:throw t;case n.Testing:throw console.error("错误:",t.message,e),t;case n.Production:throw console.warn("错误:",t.message),t}throw t}static warn(t,e){if(this._config.level!==n.Silent){if(this._errorStats.totalWarnings++,this._config.onWarning)try{this._config.onWarning(t,e)}catch(t){console.error("警告回调执行失败:",t)}switch(this._config.level){case n.Development:case n.Testing:console.warn("警告:",t,e);break;case n.Production:console.warn("警告:",t)}}}static getPerformanceStats(){return new Map(this._performanceData)}static getErrorStats(){return{...this._errorStats}}static resetStats(){this._performanceData.clear(),this._errorStats={totalErrors:0,totalWarnings:0,totalAssertions:0,totalTypeChecks:0}}static getConfig(){return{...this._config}}static wrap(t,e,i=!1){return(...s)=>{try{return i?this.monitor(e,(()=>t(...s))):t(...s)}catch(t){this._handleError(t instanceof Error?t:new Error(String(t)),{args:s,functionName:e})}}}}function d(t={}){return function(e,i,s){const r=s.value,n=t.name||`${e.constructor.name}.${i}`;return s.value=function(...e){if(t.enableTypeChecking)for(let t=0;t<e.length;t++)null==e[t]&&_.warn(`方法 ${n} 的第 ${t+1} 个参数为null或undefined`);if(t.enableMonitoring)return _.monitor(n,(()=>r.apply(this,e)));try{return r.apply(this,e)}catch(t){const i=t instanceof Error?t:new Error(String(t));throw _.warn(`方法 ${n} 执行失败`,{error:i,args:e,instance:this}),i}},s}}_._config={level:n.Development,enableAssertions:!0,enableTypeChecking:!0,enablePerformanceMonitoring:!1},_._performanceData=new Map,_._errorStats={totalErrors:0,totalWarnings:0,totalAssertions:0,totalTypeChecks:0};class f{constructor(t={}){this._listeners=new Map,this._cleanupTimer=null,this._nextListenerId=1,this._config={enableAutoCleanup:t.enableAutoCleanup??!0,cleanupInterval:t.cleanupInterval??3e4,maxListeners:t.maxListeners??1e3,listenerExpirationTime:t.listenerExpirationTime??3e5,enablePerformanceMonitoring:t.enablePerformanceMonitoring??!1},this._stats={totalListeners:0,activeListeners:0,totalEvents:0,averageEventTime:0,lastCleanupTime:Date.now()},this._config.enableAutoCleanup&&this._startAutoCleanup()}on(t,e,i={}){const s=this._generateListenerId(),r={callback:e,id:s,createdAt:Date.now(),lastCalledAt:0,callCount:0,once:i.once??!1,priority:i.priority??0,weak:i.weak??!1,owner:i.owner||void 0};if(this._stats.totalListeners>=this._config.maxListeners&&(console.warn(`事件监听器数量已达到上限 ${this._config.maxListeners}`),this._performCleanup(),this._stats.totalListeners>=this._config.maxListeners))throw new Error("无法添加更多事件监听器,已达到上限");this._listeners.has(t)||this._listeners.set(t,[]);const n=this._listeners.get(t);return n.push(r),n.sort(((t,e)=>e.priority-t.priority)),this._stats.totalListeners++,this._updateActiveListeners(),s}onWeak(t,e,i,s={}){return this.on(t,e,{...s,weak:!0,owner:i})}once(t,e,i={}){return this.on(t,e,{...i,once:!0})}off(t,e){const i=this._listeners.get(t);if(!i)return!1;const s=i.findIndex((t=>t.id===e));return-1!==s&&(i.splice(s,1),this._stats.totalListeners--,0===i.length&&this._listeners.delete(t),this._updateActiveListeners(),!0)}offAll(t){const e=this._listeners.get(t);if(!e)return 0;const i=e.length;return this._listeners.delete(t),this._stats.totalListeners-=i,this._updateActiveListeners(),i}offByOwner(t){let e=0;for(const[i,s]of this._listeners){for(let i=s.length-1;i>=0;i--){s[i].owner===t&&(s.splice(i,1),e++,this._stats.totalListeners--)}0===s.length&&this._listeners.delete(i)}return this._updateActiveListeners(),e}emit(t,e){const i=this._listeners.get(t);if(!i||0===i.length)return 0;const s=this._config.enablePerformanceMonitoring?performance.now():0;let r=0;const n=[];for(let s=0;s<i.length;s++){const a=i[s];try{a.callback(e),a.lastCalledAt=Date.now(),a.callCount++,r++,a.once&&n.push(s)}catch(e){console.error(`事件监听器执行失败 (${t}):`,e)}}for(let t=n.length-1;t>=0;t--){const e=n[t];i.splice(e,1),this._stats.totalListeners--}if(0===i.length&&this._listeners.delete(t),this._stats.totalEvents++,this._config.enablePerformanceMonitoring&&s>0){const t=performance.now()-s;this._updateAverageEventTime(t)}return this._updateActiveListeners(),r}hasListeners(t){const e=this._listeners.get(t);return!!e&&e.length>0}getListenerCount(t){const e=this._listeners.get(t);return e?e.length:0}getEventNames(){return Array.from(this._listeners.keys())}cleanup(t=!1){return this._performCleanup(t)}_startAutoCleanup(){this._cleanupTimer||(this._cleanupTimer=window.setInterval((()=>{this._performCleanup()}),this._config.cleanupInterval))}_stopAutoCleanup(){this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null)}_performCleanup(t=!1){const e=Date.now();let i=0;for(const[s,r]of this._listeners){for(let s=r.length-1;s>=0;s--){const n=r[s];let a=t;if(!a&&!a&&this._config.listenerExpirationTime>0){const t=e-n.createdAt,i=e-n.lastCalledAt;t>this._config.listenerExpirationTime&&i>this._config.listenerExpirationTime&&(a=!0)}a&&(r.splice(s,1),i++,this._stats.totalListeners--)}0===r.length&&this._listeners.delete(s)}return this._stats.lastCleanupTime=e,this._updateActiveListeners(),i}_generateListenerId(){return`listener_${this._nextListenerId++}_${Date.now()}`}_updateActiveListeners(){this._stats.activeListeners=this._stats.totalListeners}_updateAverageEventTime(t){1===this._stats.totalEvents?this._stats.averageEventTime=t:this._stats.averageEventTime=(this._stats.averageEventTime*(this._stats.totalEvents-1)+t)/this._stats.totalEvents}getStats(){return{...this._stats}}resetStats(){this._stats={totalListeners:this._stats.totalListeners,activeListeners:this._stats.activeListeners,totalEvents:0,averageEventTime:0,lastCleanupTime:Date.now()}}getConfig(){return{...this._config}}destroy(){this._stopAutoCleanup(),this._listeners.clear(),this._stats.totalListeners=0,this._stats.activeListeners=0}}class p{static isString(t){return"string"==typeof t}static isNumber(t){return"number"==typeof t&&!isNaN(t)}static isBoolean(t){return"boolean"==typeof t}static isFunction(t){return"function"==typeof t}static isObject(t){return"object"==typeof t&&null!==t}static isArray(t){return Array.isArray(t)}static isNullish(t){return null==t}static isNotNull(t){return null!=t}static isArrayOf(t,e){return Array.isArray(t)&&t.every(e)}static isStringArray(t){return this.isArrayOf(t,this.isString)}static isNumberArray(t){return this.isArrayOf(t,this.isNumber)}static isInstanceOf(t,e){return t instanceof e}static hasProperty(t,e){return this.isObject(t)&&e in t}static hasPropertyOfType(t,e,i){return this.hasProperty(t,e)&&i(t[e])}static createValidator(t,e,i){return{validate:t,typeName:e,errorMessage:i||`Expected ${e}`}}static checkObject(t,e){if(!this.isObject(t))return{success:!1,value:t,error:"Value is not an object",expectedType:"object",actualType:typeof t};const i=t,s={};for(const[r,n]of Object.entries(e)){const e=i[r];if(!n.validate(e))return{success:!1,value:t,error:`Property '${r}' ${n.errorMessage||`is not of type ${n.typeName}`}`,expectedType:n.typeName,actualType:typeof e};s[r]=e}return{success:!0,value:s}}static safeCast(t,e){return e.validate(t)?{success:!0,value:t}:{success:!1,value:t,error:e.errorMessage||`Value is not of type ${e.typeName}`,expectedType:e.typeName,actualType:typeof t}}static assertType(t,e,i){if(!e.validate(t)){const s=i||e.errorMessage||`Type assertion failed: expected ${e.typeName}, got ${typeof t}`;throw new TypeError(s)}}static tryConvert(t,e,i){try{const s=e(t);return i.validate(s)?{success:!0,value:s}:{success:!1,value:s,error:`Conversion result is not of type ${i.typeName}`,expectedType:i.typeName,actualType:typeof s}}catch(e){return{success:!1,value:t,error:`Conversion failed: ${e instanceof Error?e.message:String(e)}`,expectedType:i.typeName,actualType:typeof t}}}static stringToNumber(t){return this.tryConvert(t,(t=>{if("string"==typeof t){const e=Number(t);if(isNaN(e))throw new Error("Invalid number format");return e}throw new Error("Value is not a string")}),this.validators.number)}static toString(t){return this.tryConvert(t,(t=>String(t)),this.validators.string)}static toBoolean(t){return this.tryConvert(t,(t=>Boolean(t)),this.validators.boolean)}static isInRange(t,e,i,s=!0){return!!this.isNumber(t)&&(s?t>=e&&t<=i:t>e&&t<i)}static isStringLengthInRange(t,e,i){return this.isString(t)&&t.length>=e&&t.length<=i}static isArrayLengthInRange(t,e,i){return this.isArray(t)&&t.length>=e&&t.length<=i}static matchesPattern(t,e){return this.isString(t)&&e.test(t)}static isEmail(t){return this.matchesPattern(t,/^[^\s@]+@[^\s@]+\.[^\s@]+$/)}static isUrl(t){if(!this.isString(t))return!1;try{return new URL(t),!0}catch{return!1}}static isUuid(t){return this.matchesPattern(t,/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}}p.validators={string:p.createValidator((t=>"string"==typeof t),"string"),number:p.createValidator((t=>"number"==typeof t&&!isNaN(t)),"number"),boolean:p.createValidator((t=>"boolean"==typeof t),"boolean"),function:p.createValidator((t=>"function"==typeof t),"function"),object:p.createValidator((t=>"object"==typeof t&&null!==t),"object"),array:p.createValidator((t=>Array.isArray(t)),"array"),notNull:p.createValidator((t=>null!=t),"not null"),integer:p.createValidator((t=>"number"==typeof t&&Number.isInteger(t)),"integer"),positiveNumber:p.createValidator((t=>"number"==typeof t&&t>0),"positive number"),nonNegativeNumber:p.createValidator((t=>"number"==typeof t&&t>=0),"non-negative number"),nonEmptyString:p.createValidator((t=>"string"==typeof t&&t.trim().length>0),"non-empty string"),optional:t=>({validate:e=>void 0===e||t.validate(e),typeName:`${t.typeName} | undefined`,errorMessage:`Expected ${t.typeName} or undefined`}),nullable:t=>({validate:e=>null===e||t.validate(e),typeName:`${t.typeName} | null`,errorMessage:`Expected ${t.typeName} or null`}),union:(...t)=>({validate:e=>t.some((t=>t.validate(e))),typeName:t.map((t=>t.typeName)).join(" | "),errorMessage:`Expected one of: ${t.map((t=>t.typeName)).join(", ")}`})},function(t){t[t.Invalid=0]="Invalid",t[t.Success=1]="Success",t[t.Failure=2]="Failure",t[t.Running=3]="Running"}(a||(a={}));class g{constructor(){this.status=a.Invalid}invalidate(){this.status=a.Invalid}onStart(){}onEnd(){}tick(t){return this.status==a.Invalid&&this.onStart(),this.status=this.update(t),this.status!=a.Running&&this.onEnd(),this.status}}class m{constructor(t,e,i=.2,s=!1){if(this._lastTime=0,this._performanceMode=!1,this._stats={totalTicks:0,totalExecutionTime:0,averageExecutionTime:0,lastExecutionTime:0},null==t)throw new Error("上下文不能为null或undefined");if(null==e)throw new Error("根节点不能为null或undefined");if(i<0)throw new Error("更新周期不能为负数");this._context=t,this._root=e,this.updatePeriod=this._elapsedTime=i,this._performanceMode=s,this._lastTime=this._getCurrentTime()}_getCurrentTime(){try{return u.getCurrentTime()}catch{return this._performanceMode?Date.now()/1e3:performance.now()/1e3}}tick(t){const e=this._performanceMode?0:this._getCurrentTime();try{if(this.updatePeriod>0){let e;if(void 0!==t)e=t;else try{if(e=u.getDeltaTime(),e<=0){const t=this._getCurrentTime();e=t-this._lastTime,this._lastTime=t}}catch{const t=this._getCurrentTime();e=t-this._lastTime,this._lastTime=t}if(e<0||!isFinite(e))return void _.warn("BehaviorTree: 无效的deltaTime值,跳过此次更新",{deltaTime:e});if(e=Math.min(e,1),this._elapsedTime-=e,this._elapsedTime<=0){for(;this._elapsedTime<=0;)this._elapsedTime+=this.updatePeriod;this._executeRoot()}}else this._executeRoot()}catch(t){_.warn("行为树更新时发生错误",{error:t,context:this._context})}finally{if(!this._performanceMode&&e>0){const t=this._getCurrentTime()-e;this._updateStats(t)}}}_executeRoot(){this._root.tick(this._context),this._stats.totalTicks++}_updateStats(t){this._stats.lastExecutionTime=t,this._stats.totalExecutionTime+=t,this._stats.averageExecutionTime=this._stats.totalExecutionTime/this._stats.totalTicks}getContext(){return this._context}setContext(t){if(null==t)throw new Error("上下文不能为null或undefined");this._context=t}getRoot(){return this._root}setRoot(t){if(null==t)throw new Error("根节点不能为null或undefined");this._root=t}reset(){try{this._root.invalidate(),this._elapsedTime=this.updatePeriod,this._lastTime=this._getCurrentTime()}catch(t){console.error("重置行为树时发生错误:",t)}}setPerformanceMode(t){this._performanceMode=t,t&&console.log("行为树性能模式已启用:使用较低精度的时间计算以提高性能")}getStats(){return{...this._stats}}resetStats(){this._stats={totalTicks:0,totalExecutionTime:0,averageExecutionTime:0,lastExecutionTime:0}}isActive(){return this.updatePeriod<=0||this._elapsedTime<=0}getTimeToNextUpdate(){return this.updatePeriod>0?Math.max(this._elapsedTime,0):0}}!function(t){t[t.None=0]="None",t[t.LowerPriority=1]="LowerPriority",t[t.Self=2]="Self",t[t.Both=3]="Both"}(o||(o={}));class S{static has(t,e){return(t&e)==e}}function w(t){return t&&"IConditional"===t.discriminator}class y extends g{constructor(){super(...arguments),this.abortType=o.None,this._children=new Array,this._hasLowerPriorityConditionalAbort=!1,this._currentChildIndex=0}invalidate(){super.invalidate();const t=this._children.length;for(let e=0;e<t;e++)this._children[e].invalidate()}onStart(){this._hasLowerPriorityConditionalAbort=this.hasLowerPriorityConditionalAbortInChildren(),this._currentChildIndex=0}onEnd(){const t=this._children.length;for(let e=0;e<t;e++)this._children[e].invalidate()}hasLowerPriorityConditionalAbortInChildren(){for(let t=0;t<this._children.length;t++){let e=this._children[t];if(null!=e&&S.has(e.abortType,o.LowerPriority)&&e.isFirstChildConditional())return!0}return!1}addChild(t){this._children.push(t)}isFirstChildConditional(){return w(this._children[0])}updateSelfAbortConditional(t,e){for(let i=0;i<this._currentChildIndex;i++){const s=this._children[i];if(!w(s))continue;if(this.updateConditionalNode(t,s)!==e){this._currentChildIndex=i;const t=this._children.length;for(let e=i;e<t;e++)this._children[e].invalidate();break}}}updateLowerPriorityAbortConditional(t,e){for(let i=0;i<this._currentChildIndex;i++){const s=this._children[i];if(s&&S.has(s.abortType,o.LowerPriority)){const r=s._children[0];if(r){if(this.updateConditionalNode(t,r)!==e){this._currentChildIndex=i;const t=this._children.length;for(let e=i;e<t;e++)this._children[e].invalidate();break}}}}}updateConditionalNode(t,e){return e.update(t)}}class C extends g{invalidate(){super.invalidate(),this.child?.invalidate()}}class T extends g{constructor(t,e={}){if(super(),null==t)throw new Error("动作函数不能为null或undefined");if("function"!=typeof t)throw new Error("动作必须是一个函数");this._action=t,this._enableErrorHandling=e.enableErrorHandling??!0,this._name=e.name}update(t){if(!this._enableErrorHandling)return this._action(t);try{const e=this._action(t);return this.isValidTaskStatus(e)?e:(console.error(`ExecuteAction ${this._name||""}: 动作函数返回了无效的TaskStatus: ${e}`),a.Failure)}catch(t){const e=this._name?`"${this._name}"`:"";return console.error(`ExecuteAction ${e} 执行时发生错误:`,t),a.Failure}}isValidTaskStatus(t){return t===a.Success||t===a.Failure||t===a.Running}getName(){return this._name||this._action.name||"Anonymous Action"}static createAlwaysSuccess(t,e){return new T((e=>(t(e),a.Success)),{name:e||"Always Success Action"})}static createConditional(t,e){return new T((e=>t(e)?a.Success:a.Failure),{name:e||"Conditional Action"})}}class b extends T{constructor(t,e={}){super(t,e),this.discriminator="IConditional"}static createPredicate(t,e){return new b((e=>t(e)?a.Success:a.Failure),{name:e||"Predicate Condition"})}static createNumericComparison(t,e,i,s){const r={greater:(t,e)=>t>e,less:(t,e)=>t<e,equal:(t,e)=>Math.abs(t-e)<Number.EPSILON,greaterEqual:(t,e)=>t>=e,lessEqual:(t,e)=>t<=e},n=r[i],o=s||`Numeric ${i} ${e}`;return new b((i=>{try{const s=t(i);return"number"!=typeof s||isNaN(s)?(console.warn(`${o}: getValue返回了无效的数值: ${s}`),a.Failure):n(s,e)?a.Success:a.Failure}catch(t){return console.error(`${o}: 获取数值时发生错误:`,t),a.Failure}}),{name:o})}static createPropertyExists(t,e){return new b((i=>{try{return null!=t(i)?a.Success:a.Failure}catch(t){return console.error(`${e||"Property Check"}: 检查属性时发生错误:`,t),a.Failure}}),{name:e||"Property Exists Check"})}static createAnd(t,e){return new b((e=>{for(const i of t)if(!i(e))return a.Failure;return a.Success}),{name:e||"AND Condition"})}static createOr(t,e){return new b((e=>{for(const i of t)if(i(e))return a.Success;return a.Failure}),{name:e||"OR Condition"})}}class v extends g{constructor(t){super(),this.isError=!1,this.text=t}update(t){return this.isError?console.error(this.text):console.log(this.text),a.Success}}class x extends g{constructor(t,e=!1){if(super(),this._elapsedTime=0,this._useExternalTime=!1,this._lastUpdateTime=0,t<=0)throw new Error("等待时间必须大于0");this.waitTime=t,this._useExternalTime=e}onStart(){this._elapsedTime=0,this._lastUpdateTime=performance.now()/1e3}update(t){let e;var i;return this._useExternalTime&&(null!=(i=t)&&"object"==typeof i&&"deltaTime"in i&&"number"==typeof i.deltaTime)?(e=t.deltaTime,(e<0||!isFinite(e))&&(console.warn("WaitAction: 无效的deltaTime值,回退到内部时间计算"),e=this._calculateInternalDeltaTime())):e=this._calculateInternalDeltaTime(),this._elapsedTime+=e,this._elapsedTime>=this.waitTime?a.Success:a.Running}_calculateInternalDeltaTime(){const t=performance.now()/1e3,e=t-this._lastUpdateTime;return this._lastUpdateTime=t,Math.min(e,.1)}getProgress(){return Math.min(this._elapsedTime/this.waitTime,1)}getRemainingTime(){return Math.max(this.waitTime-this._elapsedTime,0)}setWaitTime(t,e=!1){if(t<=0)throw new Error("等待时间必须大于0");this.waitTime=t,e&&(this._elapsedTime=0,this._lastUpdateTime=performance.now()/1e3)}isCompleted(){return this._elapsedTime>=this.waitTime}}class E extends g{constructor(t){super(),this._childTree=t}update(t){return this._childTree.tick(),a.Success}}class N extends C{constructor(t,e=!0){if(super(),this.discriminator="IConditional",this._conditionalStatus=a.Invalid,!w(t))throw new Error("conditional 必须继承 IConditional");this._conditional=t,this._shouldReevaluate=e}invalidate(){super.invalidate(),this._conditionalStatus=a.Invalid}onStart(){this._conditionalStatus=a.Invalid}update(t){if(!this.child)throw new Error("child不能为空");return this._conditionalStatus=this.executeConditional(t),this._conditionalStatus==a.Success?this.child.tick(t):a.Failure}executeConditional(t,e=!1){return(e||this._shouldReevaluate||this._conditionalStatus==a.Invalid)&&(this._conditionalStatus=this._conditional.update(t)),this._conditionalStatus}}class P extends C{update(t){if(!this.child)throw new Error("child必须不能为空");return this.child.update(t)==a.Running?a.Running:a.Failure}}class M extends C{update(t){if(!this.child)throw new Error("child必须不能为空");return this.child.update(t)==a.Running?a.Running:a.Success}}class A extends C{update(t){if(!this.child)throw new Error("child必须不能为空");let e=this.child.tick(t);return e==a.Success?a.Failure:e==a.Failure?a.Success:a.Running}}class z extends C{constructor(t,e=!1,i=!1){if(super(),this._iterationCount=0,this._lastChildStatus=a.Invalid,!Number.isInteger(t)||t<-1||0===t)throw new Error("重复次数必须是正整数或-1(无限重复)");this.count=t,this.endOnFailure=e,this.endOnSuccess=i}get repeatForever(){return-1===this.count}set repeatForever(t){this.count=t?-1:Math.max(1,this.count)}onStart(){this._iterationCount=0,this._lastChildStatus=a.Invalid}update(t){if(!this.child)throw new Error("子节点不能为空");if(!this.repeatForever&&this._iterationCount>=this.count)return a.Success;const e=this.child.tick(t);return this._lastChildStatus=e,e===a.Running?a.Running:(this._iterationCount++,this.endOnFailure&&e===a.Failure||this.endOnSuccess&&e===a.Success||!this.repeatForever&&this._iterationCount>=this.count?a.Success:(this.child.invalidate(),a.Running))}getIterationCount(){return this._iterationCount}getRemainingCount(){return this.repeatForever?-1:Math.max(0,this.count-this._iterationCount)}getProgress(){return this.repeatForever?-1:Math.min(this._iterationCount/this.count,1)}getLastChildStatus(){return this._lastChildStatus}reset(){this._iterationCount=0,this._lastChildStatus=a.Invalid,this.child&&this.child.invalidate()}static createUntilSuccess(t=-1){return new z(t,!1,!0)}static createUntilFailure(t=-1){return new z(t,!0,!1)}static createInfinite(){return new z(-1,!1,!1)}}class I extends C{update(t){if(!this.child)throw new Error("child必须不为空");return this.child.update(t)!=a.Failure?a.Running:a.Success}}class $ extends C{update(t){if(!this.child)throw new Error("child必须不为空");return this.child.update(t)!=a.Success?a.Running:a.Success}}class k extends y{constructor(){super(...arguments),this._childCount=0}onStart(){super.onStart(),this._childCount=this._children.length}update(t){if(0===this._childCount)return a.Success;let e=0;for(let i=0;i<this._childCount;i++){const s=this._children[i];s.tick(t);const r=s.status;if(r===a.Failure)return a.Failure;r===a.Success&&e++}return e===this._childCount?a.Success:a.Running}addChild(t){super.addChild(t),this._childCount=this._children.length}}class F extends y{constructor(){super(...arguments),this._childCount=0}onStart(){super.onStart(),this._childCount=this._children.length}update(t){if(0===this._childCount)return a.Failure;let e=0;for(let i=0;i<this._childCount;i++){const s=this._children[i];s.tick(t);const r=s.status;if(r===a.Success)return a.Success;r===a.Failure&&e++}return e===this._childCount?a.Failure:a.Running}addChild(t){super.addChild(t),this._childCount=this._children.length}}class O extends y{constructor(t=o.None){super(),this._childCount=0,this.abortType=t}onStart(){super.onStart(),this._childCount=this._children.length}update(t){if(0===this._childCount)return a.Failure;if(0!==this._currentChildIndex&&this.handleConditionalAborts(t),this._currentChildIndex>=this._childCount)return this._currentChildIndex=0,a.Failure;const e=this._children[this._currentChildIndex].tick(t);return e!==a.Failure?e:(this._currentChildIndex++,this._currentChildIndex>=this._childCount?(this._currentChildIndex=0,a.Failure):a.Running)}addChild(t){super.addChild(t),this._childCount=this._children.length}handleConditionalAborts(t){this._hasLowerPriorityConditionalAbort&&this.updateLowerPriorityAbortConditional(t,a.Failure),S.has(this.abortType,o.Self)&&this.updateSelfAbortConditional(t,a.Failure)}}class L extends O{constructor(t=o.None,e=!0){super(t),this._originalOrder=null,this._reshuffleOnRestart=e}onStart(){if(null===this._originalOrder&&this._children.length>0&&(this._originalOrder=[...this._children]),this._children.length>1)try{e.shuffle(this._children)}catch(t){console.error("RandomSelector: 洗牌子节点时发生错误:",t),this._originalOrder&&(this._children=[...this._originalOrder])}}invalidate(){super.invalidate(),!this._reshuffleOnRestart&&this._originalOrder&&(this._children=[...this._originalOrder])}setReshuffleOnRestart(t){this._reshuffleOnRestart=t}getReshuffleOnRestart(){return this._reshuffleOnRestart}restoreOriginalOrder(){this._originalOrder&&(this._children=[...this._originalOrder])}reshuffleNow(){if(this._children.length>1)try{e.shuffle(this._children)}catch(t){console.error("RandomSelector: 手动洗牌时发生错误",t)}}}class R extends y{constructor(t=o.None){super(),this._childCount=0,this.abortType=t}onStart(){super.onStart(),this._childCount=this._children.length}update(t){if(0===this._childCount)return a.Success;if(0!==this._currentChildIndex&&this.handleConditionalAborts(t),this._currentChildIndex>=this._childCount)return this._currentChildIndex=0,a.Success;const e=this._children[this._currentChildIndex].tick(t);return e!==a.Success?e:(this._currentChildIndex++,this._currentChildIndex>=this._childCount?(this._currentChildIndex=0,a.Success):a.Running)}addChild(t){super.addChild(t),this._childCount=this._children.length}handleConditionalAborts(t){this._hasLowerPriorityConditionalAbort&&this.updateLowerPriorityAbortConditional(t,a.Success),S.has(this.abortType,o.Self)&&this.updateSelfAbortConditional(t,a.Success)}}class D extends R{constructor(t=o.None,e=!0){super(t),this._originalOrder=null,this._reshuffleOnRestart=e}onStart(){if(null===this._originalOrder&&this._children.length>0&&(this._originalOrder=[...this._children]),this._children.length>1)try{e.shuffle(this._children)}catch(t){console.error("RandomSequence: 洗牌子节点时发生错误:",t),this._originalOrder&&(this._children=[...this._originalOrder])}}invalidate(){super.invalidate(),!this._reshuffleOnRestart&&this._originalOrder&&(this._children=[...this._originalOrder])}setReshuffleOnRestart(t){this._reshuffleOnRestart=t}getReshuffleOnRestart(){return this._reshuffleOnRestart}restoreOriginalOrder(){this._originalOrder&&(this._children=[...this._originalOrder])}reshuffleNow(){if(this._children.length>1)try{e.shuffle(this._children)}catch(t){console.error("RandomSequence: 手动洗牌时发生错误",t)}}}class B{constructor(t){this._parentNodeStack=new Array,this._context=t}static begin(t){return new B(t)}setChildOnParent(t){let e=this._parentNodeStack[this._parentNodeStack.length-1];return e instanceof y?e.addChild(t):e instanceof C&&(e.child=t,this.endDecorator()),this}pushParentNode(t){return this._parentNodeStack.length>0&&this.setChildOnParent(t),this._parentNodeStack.push(t),this}endDecorator(){return this._currentNode=this._parentNodeStack.pop(),this}action(t){if(0==this._parentNodeStack.length)throw new Error("无法创建无嵌套的动作节点,它必须是一个叶节点");return this.setChildOnParent(new T(t))}actionR(t){return this.action((e=>t(e)?a.Success:a.Failure))}conditional(t){if(0==this._parentNodeStack.length)throw new Error("无法创建无嵌套的条件节点,它必须是一个叶节点");return this.setChildOnParent(new b(t))}conditionalR(t){return this.conditional((e=>t(e)?a.Success:a.Failure))}logAction(t){if(0==this._parentNodeStack.length)throw new Error("无法创建无嵌套的动作节点,它必须是一个叶节点");return this.setChildOnParent(new v(t))}waitAction(t){if(0==this._parentNodeStack.length)throw new Error("无法创建无嵌套的动作节点,它必须是一个叶节点");return this.setChildOnParent(new x(t))}subTree(t){if(0==this._parentNodeStack.length)throw new Error("无法创建无嵌套的动作节点,它必须是一个叶节点");return this.setChildOnParent(new E(t))}conditionalDecorator(t,e=!0){let i=new b(t);return this.pushParentNode(new N(i,e))}conditionalDecoratorR(t,e=!0){return this.conditionalDecorator((e=>t(e)?a.Success:a.Failure),e)}alwaysFail(){return this.pushParentNode(new P)}alwaysSucceed(){return this.pushParentNode(new M)}inverter(){return this.pushParentNode(new A)}repeater(t){return this.pushParentNode(new z(t))}untilFail(){return this.pushParentNode(new I)}untilSuccess(){return this.pushParentNode(new $)}paraller(){return this.pushParentNode(new k)}parallelSelector(){return this.pushParentNode(new F)}selector(t=o.None){return this.pushParentNode(new O(t))}randomSelector(){return this.pushParentNode(new L)}sequence(t=o.None){return this.pushParentNode(new R(t))}randomSequence(){return this.pushParentNode(new D)}endComposite(){if(!(this._parentNodeStack[this._parentNodeStack.length-1]instanceof y))throw new Error("尝试结束复合器,但顶部节点是装饰器");return this._currentNode=this._parentNodeStack.pop(),this}build(t=.2){if(!this._currentNode)throw new Error("无法创建零节点的行为树");return new m(this._context,this._currentNode,t)}}class j{constructor(t,e,i=100){if(this._pool=[],i<=0)throw new Error("池的最大大小必须大于0");if("function"!=typeof t)throw new Error("createFn必须是一个函数");this._createFn=t,this._resetFn=e,this._maxSize=i}get(){return this._pool.length>0?this._pool.pop():this._createFn()}release(t){if(null==t)throw new Error("不能归还null或undefined对象到池中");if(this._pool.includes(t))console.warn("对象已经在池中,忽略重复归还");else if(this._pool.length<this._maxSize){if(this._resetFn)try{this._resetFn(t)}catch(t){return void console.error("重置对象时发生错误:",t)}this._pool.push(t)}}prewarm(t){if(t<0)throw new Error("预填充数量不能小于0");const e=Math.min(t,this._maxSize-this._pool.length);for(let t=0;t<e;t++)try{this._pool.push(this._createFn())}catch(t){console.error("预填充对象时发生错误:",t);break}}clear(){this._pool.length=0}get size(){return this._pool.length}get maxSize(){return this._maxSize}set maxSize(t){if(t<=0)throw new Error("池的最大大小必须大于0");for(this._maxSize=t;this._pool.length>this._maxSize;)this._pool.pop()}get utilization(){return this._pool.length/this._maxSize}get isEmpty(){return 0===this._pool.length}get isFull(){return this._pool.length>=this._maxSize}}class U{constructor(){this._pools=new Map}static getInstance(){return this._instance||(this._instance=new U),this._instance}registerPool(t,e,i,s=50){if(!t||""===t.trim())throw new Error("节点类型名称不能为空");if(this._pools.has(t))throw new Error(`节点类型 "${t}" 的池已经存在`);const r=new j(e,i,s);this._pools.set(t,r)}get(t){const e=this._pools.get(t);return e?e.get():null}release(t,e){const i=this._pools.get(t);if(i&&null!=e)try{return i.release(e),!0}catch(e){return console.error(`归还对象到池 "${t}" 时发生错误:`,e),!1}return!1}prewarmAll(t=10){for(const[e,i]of this._pools.entries())try{i.prewarm(t)}catch(t){console.error(`预热池 "${e}" 时发生错误:`,t)}}clearAll(){for(const t of this._pools.values())t.clear()}removePool(t){const e=this._pools.get(t);return!!e&&(e.clear(),this._pools.delete(t),!0)}getStats(){const t={};for(const[e,i]of this._pools.entries())t[e]={size:i.size,maxSize:i.maxSize,utilization:i.utilization};return t}getRegisteredTypes(){return Array.from(this._pools.keys())}}!function(t){t[t.Low=0]="Low",t[t.Normal=1]="Normal",t[t.High=2]="High",t[t.Critical=3]="Critical"}(h||(h={}));class V{static registerPool(t){this._pools.add(t)}static unregisterPool(t){this._pools.delete(t)}static performGlobalCleanup(){const t=Array.from(this._pools).sort(((t,e)=>t.priority-e.priority));for(const e of t){if(e.priority===h.Critical)continue;const t=Math.floor(.5*e.size);e.shrink(t)}}static performGlobalMaintenance(){const t=Date.now();if(t-this._lastMaintenanceTime<this._maintenanceInterval)return;this._lastMaintenanceTime=t;for(const t of this._pools)t.performMaintenance();this._pools.size>50&&this.performGlobalCleanup()}static getGlobalStats(){let t=0;const e={[h.Low]:0,[h.Normal]:0,[h.High]:0,[h.Critical]:0};for(const i of this._pools)t+=i.size,e[i.priority]++;return{totalPools:this._pools.size,totalObjects:t,totalMemoryUsage:64*t,poolsByPriority:e}}static clearAllPools(t=!1){for(const e of this._pools)e.clear(t)}}V._pools=new Set,V._maintenanceInterval=1e4,V._lastMaintenanceTime=0;var W=Object.freeze({__proto__:null,AdvancedObjectPool:class{constructor(t,e,i={}){if(this._pool=[],this._poolSet=new WeakSet,this._lastCleanupTime=0,this._cleanupInterval=5e3,"function"!=typeof t)throw new Error("createFn必须是一个函数");if(this._createFn=t,this._resetFn=e,this._validator=i.validator,this._config={initialSize:i.initialSize??0,maxSize:i.maxSize??100,priority:i.priority??h.Normal,enableStats:i.enableStats??!0,validator:i.validator},this._config.maxSize<=0)throw new Error("最大池大小必须大于0");this._stats={currentSize:0,maxSize:this._config.maxSize,totalGets:0,totalReleases:0,totalCreations:0,hitRate:0,utilization:0,priority:this._config.priority},this._config.initialSize>0&&this.prewarm(this._config.initialSize),V.registerPool(this)}get(){if(this._updateStats("get"),this._pool.length>0){const t=this._pool.pop();return this._poolSet.delete(t),this._updateStats("hit"),t}const t=this._createObject();return this._updateStats("creation"),t}release(t){if(null==t)return console.warn("不能归还null或undefined对象到池中"),!1;if(this._poolSet.has(t))return console.warn("对象已经在池中,忽略重复归还"),!1;if(this._validator&&!this._validator(t))return console.warn("对象验证失败,拒绝归还到池中"),!1;if(this._pool.length>=this._config.maxSize)return!1;if(this._resetFn)try{this._resetFn(t)}catch(t){return console.error("重置对象时发生错误:",t),!1}return this._pool.push(t),this._poolSet.add(t),this._updateStats("release"),!0}_createObject(){try{return this._createFn()}catch(t){throw console.error("创建对象时发生错误:",t),t}}_updateStats(t){if(this._config.enableStats){switch(t){case"get":this._stats.totalGets++;break;case"release":this._stats.totalReleases++;break;case"creation":this._stats.totalCreations++}this._stats.currentSize=this._pool.length,this._stats.hitRate=this._stats.totalGets>0?(this._stats.totalGets-this._stats.totalCreations)/this._stats.totalGets:0,this._stats.utilization=this._stats.currentSize/this._stats.maxSize}}prewarm(t){if(t<0)throw new Error("预填充数量不能小于0");const e=Math.min(t,this._config.maxSize-this._pool.length);for(let t=0;t<e;t++)try{const t=this._createObject();this._pool.push(t),this._poolSet.add(t),this._updateStats("creation")}catch(t){console.error("预填充对象时发生错误:",t);break}}clear(t=!1){(t||this._config.priority!==h.Critical)&&(this._pool.length=0,this._updateStats("release"))}shrink(t){for(t<0&&(t=0);this._pool.length>t;){const t=this._pool.pop();t&&this._poolSet.delete(t)}this._updateStats("release")}performMaintenance(){const t=Date.now();if(!(t-this._lastCleanupTime<this._cleanupInterval)&&(this._lastCleanupTime=t,this._stats.utilization<.3&&this._pool.length>this._config.initialSize)){const t=Math.max(this._config.initialSize,Math.floor(.7*this._pool.length));this.shrink(t)}}get size(){return this._pool.length}get maxSize(){return this._config.maxSize}get priority(){return this._config.priority}set maxSize(t){if(t<=0)throw new Error("最大池大小必须大于0");this._config.maxSize=t,this._stats.maxSize=t,this._pool.length>t&&this.shrink(t)}getStats(){return this._updateStats("get"),{...this._stats}}resetStats(){this._stats.totalGets=0,this._stats.totalReleases=0,this._stats.totalCreations=0,this._stats.hitRate=0}get isEmpty(){return 0===this._pool.length}get isFull(){return this._pool.length>=this._config.maxSize}},AdvancedPoolManager:V,AlwaysFail:P,AlwaysSucceed:M,Behavior:g,BehaviorNodePoolManager:U,BehaviorTree:m,BehaviorTreeBuilder:B,BehaviorTreeReference:E,Composite:y,ConditionalDecorator:N,Decorator:C,ExecuteAction:T,ExecuteActionConditional:b,Inverter:A,LogAction:v,ObjectPool:j,Parallel:k,ParallelSelector:F,get PoolPriority(){return h},RandomProbability:class extends g{constructor(t){super(),this.discriminator="IConditional",this._successProbability=t}update(t){return Math.random()>this._successProbability?a.Success:a.Failure}},RandomSelector:L,RandomSequence:D,Repeater:z,Selector:O,Sequence:R,get TaskStatus(){return a},UntilFail:I,UntilSuccess:$,WaitAction:x,isIConditional:w});class H{setMachineAndContext(t,e){this._machine=t,this._context=e,this.onInitialized()}onInitialized(){}begin(){}reason(){}end(){}}class G{get currentState(){return this._currentState}constructor(t,e){if(this.elapsedTimeInState=0,this._states=new Map,null==t)throw new Error("上下文不能为null或undefined");if(null==e)throw new Error("初始状态不能为null或undefined");this._context=t,this.addState(e),this._currentState=e,this._currentState.begin()}addState(t){if(null==t)throw new Error("状态不能为null或undefined");const e=t.constructor;if