UNPKG

@esengine/ai

Version:

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

1 lines 103 kB
"use strict";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 r=[],s=new Set;for(;r.length<e;){const e=this.integer(0,t.length-1);s.has(e)||(s.add(e),r.push(t[e]))}return r}{const r=[...t];for(let t=0;t<e;t++){const e=this.integer(t,r.length-1);[r[t],r[e]]=[r[e],r[t]]}return r.slice(0,e)}}static gaussian(t=0,e=1){const r=this.value(),s=this.value();return Math.sqrt(-2*Math.log(r))*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 r=e.length-1;r>0;r--){const s=t.integer(0,r);[e[r],e[s]]=[e[s],e[r]]}}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 r{static setEnabled(t){this._enabled=t}static setThrowOnFailure(t){this._throwOnFailure=t}static fail(t,...e){const r=t||"断言失败";throw this._throwOnFailure||console.assert(!1,r,...e),new Error(r)}static isTrue(t,e,...r){this._enabled&&(t||this.fail(e||"条件必须为真",...r))}static isFalse(t,e,...r){this._enabled&&t&&this.fail(e||"条件必须为假",...r)}static isNotNull(t,e,...r){this._enabled&&null==t&&this.fail(e||"对象不能为null或undefined",...r)}static isNull(t,e,...r){this._enabled&&null!=t&&this.fail(e||"对象必须为null或undefined",...r)}static isNumber(t,e,...r){this._enabled&&("number"!=typeof t||isNaN(t))&&this.fail(e||"值必须是有效数字",...r)}static isString(t,e,...r){this._enabled&&"string"!=typeof t&&this.fail(e||"值必须是字符串",...r)}static isBoolean(t,e,...r){this._enabled&&"boolean"!=typeof t&&this.fail(e||"值必须是布尔值",...r)}static isFunction(t,e,...r){this._enabled&&"function"!=typeof t&&this.fail(e||"值必须是函数",...r)}static isObject(t,e,...r){this._enabled&&("object"==typeof t&&null!==t||this.fail(e||"值必须是对象",...r))}static isNotEmpty(t,e,...r){this._enabled&&(this.isNotNull(t,e,...r),0===t.length&&this.fail(e||"数组不能为空",...r))}static isNotEmptyString(t,e,...r){this._enabled&&(this.isNotNull(t,e,...r),0===t.trim().length&&this.fail(e||"字符串不能为空",...r))}static inRange(t,e,r,s,...a){this._enabled&&(this.isNumber(t,s,...a),(t<e||t>r)&&this.fail(s||`值必须在 ${e} 到 ${r} 之间`,...a))}static isInstanceOf(t,e,r,...s){this._enabled&&(t instanceof e||this.fail(r||`值必须是 ${e.name} 的实例`,...s))}static contains(t,e,r,...s){this._enabled&&(this.isNotNull(t,r,...s),t.includes(e)||this.fail(r||"数组必须包含指定元素",...s))}static getConfig(){return{enabled:this._enabled,throwOnFailure:this._throwOnFailure}}}var s,a,i,n,o,l,c,u;r._enabled=!0,r._throwOnFailure=!1,exports.LogLevel=void 0,(s=exports.LogLevel||(exports.LogLevel={}))[s.Debug=0]="Debug",s[s.Info=1]="Info",s[s.Warn=2]="Warn",s[s.Error=3]="Error",s[s.None=4]="None";class h{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,r=1e3){this._batchConfig.enabled=t,this._batchConfig.maxSize=Math.max(1,e),this._batchConfig.flushInterval=Math.max(100,r),t||this.flushLogs()}static debug(t,e){this._log(exports.LogLevel.Debug,t,e)}static info(t,e){this._log(exports.LogLevel.Info,t,e)}static warn(t,e){this._log(exports.LogLevel.Warn,t,e)}static error(t,e){this._log(exports.LogLevel.Error,t,e)}static _log(t,e,r){t<this._config.minLevel||this._config.minLevel===exports.LogLevel.None||(this._config.performanceMode&&this._fastLog?this._fastLog(e,r):this._batchConfig.enabled?this._addToBatch(t,e,r):this._config.performanceMode?this._performanceLog(t,e,r):this._standardLog(t,e,r))}static _addToBatch(t,e,r){const s={level:t,message:e,data:r,timestamp:Date.now(),prefix:this._config.prefix};this._logBuffer.push(s);const a=Date.now(),i=this._logBuffer.length>=this._batchConfig.maxSize,n=a-this._batchConfig.lastFlushTime>=this._batchConfig.flushInterval;(i||n)&&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],r=t.prefix?`[${t.prefix}] `:"";void 0!==t.data?console.log(`${r}[${e}] ${t.message}`,t.data):console.log(`${r}[${e}] ${t.message}`)}static _standardLogEntry(t){const e=this._config.enableTimestamp?this._formatTimestamp(t.timestamp):"",r=this._levelNames[t.level],s=t.prefix?`[${t.prefix}] `:"",a=this._levelStyles[t.level];let i=`${s}${e}[${r}] ${t.message}`;const n=this._getConsoleMethod(t.level);void 0!==t.data?a&&"function"==typeof console.log?n(`%c${i}`,a,t.data):n(i,t.data):a&&"function"==typeof console.log?n(`%c${i}`,a):n(i),t.level===exports.LogLevel.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,r){const s=this._levelNames[t],a=this._config.prefix?`[${this._config.prefix}] `:"";void 0!==r?console.log(`${a}[${s}] ${e}`,r):console.log(`${a}[${s}] ${e}`)}static _standardLog(t,e,r){const s=this._config.enableTimestamp?this._getTimestamp():"",a=this._levelNames[t],i=this._config.prefix?`[${this._config.prefix}] `:"",n=this._levelStyles[t];let o=`${i}${s}[${a}] ${e}`;const l=this._getConsoleMethod(t);void 0!==r?n&&"function"==typeof console.log?l(`%c${o}`,n,r):l(o,r):n&&"function"==typeof console.log?l(`%c${o}`,n):l(o),t===exports.LogLevel.Error&&this._config.enableStackTrace&&r instanceof Error&&console.trace(r)}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 exports.LogLevel.Debug:return console.debug||console.log;case exports.LogLevel.Info:return console.info||console.log;case exports.LogLevel.Warn:return console.warn||console.log;case exports.LogLevel.Error:return console.error||console.log;default:return console.log}}static getConfig(){return{...this._config}}static createPrefixed(t){return new d(t)}}h._config={minLevel:exports.LogLevel.Debug,enableTimestamp:!0,enableStackTrace:!0,performanceMode:!1,prefix:""},h._logBuffer=[],h._batchConfig={enabled:!1,maxSize:50,flushInterval:1e3,lastFlushTime:0},h._fastLog=null,h._levelNames={[exports.LogLevel.Debug]:"DEBUG",[exports.LogLevel.Info]:"INFO",[exports.LogLevel.Warn]:"WARN",[exports.LogLevel.Error]:"ERROR",[exports.LogLevel.None]:"NONE"},h._levelStyles={[exports.LogLevel.Debug]:"color: #888",[exports.LogLevel.Info]:"color: #007acc",[exports.LogLevel.Warn]:"color: #ff8c00",[exports.LogLevel.Error]:"color: #ff4444; font-weight: bold",[exports.LogLevel.None]:""};class d{constructor(t){this._prefix=t}debug(t,e){h.debug(`[${this._prefix}] ${t}`,e)}info(t,e){h.info(`[${this._prefix}] ${t}`,e)}warn(t,e){h.warn(`[${this._prefix}] ${t}`,e)}error(t,e){h.error(`[${this._prefix}] ${t}`,e)}}class p{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}}}p._currentTime=0,p._lastTime=0,p._deltaTime=0,p._unscaledDeltaTime=0,p._timeScale=1,p._maxDeltaTime=.1,p._useHighPrecision=!0,p._initialized=!1,p._frameCount=0,p._startTime=0,p._updateCallbacks=[],exports.ErrorLevel=void 0,(a=exports.ErrorLevel||(exports.ErrorLevel={}))[a.Development=0]="Development",a[a.Testing=1]="Testing",a[a.Production=2]="Production",a[a.Silent=3]="Silent";class _{static configure(t){this._config={...this._config,...t}}static setLevel(t){switch(this._config.level=t,t){case exports.ErrorLevel.Development:this._config.enableAssertions=!0,this._config.enableTypeChecking=!0;break;case exports.ErrorLevel.Testing:this._config.enableAssertions=!0,this._config.enableTypeChecking=!1;break;case exports.ErrorLevel.Production:this._config.enableAssertions=!1,this._config.enableTypeChecking=!1;break;case exports.ErrorLevel.Silent:this._config.enableAssertions=!1,this._config.enableTypeChecking=!1,this._config.enablePerformanceMonitoring=!1}}static assert(t,e,r){if(this._config.enableAssertions&&this._config.level!==exports.ErrorLevel.Silent&&(this._errorStats.totalAssertions++,!t)){const t=new Error(`断言失败: ${e}`);this._handleError(t,r)}}static checkType(t,e,r,s){if(!this._config.enableTypeChecking||this._config.level===exports.ErrorLevel.Silent)return;this._errorStats.totalTypeChecks++;const a=typeof t;if(a!==e){const t=new Error(r||`类型检查失败: 期望 ${e}, 实际 ${a}`);this._handleError(t,s)}}static checkNotNull(t,e,r){if(this._config.enableTypeChecking&&this._config.level!==exports.ErrorLevel.Silent&&(this._errorStats.totalTypeChecks++,null==t)){const t=new Error(e||"值不能为null或undefined");this._handleError(t,r)}}static checkRange(t,e,r,s,a){if(this._config.enableAssertions&&this._config.level!==exports.ErrorLevel.Silent&&(this._errorStats.totalAssertions++,t<e||t>r)){const i=new Error(s||`值 ${t} 超出范围 [${e}, ${r}]`);this._handleError(i,a)}}static checkArrayBounds(t,e,r,s){if(this._config.enableAssertions&&this._config.level!==exports.ErrorLevel.Silent&&(this._errorStats.totalAssertions++,e<0||e>=t.length)){const a=r||`数组索引 ${e} 超出边界 [0, ${t.length-1}]`,i=new Error(a);this._handleError(i,s)}}static monitor(t,e){if(!this._config.enablePerformanceMonitoring||this._config.level===exports.ErrorLevel.Silent)return e();const r=performance.now();try{const s=e(),a=performance.now();return this._recordPerformance(t,a-r),s}catch(e){const s=performance.now();throw this._recordPerformance(t,s-r),e}}static async monitorAsync(t,e){if(!this._config.enablePerformanceMonitoring||this._config.level===exports.ErrorLevel.Silent)return e();const r=performance.now();try{const s=await e(),a=performance.now();return this._recordPerformance(t,a-r),s}catch(e){const s=performance.now();throw this._recordPerformance(t,s-r),e}}static _recordPerformance(t,e){let r=this._performanceData.get(t);r||(r={functionName:t,executionTime:0,callCount:0,averageTime:0,maxTime:0,minTime:1/0},this._performanceData.set(t,r)),r.callCount++,r.executionTime+=e,r.averageTime=r.executionTime/r.callCount,r.maxTime=Math.max(r.maxTime,e),r.minTime=Math.min(r.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 exports.ErrorLevel.Development:throw t;case exports.ErrorLevel.Testing:throw console.error("错误:",t.message,e),t;case exports.ErrorLevel.Production:throw console.warn("错误:",t.message),t;case exports.ErrorLevel.Silent:}throw t}static warn(t,e){if(this._config.level!==exports.ErrorLevel.Silent){if(this._errorStats.totalWarnings++,this._config.onWarning)try{this._config.onWarning(t,e)}catch(t){console.error("警告回调执行失败:",t)}switch(this._config.level){case exports.ErrorLevel.Development:case exports.ErrorLevel.Testing:console.warn("警告:",t,e);break;case exports.ErrorLevel.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,r=!1){return(...s)=>{try{return r?this.monitor(e,(()=>t(...s))):t(...s)}catch(t){this._handleError(t instanceof Error?t:new Error(String(t)),{args:s,functionName:e})}}}}_._config={level:exports.ErrorLevel.Development,enableAssertions:!0,enableTypeChecking:!0,enablePerformanceMonitoring:!1},_._performanceData=new Map,_._errorStats={totalErrors:0,totalWarnings:0,totalAssertions:0,totalTypeChecks:0};class f{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,r){return this.hasProperty(t,e)&&r(t[e])}static createValidator(t,e,r){return{validate:t,typeName:e,errorMessage:r||`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 r=t,s={};for(const[a,i]of Object.entries(e)){const e=r[a];if(!i.validate(e))return{success:!1,value:t,error:`Property '${a}' ${i.errorMessage||`is not of type ${i.typeName}`}`,expectedType:i.typeName,actualType:typeof e};s[a]=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,r){if(!e.validate(t)){const s=r||e.errorMessage||`Type assertion failed: expected ${e.typeName}, got ${typeof t}`;throw new TypeError(s)}}static tryConvert(t,e,r){try{const s=e(t);return r.validate(s)?{success:!0,value:s}:{success:!1,value:s,error:`Conversion result is not of type ${r.typeName}`,expectedType:r.typeName,actualType:typeof s}}catch(e){return{success:!1,value:t,error:`Conversion failed: ${e instanceof Error?e.message:String(e)}`,expectedType:r.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,r,s=!0){return!!this.isNumber(t)&&(s?t>=e&&t<=r:t>e&&t<r)}static isStringLengthInRange(t,e,r){return this.isString(t)&&t.length>=e&&t.length<=r}static isArrayLengthInRange(t,e,r){return this.isArray(t)&&t.length>=e&&t.length<=r}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)}}f.validators={string:f.createValidator((t=>"string"==typeof t),"string"),number:f.createValidator((t=>"number"==typeof t&&!isNaN(t)),"number"),boolean:f.createValidator((t=>"boolean"==typeof t),"boolean"),function:f.createValidator((t=>"function"==typeof t),"function"),object:f.createValidator((t=>"object"==typeof t&&null!==t),"object"),array:f.createValidator((t=>Array.isArray(t)),"array"),notNull:f.createValidator((t=>null!=t),"not null"),integer:f.createValidator((t=>"number"==typeof t&&Number.isInteger(t)),"integer"),positiveNumber:f.createValidator((t=>"number"==typeof t&&t>0),"positive number"),nonNegativeNumber:f.createValidator((t=>"number"==typeof t&&t>=0),"non-negative number"),nonEmptyString:f.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(", ")}`})},exports.TaskStatus=void 0,(i=exports.TaskStatus||(exports.TaskStatus={}))[i.Invalid=0]="Invalid",i[i.Success=1]="Success",i[i.Failure=2]="Failure",i[i.Running=3]="Running";class g{constructor(){this.status=exports.TaskStatus.Invalid}invalidate(){this.status=exports.TaskStatus.Invalid}onStart(){}onEnd(){}tick(t){return this.status==exports.TaskStatus.Invalid&&this.onStart(),this.status=this.update(t),this.status!=exports.TaskStatus.Running&&this.onEnd(),this.status}}exports.BlackboardValueType=void 0,(n=exports.BlackboardValueType||(exports.BlackboardValueType={})).String="string",n.Number="number",n.Boolean="boolean",n.Vector2="vector2",n.Vector3="vector3",n.Object="object",n.Array="array";class m{constructor(){this._variables=new Map,this._listeners=new Map,this._listenerIdCounter=0,this._history=[],this.enableHistory=!1}defineVariable(t,e,r,s={}){if(!t||"string"!=typeof t)throw new Error("变量名必须是非空字符串");if(this._variables.has(t)&&console.warn(`黑板变量 "${t}" 已存在,将被重新定义`),!this._validateValueType(r,e))throw new Error(`默认值类型与变量类型 "${e}" 不匹配`);const a={name:t,type:e,value:this._cloneValue(r),defaultValue:this._cloneValue(r),description:s.description||"",readonly:s.readonly||!1,group:s.group||"Default",min:s.min,max:s.max,options:s.options?[...s.options]:void 0};this._variables.set(t,a)}setValue(t,e,r=!1){const s=this._variables.get(t);if(!s)return console.warn(`尝试设置不存在的黑板变量 "${t}"`),!1;if(s.readonly&&!r)return console.warn(`尝试修改只读黑板变量 "${t}"`),!1;if(!this._validateValueType(e,s.type))return console.error(`设置的值类型与变量 "${t}" 的类型 "${s.type}" 不匹配`),!1;if(s.type===exports.BlackboardValueType.Number&&"number"==typeof e){if(void 0!==s.min&&e<s.min)return console.warn(`变量 "${t}" 的值 ${e} 小于最小值 ${s.min}`),!1;if(void 0!==s.max&&e>s.max)return console.warn(`变量 "${t}" 的值 ${e} 大于最大值 ${s.max}`),!1}if(s.options&&!s.options.includes(e))return console.warn(`变量 "${t}" 的值不在允许的选项中`),!1;const a=this._cloneValue(s.value),i=this._cloneValue(e);return s.value=i,this.enableHistory&&this._history.push({variableName:t,oldValue:a,newValue:i,timestamp:Date.now()}),this._notifyListeners(t,i,a),!0}getValue(t,e){const r=this._variables.get(t);return r?this._cloneValue(r.value):void 0!==e?e:void console.warn(`尝试获取不存在的黑板变量 "${t}"`)}hasVariable(t){return this._variables.has(t)}getVariableDefinition(t){const e=this._variables.get(t);return e?{...e}:void 0}getVariableNames(){return Array.from(this._variables.keys())}getVariablesByGroup(t){return Array.from(this._variables.values()).filter((e=>e.group===t)).map((t=>({...t})))}getGroups(){const t=new Set;return this._variables.forEach((e=>{t.add(e.group||"Default")})),Array.from(t).sort()}resetVariable(t){const e=this._variables.get(t);return!!e&&this.setValue(t,e.defaultValue,!0)}resetAll(){this._variables.forEach(((t,e)=>{this.setValue(e,t.defaultValue,!0)}))}removeVariable(t){return!!this._variables.has(t)&&(this._variables.delete(t),this._listeners.delete(t),!0)}addListener(t,e){const r="listener_"+this._listenerIdCounter++,s={variableName:t,callback:e,id:r};return this._listeners.has(t)||this._listeners.set(t,[]),this._listeners.get(t).push(s),r}removeListener(t){for(const[e,r]of this._listeners.entries()){const s=r.findIndex((e=>e.id===t));if(-1!==s)return r.splice(s,1),0===r.length&&this._listeners.delete(e),!0}return!1}serialize(){const t={variables:Array.from(this._variables.entries()).map((([t,e])=>({name:t,type:e.type,value:e.value,defaultValue:e.defaultValue,description:e.description,readonly:e.readonly,group:e.group,min:e.min,max:e.max,options:e.options})))};return JSON.stringify(t,null,2)}deserialize(t){try{const e=JSON.parse(t);if(!e.variables||!Array.isArray(e.variables))throw new Error("无效的黑板数据格式");this._variables.clear(),this._listeners.clear();for(const t of e.variables)this.defineVariable(t.name,t.type,t.defaultValue,{description:t.description,readonly:t.readonly,group:t.group,min:t.min,max:t.max,options:t.options}),this.setValue(t.name,t.value,!0);return!0}catch(t){return console.error("反序列化黑板数据失败:",t),!1}}getHistory(){return[...this._history]}clearHistory(){this._history.length=0}_validateValueType(t,e){switch(e){case exports.BlackboardValueType.String:return"string"==typeof t;case exports.BlackboardValueType.Number:return"number"==typeof t&&!isNaN(t);case exports.BlackboardValueType.Boolean:return"boolean"==typeof t;case exports.BlackboardValueType.Vector2:return this._isVector2(t);case exports.BlackboardValueType.Vector3:return this._isVector3(t);case exports.BlackboardValueType.Object:return"object"==typeof t&&null!==t&&!Array.isArray(t);case exports.BlackboardValueType.Array:return Array.isArray(t);default:return!0}}_isVector2(t){return"object"==typeof t&&null!==t&&"number"==typeof t.x&&"number"==typeof t.y}_isVector3(t){return"object"==typeof t&&null!==t&&"number"==typeof t.x&&"number"==typeof t.y&&"number"==typeof t.z}_cloneValue(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map((t=>this._cloneValue(t)));const e={};for(const r in t)t.hasOwnProperty(r)&&(e[r]=this._cloneValue(t[r]));return e}_notifyListeners(t,e,r){const s=this._listeners.get(t);s&&s.forEach((t=>{try{t.callback(e,r)}catch(t){console.error("黑板监听器回调执行失败:",t)}}))}}class b{constructor(t,e,r=.2,s=!1,a){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(r<0)throw new Error("更新周期不能为负数");this._context=t,this._root=e,this.updatePeriod=this._elapsedTime=r,this._performanceMode=s,this._lastTime=this._getCurrentTime(),this._blackboard=a||new m,this._context.blackboard=this._blackboard}_getCurrentTime(){try{return p.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=p.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}getBlackboard(){return this._blackboard}setContext(t){if(null==t)throw new Error("上下文不能为null或undefined");this._context=t,this._context.blackboard=this._blackboard}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 x(t){return t&&"IConditional"===t.discriminator}function T(t){return x(t)&&"abortType"in t&&"executeConditional"in t&&"function"==typeof t.executeConditional}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++){const e=this._children[t];if(T(e)&&S.has(e.abortType,o.LowerPriority))return!0;const r=e;if(null!=r&&S.has(r.abortType,o.LowerPriority)&&r.isFirstChildConditional())return!0}return!1}addChild(t){this._children.push(t)}isFirstChildConditional(){return x(this._children[0])}updateSelfAbortConditional(t,e){for(let r=0;r<this._currentChildIndex;r++){const s=this._children[r];if(!x(s))continue;if(this.updateConditionalNode(t,s)!==e){this._currentChildIndex=r;const t=this._children.length;for(let e=r;e<t;e++)this._children[e].invalidate();break}}}updateLowerPriorityAbortConditional(t,e){for(let r=0;r<this._currentChildIndex;r++){const s=this._children[r];if(T(s)&&S.has(s.abortType,o.LowerPriority)){const a=s.executeConditional(t,!0);if(e===exports.TaskStatus.Failure?a===exports.TaskStatus.Success:a===exports.TaskStatus.Failure){this._currentChildIndex=r;const t=this._children.length;for(let e=r+1;e<t;e++)this._children[e].invalidate();break}}else{const a=s;if(a&&S.has(a.abortType,o.LowerPriority)){const s=a._children[0];if(s&&x(s)){const a=this.updateConditionalNode(t,s);if(e===exports.TaskStatus.Failure?a===exports.TaskStatus.Success:a===exports.TaskStatus.Failure){this._currentChildIndex=r;const t=this._children.length;for(let e=r+1;e<t;e++)this._children[e].invalidate();break}}}}}}updateConditionalNode(t,e){return e.update(t)}}class k extends g{invalidate(){super.invalidate(),this.child?.invalidate()}}class w 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}`),exports.TaskStatus.Failure)}catch(t){const e=this._name?`"${this._name}"`:"";return console.error(`ExecuteAction ${e} 执行时发生错误:`,t),exports.TaskStatus.Failure}}isValidTaskStatus(t){return t===exports.TaskStatus.Success||t===exports.TaskStatus.Failure||t===exports.TaskStatus.Running}getName(){return this._name||this._action.name||"Anonymous Action"}static createAlwaysSuccess(t,e){return new w((e=>(t(e),exports.TaskStatus.Success)),{name:e||"Always Success Action"})}static createConditional(t,e){return new w((e=>t(e)?exports.TaskStatus.Success:exports.TaskStatus.Failure),{name:e||"Conditional Action"})}}class v extends w{constructor(t,e={}){super(t,e),this.discriminator="IConditional"}static createPredicate(t,e){return new v((e=>t(e)?exports.TaskStatus.Success:exports.TaskStatus.Failure),{name:e||"Predicate Condition"})}static createNumericComparison(t,e,r,s){const a={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},i=a[r],n=s||`Numeric ${r} ${e}`;return new v((r=>{try{const s=t(r);return"number"!=typeof s||isNaN(s)?(console.warn(`${n}: getValue返回了无效的数值: ${s}`),exports.TaskStatus.Failure):i(s,e)?exports.TaskStatus.Success:exports.TaskStatus.Failure}catch(t){return console.error(`${n}: 获取数值时发生错误:`,t),exports.TaskStatus.Failure}}),{name:n})}static createPropertyExists(t,e){return new v((r=>{try{return null!=t(r)?exports.TaskStatus.Success:exports.TaskStatus.Failure}catch(t){return console.error(`${e||"Property Check"}: 检查属性时发生错误:`,t),exports.TaskStatus.Failure}}),{name:e||"Property Exists Check"})}static createAnd(t,e){return new v((e=>{for(const r of t)if(!r(e))return exports.TaskStatus.Failure;return exports.TaskStatus.Success}),{name:e||"AND Condition"})}static createOr(t,e){return new v((e=>{for(const r of t)if(r(e))return exports.TaskStatus.Success;return exports.TaskStatus.Failure}),{name:e||"OR Condition"})}}!function(t){t.Equal="equal",t.NotEqual="notEqual",t.Greater="greater",t.GreaterOrEqual="greaterOrEqual",t.Less="less",t.LessOrEqual="lessOrEqual",t.Contains="contains",t.NotContains="notContains"}(l||(l={}));class C{constructor(t,e,r=null,s){this.discriminator="IConditional",this.variableName=t,this.operator=e,this.compareValue=r,this.compareVariable=s}update(t){const e=t.blackboard;if(!(e&&e instanceof m))return console.warn("BlackboardValueComparison: 上下文中未找到Blackboard实例"),exports.TaskStatus.Failure;if(!e.hasVariable(this.variableName))return console.warn(`BlackboardValueComparison: 变量 "${this.variableName}" 不存在`),exports.TaskStatus.Failure;const r=e.getValue(this.variableName);let s;if(this.compareVariable){if(!e.hasVariable(this.compareVariable))return console.warn(`BlackboardValueComparison: 比较变量 "${this.compareVariable}" 不存在`),exports.TaskStatus.Failure;s=e.getValue(this.compareVariable)}else s=this.compareValue;return this._performComparison(r,s,this.operator)?exports.TaskStatus.Success:exports.TaskStatus.Failure}_performComparison(t,e,r){switch(r){case l.Equal:return t===e;case l.NotEqual:return t!==e;case l.Greater:return"number"==typeof t&&"number"==typeof e&&t>e;case l.GreaterOrEqual:return"number"==typeof t&&"number"==typeof e&&t>=e;case l.Less:return"number"==typeof t&&"number"==typeof e&&t<e;case l.LessOrEqual:return"number"==typeof t&&"number"==typeof e&&t<=e;case l.Contains:return("string"==typeof t&&"string"==typeof e||!!Array.isArray(t))&&t.includes(e);case l.NotContains:return"string"==typeof t&&"string"==typeof e?!t.includes(e):!Array.isArray(t)||!t.includes(e);default:return!1}}}class N{constructor(t,e=!1){this.discriminator="IConditional",this.variableName=t,this.invert=e}update(t){const e=t.blackboard;if(!(e&&e instanceof m))return console.warn("BlackboardVariableExists: 上下文中未找到Blackboard实例"),this.invert?exports.TaskStatus.Success:exports.TaskStatus.Failure;const r=e.hasVariable(this.variableName),s=r?e.getValue(this.variableName):void 0,a=r&&null!=s;return(this.invert?!a:a)?exports.TaskStatus.Success:exports.TaskStatus.Failure}}class E{constructor(t,e){this.discriminator="IConditional",this.variableName=t,this.expectedType=e}update(t){const e=t.blackboard;if(!(e&&e instanceof m))return console.warn("BlackboardVariableTypeCheck: 上下文中未找到Blackboard实例"),exports.TaskStatus.Failure;const r=e.getVariableDefinition(this.variableName);if(!r)return exports.TaskStatus.Failure;return r.type===this.expectedType?exports.TaskStatus.Success:exports.TaskStatus.Failure}}class V{constructor(t,e,r){this.discriminator="IConditional",this.variableName=t,this.minValue=e,this.maxValue=r}update(t){const e=t.blackboard;if(!(e&&e instanceof m))return console.warn("BlackboardVariableRangeCheck: 上下文中未找到Blackboard实例"),exports.TaskStatus.Failure;if(!e.hasVariable(this.variableName))return exports.TaskStatus.Failure;const r=e.getValue(this.variableName);if("number"!=typeof r)return exports.TaskStatus.Failure;return r>=this.minValue&&r<=this.maxValue?exports.TaskStatus.Success:exports.TaskStatus.Failure}}class F{static createCondition(t,e={},r){if(!t)return new v((()=>exports.TaskStatus.Success));switch(t.type){case"blackboard-value-comparison":return F.createBlackboardComparison(e);case"condition-custom":return F.createCustomCondition(t.properties||e);case"event-condition":return F.createEventCondition(t.properties||e,r);default:return console.warn(`未知的条件类型: ${t.type},使用默认成功条件`),new v((()=>exports.TaskStatus.Success))}}static createBlackboardComparison(t){const e=F.extractNestedValue(t.variableName)||"variable",r=F.extractNestedValue(t.operator)||"equal",s=F.extractNestedValue(t.compareValue),a=F.extractNestedValue(t.compareVariable),i=F.mapOperatorToEnum(r),n=F.cleanVariableName(e),o=a?F.cleanVariableName(a):void 0;let l=s;return"string"==typeof s&&("true"===s.toLowerCase()?l=!0:"false"===s.toLowerCase()?l=!1:isNaN(Number(s))||""===s.trim()||(l=Number(s))),new C(n,i,l,o)}static createCustomCondition(t={}){const e=t.conditionCode,r="string"==typeof e?e:"object"==typeof e&&e&&"value"in e?String(e.value):void 0;if(r&&"string"==typeof r)try{const t=new Function("context",`\n try {\n return (${r})(context);\n } catch (error) {\n console.error('自定义条件函数执行错误:', error);\n return false;\n }\n `);return new v((e=>{try{return t(e)?exports.TaskStatus.Success:exports.TaskStatus.Failure}catch(t){return console.error("自定义条件函数执行失败:",t),exports.TaskStatus.Failure}}))}catch(t){console.warn("解析自定义条件函数失败:",t)}return new v((()=>exports.TaskStatus.Failure))}static createEventCondition(t={},e){const r=F.extractNestedValue(t.eventName);return r&&"string"==typeof r?new v((e=>{try{const s=e.eventRegistry;if(!s)return console.warn("[event-condition] 未找到事件注册表,请在执行上下文中提供 eventRegistry"),exports.TaskStatus.Failure;const a=s.getConditionHandler?s.getConditionHandler(r):s.handlers?.get(r);if(!a)return console.warn(`[event-condition] 未找到条件处理器: ${r}`),exports.TaskStatus.Failure;let i={};const n=F.extractNestedValue(t.parameters);if(n){if("string"==typeof n)try{i=JSON.parse(n)}catch(t){console.warn(`[event-condition] 参数解析失败: ${n}`)}else i=n;const t=e.blackboard;t&&(i=F.replaceBlackboardVariables(i,t))}const o=a(e,i);return o instanceof Promise?(console.warn(`[event-condition] 条件 ${r} 返回Promise,条件节点不支持异步操作`),exports.TaskStatus.Failure):o?exports.TaskStatus.Success:exports.TaskStatus.Failure}catch(t){return console.error(`[event-condition] 条件 ${r} 检查失败:`,t),exports.TaskStatus.Failure}})):(console.warn("[event-condition] 缺少有效的 eventName 属性"),new v((()=>exports.TaskStatus.Failure)))}static mapOperatorToEnum(t){switch(t.toLowerCase()){case"equal":default:return l.Equal;case"notequal":case"not_equal":return l.NotEqual;case"greater":return l.Greater;case"greaterorequal":case"greater_or_equal":return l.GreaterOrEqual;case"less":return l.Less;case"lessorequal":case"less_or_equal":return l.LessOrEqual;case"contains":return l.Contains;case"notcontains":case"not_contains":return l.NotContains}}static cleanVariableName(t){return"string"!=typeof t?String(t):t.replace(/^\{\{|\}\}$/g,"")}static extractNestedValue(t){return null==t||"object"!=typeof t?t:"value"in t?F.extractNestedValue(t.value):t}static replaceBlackboardVariables(t,e){if("string"==typeof t)return t.replace(/\{\{([^}]+)\}\}/g,((t,r)=>{const s=e.get?e.get(r):e[r];return void 0!==s?s:t}));if(Array.isArray(t))return t.map((t=>F.replaceBlackboardVariables(t,e)));if(t&&"object"==typeof t){const r={};for(const s in t)t.hasOwnProperty(s)&&(r[s]=F.replaceBlackboardVariables(t[s],e));return r}return t}}class L extends g{constructor(t){super(),this.isError=!1,this.text=t}update(t){return this.isError?console.error(this.text):console.log(this.text),exports.TaskStatus.Success}}class $ 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 r;return this._useExternalTime&&(null!=(r=t)&&"object"==typeof r&&"deltaTime"in r&&"number"==typeof r.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?exports.TaskStatus.Success:exports.TaskStatus.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 A extends g{constructor(t){super(),this._childTree=t}update(t){return this._childTree.tick(),exports.TaskStatus.Success}}class B extends k{constructor(t,e=!0,r=o.None){if(super(),this.discriminator="IConditional",this.abortType=o.None,this._conditionalStatus=exports.TaskStatus.Invalid,!x(t))throw new Error("conditional 必须继承 IConditional");this._conditional=t,this._shouldReevaluate=e,this.abortType=r}invalidate(){super.invalidate(),this._conditionalStatus=exports.TaskStatus.Invalid}onStart(){this._conditionalStatus=exports.TaskStatus.Invalid}update(t){if(!this.child)throw new Error("child不能为空");if(!this._shouldReevaluate&&this.child.status===exports.TaskStatus.Running)return this.child.tick(t);if(this._conditionalStatus=this.executeConditional(t),this._conditionalStatus==exports.TaskStatus.Success){return this.child.tick(t)}return exports.TaskStatus.Failure}executeConditional(t,e=!1){return(e||this._shouldReevaluate||this._conditionalStatus==exports.TaskStatus.Invalid)&&(this._conditionalStatus=this._conditional.update(t)),this._conditionalStatus}}class M extends k{update(t){if(!this.child)throw new Error("child必须不能为空");return this.child.update(t)==exports.TaskStatus.Running?exports.TaskStatus.Running:exports.TaskStatus.Failure}}class P extends k{update(t){if(!this.child)throw new Error("child必须不能为空");return this.child.update(t)==exports.TaskStatus.Running?exports.TaskStatus.Running:exports.TaskStatus.Success}}class O extends k{update(t){if(!this.child)throw new Error("child必须不能为空");let e=this.child.tick(t);return e==exports.TaskStatus.Success?exports.TaskStatus.Failure:e==exports.TaskStatus.Failure?exports.TaskStatus.Success:exports.TaskStatus.Running}}class I extends k{constructor(t,e=!1,r=!1){if(super(),this._iterationCount=0,this._lastChildStatus=exports.TaskStatus.Invalid,!Number.isInteger(t)||t<-1||0===t)throw new Error("重复次数必须是正整数或-1(无限重复)");this.count=t,this.endOnFailure=e,this.endOnSuccess=r}get repeatForever(){return-1===this.count}set repeatForever(t){this.count=t?-1:Math.max(1,this.count)}onStart(){this._iterationCount=0,this._lastChildStatus=exports.TaskStatus.Invalid}update(t){if(!this.child)throw new Error("子节点不能为空");if(!this.repeatForever&&this._iterationCount>=this.count)return exports.TaskStatus.Success;const e=this.child.tick(t);return this._lastChildStatus=e,e===exports.TaskStatus.Running?exports.TaskStatus.Running:(this._iterationCount++,this.endOnFailure&&e===exports.TaskStatus.Failure||this.endOnSuccess&&e===exports.TaskStatus.Success||!this.repeatForever&&this._iterationCount>=this.count?exports.TaskStatus.Success:(this.child.invalidate(),exports.TaskStatus.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=exports.TaskStatus.Invalid,this.child&&this.child.invalidate()}static createUntilSuccess(t=-1){return new I(t,!1,!0)}static createUntilFailure(t=-1){return new I(t,!0,!1)}static createInfinite(){return new I(-1,!1,!1)}}class z extends k{update(t){if(!this.child)throw new Error("child必须不为空");return this.child.update(t)!=exports.TaskStatus.Failure?exports.TaskStatus.Running:exports.TaskStatus.Success}}class R extends k{update(t){if(!this.child)throw new Error("child必须不为空");return this.child.update(t)!=exports.TaskStatus.Success?exports.TaskStatus.Running:exports.TaskStatus.Success}}class D extends y{constructor(){super(...arguments),this._childCount=0}onStart(){super.onStart(),this._childCount=this._children.length}update(t){if(0===this._childCount)return exports.TaskStatus.Success;let e=0;for(let r=0;r<this._childCount;r++){const s=this._children[r];s.tick(t);const a=s.status;if(a===exports.TaskStatus.Failure)return exports.TaskStatus.Failure;a===exports.TaskStatus.Success&&e++}return e===this._childCount?exports.TaskStatus.Success:exports.TaskStatus.Running}addChild(t){super.addChild(t),this._childCount=this._children.length}}class q extends y{constructor(){super(...arguments),this._childCount=0}onStart(){super.onStart(),this._childCount=this._children.length}update(t){if(0===this._childCount)return exports.TaskStatus.Failure;let e=0;for(let r=0;r<this._childCount;r++){const s=this._children[r];s.tick(t);const a=s.status;if(a===exports.TaskStatus.Success)return exports.TaskStatus.Success;a===exports.TaskStatus.Failure&&e++}return e===this._childCount?exports.TaskStatus.Failure:exports.TaskStatus.Running}addChild(t){super.addChild(t),this._childCount=this._children.length}}class j extends y{constructor(t=o.None){super(),this._childCount=0,this.abortType=t}onStart(){super.onStart(),this._childCount=this._children.length,this._currentChildIndex=0}update(t){if(0===this._childCount)return exports.TaskStatus.Failure;if(0!==this._currentChildIndex&&this.handleConditionalAborts(t),this._currentChildIndex>=this._childCount)return this._currentChildIndex=0,exports.TaskStatus.Failure;const e=this._children[this._currentChildIndex].tick(t);return e!==exports.TaskStatus.Failure?e:(this._currentChildIndex++,this._currentChildIndex>=this._childCount?(this._currentChildIndex=0,exports.TaskStatus.Failure):exports.TaskStatus.Running)}invalidate(){super.invalidate(),this._currentChildIndex=0}addChild(t){super.addChild(t),this._childCount=this._children.length}handleConditionalAborts(t){this._hasLowerPriorityConditionalAbort&&this.updateLowerPriorityAbortConditional(t,exports.TaskStatus.Failure),S.has(this.abortType,o.Self)&&this.updateSelfAbortConditional(t,exports.TaskStatus.Failure)}}class H extends j{constructor(t=o.None,e=!0){super(t),this._originalOrder=null,this._reshuffleOnRestart=e}onStart(){if(super.onStart(),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 U extends y{constructor(t=o.None){super(),this._childCount=0,this.abortType=t}onStart(){super.onStart(),this._childCount=this._children.length,this._currentChildIndex=0}update(t){if(0===this._childCount)return exports.TaskStatus.Success;if(0!==this._currentChildIndex&&this.handleConditionalAborts(t),this._currentChildIndex>=this._childCount)return this._currentChildIndex=0,exports.TaskStatus.Success;const e=this._children[this._currentChildIndex].tick(t);return e!==exports.TaskStatus.Success?e:(this._currentChildIndex++,this._currentChildIndex>=this._childCount?(this._currentChildIndex=0,exports.TaskStatus.Success):exports.TaskStatus.Running)}invalidate(){super.invalidate(),this._currentChildIndex=0}addChild(t){super.addChild(t),this._childCount=this._children.length}handleConditionalAborts(t){this._hasLowerPriorityConditionalAbort&&this.updateLowerPriorityAbortConditional(t,exports.TaskStatus.Success),S.has(this.abortType,o.Self)&&this.updateSelfAbortConditional(t,exports.TaskStatus.Success)}}class G extends U{constructor(t=o.None,e=!0){super(t),this._originalOrder=null,this._reshuffleOnRestart=e}onStart(){if(super.onStart(),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 W extends g{constructor(t,e=null,r,s=!1){super(),this.variableName=t,this.value=e,this.sourceVariable=r,this.force=s}update(t){const e=t.blackboard;if(!(e&&e instanceof m))return console.warn("SetBlackboardValue: 上下文中未找到Blackboard实例"),exports.TaskStatus.Failure;let r;if(this.sourceVariable){if(!e.hasVariable(this.sourceVariable))return console.warn(`SetBlackboardValue: 源变量 "${this.sourceVariable}" 不存在`),exports.TaskStatus.Failure;r=e.getValue(this.sourceVariable)}else if(r=this.value,"string"==typeof r){const t=r.match(/^{{\s*(\w+)\s*}}$/);if(t){const s=t[1];if(!e.hasVariable(s))return console.warn(`SetBlackboardValue: 引用的变量 "${s}" 不存在`),exports.TaskStatus.Failure;r=e.getValue(s)}else r=r.replace(/\{\{(\w+)\}\}/g,((t,r)=>{if(e.hasVariable(r)){const s=e.getValue(r);return void 0!==s?String(s):t}return t}))}const s=e.getVariableDefinition(this.variableName);s&&null!=r&&(r=this.convertValueToTargetType(r,s.type));return e.setValue(this.variableName,r,this.force)?exports.TaskStatus.Success:exports.TaskStatus.Failure}convertValueToTargetType(t,e){if(null==t)return t;switch(e===