@esengine/behavior-tree 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +1 -1
- package/index.cjs.map +1 -1
- package/index.d.ts +944 -2095
- package/index.es5.js +2 -2
- package/index.es5.js.map +1 -1
- package/index.mjs +1 -1
- package/index.mjs.map +1 -1
- package/index.umd.js +1 -1
- package/index.umd.js.map +1 -1
- package/package.json +1 -1
package/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e,t,o,s,r,i,n=require("@esengine/ecs-framework");function a(e,t,o,s){var r,i=arguments.length,n=i<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,o):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,o,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(n=(i<3?r(n):i>3?r(t,o,n):r(t,o))||n);return i>3&&n&&Object.defineProperty(t,o,n),n}function d(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}"function"==typeof SuppressedError&&SuppressedError,exports.TaskStatus=void 0,(e=exports.TaskStatus||(exports.TaskStatus={}))[e.Invalid=0]="Invalid",e[e.Success=1]="Success",e[e.Failure=2]="Failure",e[e.Running=3]="Running",exports.NodeType=void 0,(t=exports.NodeType||(exports.NodeType={})).Composite="composite",t.Decorator="decorator",t.Action="action",t.Condition="condition",exports.CompositeType=void 0,(o=exports.CompositeType||(exports.CompositeType={})).Sequence="sequence",o.Selector="selector",o.Parallel="parallel",o.ParallelSelector="parallel-selector",o.RandomSequence="random-sequence",o.RandomSelector="random-selector",exports.DecoratorType=void 0,(s=exports.DecoratorType||(exports.DecoratorType={})).Inverter="inverter",s.Repeater="repeater",s.UntilSuccess="until-success",s.UntilFail="until-fail",s.AlwaysSucceed="always-succeed",s.AlwaysFail="always-fail",s.Conditional="conditional",s.Cooldown="cooldown",s.Timeout="timeout",exports.AbortType=void 0,(r=exports.AbortType||(exports.AbortType={})).None="none",r.Self="self",r.LowerPriority="lower-priority",r.Both="both",exports.BlackboardValueType=void 0,(i=exports.BlackboardValueType||(exports.BlackboardValueType={})).String="string",i.Number="number",i.Boolean="boolean",i.Vector2="vector2",i.Vector3="vector3",i.Object="object",i.Array="array";class c{static registerNodeClass(e,t){const o=`${t.category}:${t.displayName}`;this.nodeClasses.set(o,{metadata:t,constructor:e})}static getAllNodeClasses(){return Array.from(this.nodeClasses.values())}static getNodeClass(e,t){const o=`${e}:${t}`;return this.nodeClasses.get(o)?.constructor}static clear(){this.nodeClasses.clear()}}function p(e){return function(t){const o={...e,className:t.name};return c.registerNodeClass(t,o),t}}function l(e){return function(t,o){t.constructor.__nodeProperties||(t.constructor.__nodeProperties=[]),t.constructor.__nodeProperties.push({name:o,...e})}}c.nodeClasses=new Map;const u=l;function h(){return c.getAllNodeClasses().map((({metadata:e,constructor:t})=>{const o=t.__nodeProperties||[],s={nodeType:e.type.toLowerCase()},r=new t,i=o.map((e=>{const t=r[e.name];return void 0!==t&&(s[e.name]=t),{...e,defaultValue:void 0!==t?t:e.defaultValue}}));switch(e.type){case exports.NodeType.Composite:s.compositeType=e.displayName;break;case exports.NodeType.Decorator:s.decoratorType=e.displayName;break;case exports.NodeType.Action:s.actionType=e.displayName;break;case exports.NodeType.Condition:s.conditionType=e.displayName}return{type:e.type,displayName:e.displayName,category:e.category,icon:e.icon,description:e.description,color:e.color,className:e.className,requiresChildren:e.requiresChildren,defaultConfig:s,properties:i}}))}var m,y;exports.ExecuteAction=class extends n.Component{constructor(){super(...arguments),this.actionCode="return TaskStatus.Success;",this.parameters={}}getFunction(){if(!this.compiledFunction&&this.actionCode)try{const e=new Function("entity","blackboard","deltaTime","parameters","TaskStatus",`\n const { Success, Failure, Running, Invalid } = TaskStatus;\n try {\n ${this.actionCode}\n } catch (error) {\n return TaskStatus.Failure;\n }\n `);this.compiledFunction=(t,o,s)=>e(t,o,s,this.parameters,exports.TaskStatus)||exports.TaskStatus.Success}catch(e){return}return this.compiledFunction}setFunction(e){this.compiledFunction=e}},a([l({label:"动作代码",type:"code",description:"JavaScript 代码,返回 TaskStatus",required:!0}),n.Serialize(),d("design:type",String)],exports.ExecuteAction.prototype,"actionCode",void 0),a([n.Serialize(),d("design:type",Object)],exports.ExecuteAction.prototype,"parameters",void 0),a([n.IgnoreSerialization(),d("design:type",Function)],exports.ExecuteAction.prototype,"compiledFunction",void 0),exports.ExecuteAction=a([p({displayName:"自定义动作",category:"动作",type:exports.NodeType.Action,icon:"Code",description:"执行自定义代码",color:"#FFC107"}),n.ECSComponent("ExecuteAction"),n.Serializable({version:1})],exports.ExecuteAction),exports.WaitAction=class extends n.Component{constructor(){super(...arguments),this.waitTime=1,this.elapsedTime=0}reset(){this.elapsedTime=0}},a([l({label:"等待时间",type:"number",min:0,step:.1,description:"等待时间(秒)",required:!0}),n.Serialize(),d("design:type",Number)],exports.WaitAction.prototype,"waitTime",void 0),a([n.IgnoreSerialization(),d("design:type",Number)],exports.WaitAction.prototype,"elapsedTime",void 0),exports.WaitAction=a([p({displayName:"等待",category:"动作",type:exports.NodeType.Action,icon:"Clock",description:"等待指定时间",color:"#9E9E9E"}),n.ECSComponent("WaitAction"),n.Serializable({version:1})],exports.WaitAction),exports.LogAction=class extends n.Component{constructor(){super(...arguments),this.message="Hello",this.level="log",this.includeEntityInfo=!1}},a([l({label:"消息",type:"string",required:!0}),n.Serialize(),d("design:type",String)],exports.LogAction.prototype,"message",void 0),a([l({label:"级别",type:"select",options:[{label:"Log",value:"log"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"}]}),n.Serialize(),d("design:type",String)],exports.LogAction.prototype,"level",void 0),a([l({label:"包含实体信息",type:"boolean"}),n.Serialize(),d("design:type",Boolean)],exports.LogAction.prototype,"includeEntityInfo",void 0),exports.LogAction=a([p({displayName:"日志",category:"动作",type:exports.NodeType.Action,icon:"FileText",description:"输出日志消息",color:"#673AB7"}),n.ECSComponent("LogAction"),n.Serializable({version:1})],exports.LogAction),exports.SetBlackboardValueAction=class extends n.Component{constructor(){super(...arguments),this.variableName="",this.value="",this.force=!1}},a([l({label:"变量名",type:"variable",required:!0}),n.Serialize(),d("design:type",String)],exports.SetBlackboardValueAction.prototype,"variableName",void 0),a([l({label:"值",type:"string",description:"可以使用 {{varName}} 引用其他变量"}),n.Serialize(),d("design:type",Object)],exports.SetBlackboardValueAction.prototype,"value",void 0),a([n.Serialize(),d("design:type",String)],exports.SetBlackboardValueAction.prototype,"sourceVariable",void 0),a([n.Serialize(),d("design:type",Boolean)],exports.SetBlackboardValueAction.prototype,"force",void 0),exports.SetBlackboardValueAction=a([p({displayName:"设置变量",category:"动作",type:exports.NodeType.Action,icon:"Edit",description:"设置黑板变量的值",color:"#3F51B5"}),n.ECSComponent("SetBlackboardValueAction"),n.Serializable({version:1})],exports.SetBlackboardValueAction),exports.ModifyOperation=void 0,(m=exports.ModifyOperation||(exports.ModifyOperation={})).Add="add",m.Subtract="subtract",m.Multiply="multiply",m.Divide="divide",m.Modulo="modulo",m.Append="append",m.Remove="remove",exports.ModifyBlackboardValueAction=class extends n.Component{constructor(){super(...arguments),this.variableName="",this.operation=exports.ModifyOperation.Add,this.operand=0,this.force=!1}},a([l({label:"变量名",type:"variable",required:!0}),n.Serialize(),d("design:type",String)],exports.ModifyBlackboardValueAction.prototype,"variableName",void 0),a([l({label:"操作类型",type:"select",options:[{label:"加法",value:"add"},{label:"减法",value:"subtract"},{label:"乘法",value:"multiply"},{label:"除法",value:"divide"},{label:"取模",value:"modulo"},{label:"追加",value:"append"},{label:"移除",value:"remove"}]}),n.Serialize(),d("design:type",String)],exports.ModifyBlackboardValueAction.prototype,"operation",void 0),a([l({label:"操作数",type:"string",description:"可以是固定值或变量引用 {{varName}}"}),n.Serialize(),d("design:type",Object)],exports.ModifyBlackboardValueAction.prototype,"operand",void 0),a([n.Serialize(),d("design:type",Boolean)],exports.ModifyBlackboardValueAction.prototype,"force",void 0),exports.ModifyBlackboardValueAction=a([p({displayName:"修改变量",category:"动作",type:exports.NodeType.Action,icon:"Calculator",description:"对黑板变量执行数学或逻辑操作",color:"#FF9800"}),n.ECSComponent("ModifyBlackboardValueAction"),n.Serializable({version:1})],exports.ModifyBlackboardValueAction),exports.CompareOperator=void 0,(y=exports.CompareOperator||(exports.CompareOperator={})).Equal="equal",y.NotEqual="notEqual",y.Greater="greater",y.GreaterOrEqual="greaterOrEqual",y.Less="less",y.LessOrEqual="lessOrEqual",y.Contains="contains",y.Matches="matches",exports.BlackboardCompareCondition=class extends n.Component{constructor(){super(...arguments),this.variableName="",this.operator=exports.CompareOperator.Equal,this.compareValue=null,this.invertResult=!1}},a([l({label:"变量名",type:"variable",required:!0}),n.Serialize(),d("design:type",String)],exports.BlackboardCompareCondition.prototype,"variableName",void 0),a([l({label:"运算符",type:"select",options:[{label:"等于",value:"equal"},{label:"不等于",value:"notEqual"},{label:"大于",value:"greater"},{label:"大于等于",value:"greaterOrEqual"},{label:"小于",value:"less"},{label:"小于等于",value:"lessOrEqual"},{label:"包含",value:"contains"},{label:"正则匹配",value:"matches"}]}),n.Serialize(),d("design:type",String)],exports.BlackboardCompareCondition.prototype,"operator",void 0),a([l({label:"比较值",type:"string",description:"可以是固定值或变量引用 {{varName}}"}),n.Serialize(),d("design:type",Object)],exports.BlackboardCompareCondition.prototype,"compareValue",void 0),a([l({label:"反转结果",type:"boolean"}),n.Serialize(),d("design:type",Boolean)],exports.BlackboardCompareCondition.prototype,"invertResult",void 0),exports.BlackboardCompareCondition=a([p({displayName:"比较变量",category:"条件",type:exports.NodeType.Condition,icon:"Scale",description:"比较黑板变量与指定值",color:"#2196F3"}),n.ECSComponent("BlackboardCompareCondition"),n.Serializable({version:1})],exports.BlackboardCompareCondition),exports.BlackboardExistsCondition=class extends n.Component{constructor(){super(...arguments),this.variableName="",this.checkNotNull=!1,this.invertResult=!1}},a([l({label:"变量名",type:"variable",required:!0}),n.Serialize(),d("design:type",String)],exports.BlackboardExistsCondition.prototype,"variableName",void 0),a([l({label:"检查非空",type:"boolean",description:"检查值不为 null/undefined"}),n.Serialize(),d("design:type",Boolean)],exports.BlackboardExistsCondition.prototype,"checkNotNull",void 0),a([l({label:"反转结果",type:"boolean",description:"检查不存在"}),n.Serialize(),d("design:type",Boolean)],exports.BlackboardExistsCondition.prototype,"invertResult",void 0),exports.BlackboardExistsCondition=a([p({displayName:"检查变量存在",category:"条件",type:exports.NodeType.Condition,icon:"Search",description:"检查黑板变量是否存在",color:"#00BCD4"}),n.ECSComponent("BlackboardExistsCondition"),n.Serializable({version:1})],exports.BlackboardExistsCondition),exports.RandomProbabilityCondition=class extends n.Component{constructor(){super(...arguments),this.probability=.5,this.alwaysRandomize=!0}evaluate(){return(this.alwaysRandomize||void 0===this.cachedResult)&&(this.cachedResult=Math.random()<this.probability),this.cachedResult}reset(){this.cachedResult=void 0}},a([l({label:"成功概率",type:"number",min:0,max:1,step:.1,description:"0.0 - 1.0",required:!0}),n.Serialize(),d("design:type",Number)],exports.RandomProbabilityCondition.prototype,"probability",void 0),a([l({label:"总是重新随机",type:"boolean",description:"false则第一次随机后固定结果"}),n.Serialize(),d("design:type",Boolean)],exports.RandomProbabilityCondition.prototype,"alwaysRandomize",void 0),exports.RandomProbabilityCondition=a([p({displayName:"随机概率",category:"条件",type:exports.NodeType.Condition,icon:"Dice",description:"根据概率返回成功或失败",color:"#E91E63"}),n.ECSComponent("RandomProbabilityCondition"),n.Serializable({version:1})],exports.RandomProbabilityCondition),exports.ExecuteCondition=class extends n.Component{constructor(){super(...arguments),this.parameters={},this.invertResult=!1}getFunction(){if(!this.compiledFunction&&this.conditionCode)try{const e=new Function("entity","blackboard","deltaTime","parameters",`\n try {\n ${this.conditionCode}\n } catch (error) {\n return false;\n }\n `);this.compiledFunction=(t,o,s)=>Boolean(e(t,o,s,this.parameters))}catch(e){return}return this.compiledFunction}setFunction(e){this.compiledFunction=e}},a([l({label:"条件代码",type:"code",description:"JavaScript 代码,返回 boolean",required:!0}),n.Serialize(),d("design:type",String)],exports.ExecuteCondition.prototype,"conditionCode",void 0),a([n.Serialize(),d("design:type",Object)],exports.ExecuteCondition.prototype,"parameters",void 0),a([l({label:"反转结果",type:"boolean"}),n.Serialize(),d("design:type",Boolean)],exports.ExecuteCondition.prototype,"invertResult",void 0),a([n.IgnoreSerialization(),d("design:type",Function)],exports.ExecuteCondition.prototype,"compiledFunction",void 0),exports.ExecuteCondition=a([p({displayName:"自定义条件",category:"条件",type:exports.NodeType.Condition,icon:"Code",description:"执行自定义条件代码",color:"#9C27B0"}),n.ECSComponent("ExecuteCondition"),n.Serializable({version:1})],exports.ExecuteCondition),exports.CompositeNodeComponent=class extends n.Component{constructor(){super(...arguments),this.compositeType=exports.CompositeType.Sequence,this.shuffledIndices=[],this.reshuffleOnRestart=!0}getNextChildIndex(e,t){return this.compositeType===exports.CompositeType.RandomSequence||this.compositeType===exports.CompositeType.RandomSelector?((0===this.shuffledIndices.length||0===e&&this.reshuffleOnRestart)&&this.shuffleIndices(t),e<this.shuffledIndices.length?this.shuffledIndices[e]:t):e}shuffleIndices(e){this.shuffledIndices=Array.from({length:e},((e,t)=>t));for(let e=this.shuffledIndices.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));[this.shuffledIndices[e],this.shuffledIndices[t]]=[this.shuffledIndices[t],this.shuffledIndices[e]]}}resetShuffle(){this.shuffledIndices=[]}},a([n.Serialize(),d("design:type",String)],exports.CompositeNodeComponent.prototype,"compositeType",void 0),exports.CompositeNodeComponent=a([n.ECSComponent("CompositeNode"),n.Serializable({version:1})],exports.CompositeNodeComponent),exports.SequenceNode=class extends exports.CompositeNodeComponent{constructor(){super(),this.abortType=exports.AbortType.None,this.compositeType=exports.CompositeType.Sequence}},a([l({label:"中止类型",type:"select",description:"条件变化时的中止行为",options:[{label:"无",value:"none"},{label:"自身",value:"self"},{label:"低优先级",value:"lower-priority"},{label:"两者",value:"both"}]}),n.Serialize(),d("design:type",String)],exports.SequenceNode.prototype,"abortType",void 0),exports.SequenceNode=a([p({displayName:"序列",category:"组合",type:exports.NodeType.Composite,icon:"List",description:"按顺序执行子节点,全部成功才成功",color:"#4CAF50"}),n.ECSComponent("SequenceNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.SequenceNode),exports.SelectorNode=class extends exports.CompositeNodeComponent{constructor(){super(),this.abortType=exports.AbortType.None,this.compositeType=exports.CompositeType.Selector}},a([l({label:"中止类型",type:"select",description:"条件变化时的中止行为",options:[{label:"无",value:"none"},{label:"自身",value:"self"},{label:"低优先级",value:"lower-priority"},{label:"两者",value:"both"}]}),n.Serialize(),d("design:type",String)],exports.SelectorNode.prototype,"abortType",void 0),exports.SelectorNode=a([p({displayName:"选择",category:"组合",type:exports.NodeType.Composite,icon:"GitBranch",description:"按顺序执行子节点,任一成功则成功",color:"#8BC34A"}),n.ECSComponent("SelectorNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.SelectorNode),exports.ParallelNode=class extends exports.CompositeNodeComponent{constructor(){super(),this.successPolicy="all",this.failurePolicy="one",this.compositeType=exports.CompositeType.Parallel}},a([l({label:"成功策略",type:"select",description:"多少个子节点成功时整体成功",options:[{label:"全部成功",value:"all"},{label:"任意一个成功",value:"one"}]}),n.Serialize(),d("design:type",String)],exports.ParallelNode.prototype,"successPolicy",void 0),a([l({label:"失败策略",type:"select",description:"多少个子节点失败时整体失败",options:[{label:"任意一个失败",value:"one"},{label:"全部失败",value:"all"}]}),n.Serialize(),d("design:type",String)],exports.ParallelNode.prototype,"failurePolicy",void 0),exports.ParallelNode=a([p({displayName:"并行",category:"组合",type:exports.NodeType.Composite,icon:"Layers",description:"同时执行所有子节点",color:"#CDDC39"}),n.ECSComponent("ParallelNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.ParallelNode),exports.ParallelSelectorNode=class extends exports.CompositeNodeComponent{constructor(){super(),this.failurePolicy="all",this.compositeType=exports.CompositeType.ParallelSelector}},a([l({label:"失败策略",type:"select",description:"多少个子节点失败时整体失败",options:[{label:"任意一个失败",value:"one"},{label:"全部失败",value:"all"}]}),n.Serialize(),d("design:type",String)],exports.ParallelSelectorNode.prototype,"failurePolicy",void 0),exports.ParallelSelectorNode=a([p({displayName:"并行选择",category:"组合",type:exports.NodeType.Composite,icon:"Sparkles",description:"并行执行子节点,任一成功则成功",color:"#FFC107"}),n.ECSComponent("ParallelSelectorNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.ParallelSelectorNode),exports.RandomSequenceNode=class extends exports.CompositeNodeComponent{constructor(){super(),this.reshuffleOnRestart=!0,this.compositeType=exports.CompositeType.RandomSequence}},a([l({label:"重启时重新洗牌",type:"boolean",description:"每次重启时是否重新随机子节点顺序"}),n.Serialize(),d("design:type",Boolean)],exports.RandomSequenceNode.prototype,"reshuffleOnRestart",void 0),exports.RandomSequenceNode=a([p({displayName:"随机序列",category:"组合",type:exports.NodeType.Composite,icon:"Shuffle",description:"随机顺序执行子节点序列",color:"#FF5722"}),n.ECSComponent("RandomSequenceNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.RandomSequenceNode),exports.RandomSelectorNode=class extends exports.CompositeNodeComponent{constructor(){super(),this.reshuffleOnRestart=!0,this.compositeType=exports.CompositeType.RandomSelector}},a([l({label:"重启时重新洗牌",type:"boolean",description:"每次重启时是否重新随机子节点顺序"}),n.Serialize(),d("design:type",Boolean)],exports.RandomSelectorNode.prototype,"reshuffleOnRestart",void 0),exports.RandomSelectorNode=a([p({displayName:"随机选择",category:"组合",type:exports.NodeType.Composite,icon:"Dices",description:"随机顺序执行子节点选择",color:"#F44336"}),n.ECSComponent("RandomSelectorNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.RandomSelectorNode),exports.SubTreeNode=class extends exports.CompositeNodeComponent{constructor(){super(...arguments),this.assetId="",this.inheritParentBlackboard=!0,this.propagateFailure=!0,this.preload=!0,this.subTreeCompleted=!1,this.subTreeResult=exports.TaskStatus.Invalid}getSubTreeRoot(){return this.subTreeRoot}setSubTreeRoot(e){this.subTreeRoot=e,this.subTreeCompleted=!1,this.subTreeResult=exports.TaskStatus.Invalid}markSubTreeCompleted(e){this.subTreeCompleted=!0,this.subTreeResult=e}isSubTreeCompleted(){return this.subTreeCompleted}getSubTreeResult(){return this.subTreeResult}reset(){this.subTreeRoot=void 0,this.subTreeCompleted=!1,this.subTreeResult=exports.TaskStatus.Invalid}resetCompletionState(){this.subTreeCompleted=!1,this.subTreeResult=exports.TaskStatus.Invalid}validate(){const e=[];return this.assetId&&""!==this.assetId.trim()||e.push("SubTree 节点必须指定资产ID"),e}},a([l({label:"资产ID",type:"asset",description:"要引用的行为树资产ID"}),n.Serialize(),d("design:type",String)],exports.SubTreeNode.prototype,"assetId",void 0),a([l({label:"继承父黑板",type:"boolean",description:"子树是否可以访问父树的黑板变量"}),n.Serialize(),d("design:type",Boolean)],exports.SubTreeNode.prototype,"inheritParentBlackboard",void 0),a([l({label:"传播失败",type:"boolean",description:"子树失败时是否传播失败状态"}),n.Serialize(),d("design:type",Boolean)],exports.SubTreeNode.prototype,"propagateFailure",void 0),a([l({label:"预加载",type:"boolean",description:"在行为树启动时预加载子树,避免运行时加载延迟"}),n.Serialize(),d("design:type",Boolean)],exports.SubTreeNode.prototype,"preload",void 0),exports.SubTreeNode=a([p({displayName:"子树",category:"组合",type:exports.NodeType.Composite,icon:"GitBranch",description:"引用并执行外部行为树文件(不支持静态子节点)",color:"#FF9800",requiresChildren:!1}),n.ECSComponent("SubTreeNode"),n.Serializable({version:1})],exports.SubTreeNode),exports.DecoratorNodeComponent=class extends n.Component{constructor(){super(...arguments),this.decoratorType=exports.DecoratorType.Inverter}},a([n.Serialize(),d("design:type",String)],exports.DecoratorNodeComponent.prototype,"decoratorType",void 0),exports.DecoratorNodeComponent=a([n.ECSComponent("DecoratorNode"),n.Serializable({version:1})],exports.DecoratorNodeComponent),exports.InverterNode=class extends exports.DecoratorNodeComponent{constructor(){super(),this.decoratorType=exports.DecoratorType.Inverter}},exports.InverterNode=a([p({displayName:"反转",category:"装饰器",type:exports.NodeType.Decorator,icon:"RotateCcw",description:"反转子节点的执行结果",color:"#607D8B"}),n.ECSComponent("InverterNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.InverterNode),exports.RepeaterNode=class extends exports.DecoratorNodeComponent{constructor(){super(),this.repeatCount=1,this.endOnFailure=!1,this.currentRepeatCount=0,this.decoratorType=exports.DecoratorType.Repeater}incrementRepeat(){this.currentRepeatCount++}shouldContinueRepeat(){return-1===this.repeatCount||this.currentRepeatCount<this.repeatCount}reset(){this.currentRepeatCount=0}},a([l({label:"重复次数",type:"number",min:-1,step:1,description:"-1表示无限重复",required:!0}),n.Serialize(),d("design:type",Number)],exports.RepeaterNode.prototype,"repeatCount",void 0),a([l({label:"失败时停止",type:"boolean",description:"子节点失败时是否停止重复"}),n.Serialize(),d("design:type",Boolean)],exports.RepeaterNode.prototype,"endOnFailure",void 0),a([n.IgnoreSerialization(),d("design:type",Number)],exports.RepeaterNode.prototype,"currentRepeatCount",void 0),exports.RepeaterNode=a([p({displayName:"重复",category:"装饰器",type:exports.NodeType.Decorator,icon:"Repeat",description:"重复执行子节点指定次数",color:"#9E9E9E"}),n.ECSComponent("RepeaterNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.RepeaterNode),exports.UntilSuccessNode=class extends exports.DecoratorNodeComponent{constructor(){super(),this.decoratorType=exports.DecoratorType.UntilSuccess}},exports.UntilSuccessNode=a([p({displayName:"直到成功",category:"装饰器",type:exports.NodeType.Decorator,icon:"CheckCircle",description:"重复执行子节点直到成功",color:"#4CAF50"}),n.ECSComponent("UntilSuccessNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.UntilSuccessNode),exports.UntilFailNode=class extends exports.DecoratorNodeComponent{constructor(){super(),this.decoratorType=exports.DecoratorType.UntilFail}},exports.UntilFailNode=a([p({displayName:"直到失败",category:"装饰器",type:exports.NodeType.Decorator,icon:"XCircle",description:"重复执行子节点直到失败",color:"#F44336"}),n.ECSComponent("UntilFailNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.UntilFailNode),exports.AlwaysSucceedNode=class extends exports.DecoratorNodeComponent{constructor(){super(),this.decoratorType=exports.DecoratorType.AlwaysSucceed}},exports.AlwaysSucceedNode=a([p({displayName:"总是成功",category:"装饰器",type:exports.NodeType.Decorator,icon:"ThumbsUp",description:"无论子节点结果如何都返回成功",color:"#8BC34A"}),n.ECSComponent("AlwaysSucceedNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.AlwaysSucceedNode),exports.AlwaysFailNode=class extends exports.DecoratorNodeComponent{constructor(){super(),this.decoratorType=exports.DecoratorType.AlwaysFail}},exports.AlwaysFailNode=a([p({displayName:"总是失败",category:"装饰器",type:exports.NodeType.Decorator,icon:"ThumbsDown",description:"无论子节点结果如何都返回失败",color:"#FF5722"}),n.ECSComponent("AlwaysFailNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.AlwaysFailNode),exports.ConditionalNode=class extends exports.DecoratorNodeComponent{constructor(){super(),this.shouldReevaluate=!0,this.decoratorType=exports.DecoratorType.Conditional}evaluateCondition(e,t){if(!this.conditionCode)return!1;if(!this.compiledCondition)try{const e=new Function("entity","blackboard",`\n try {\n return Boolean(${this.conditionCode});\n } catch (error) {\n return false;\n }\n `);this.compiledCondition=(t,o)=>Boolean(e(t,o))}catch(e){return!1}return this.compiledCondition(e,t)}setConditionFunction(e){this.compiledCondition=e}},a([l({label:"条件代码",type:"code",description:"JavaScript 代码,返回 boolean",required:!0}),n.Serialize(),d("design:type",String)],exports.ConditionalNode.prototype,"conditionCode",void 0),a([l({label:"重新评估条件",type:"boolean",description:"每次执行时是否重新评估条件"}),n.Serialize(),d("design:type",Boolean)],exports.ConditionalNode.prototype,"shouldReevaluate",void 0),a([n.IgnoreSerialization(),d("design:type",Function)],exports.ConditionalNode.prototype,"compiledCondition",void 0),exports.ConditionalNode=a([p({displayName:"条件装饰器",category:"装饰器",type:exports.NodeType.Decorator,icon:"Filter",description:"基于条件判断是否执行子节点",color:"#3F51B5"}),n.ECSComponent("ConditionalNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.ConditionalNode),exports.CooldownNode=class extends exports.DecoratorNodeComponent{constructor(){super(),this.cooldownTime=1,this.lastExecutionTime=0,this.decoratorType=exports.DecoratorType.Cooldown}canExecute(e){return 0===this.lastExecutionTime||e-this.lastExecutionTime>=this.cooldownTime}recordExecution(e){this.lastExecutionTime=e}reset(){this.lastExecutionTime=0}},a([l({label:"冷却时间",type:"number",min:0,step:.1,description:"冷却时间(秒)",required:!0}),n.Serialize(),d("design:type",Number)],exports.CooldownNode.prototype,"cooldownTime",void 0),a([n.IgnoreSerialization(),d("design:type",Number)],exports.CooldownNode.prototype,"lastExecutionTime",void 0),exports.CooldownNode=a([p({displayName:"冷却",category:"装饰器",type:exports.NodeType.Decorator,icon:"Timer",description:"在冷却时间内阻止子节点执行",color:"#00BCD4"}),n.ECSComponent("CooldownNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.CooldownNode),exports.TimeoutNode=class extends exports.DecoratorNodeComponent{constructor(){super(),this.timeoutDuration=5,this.startTime=0,this.decoratorType=exports.DecoratorType.Timeout}recordStartTime(e){0===this.startTime&&(this.startTime=e)}isTimeout(e){return 0!==this.startTime&&e-this.startTime>=this.timeoutDuration}reset(){this.startTime=0}},a([l({label:"超时时间",type:"number",min:0,step:.1,description:"超时时间(秒)",required:!0}),n.Serialize(),d("design:type",Number)],exports.TimeoutNode.prototype,"timeoutDuration",void 0),a([n.IgnoreSerialization(),d("design:type",Number)],exports.TimeoutNode.prototype,"startTime",void 0),exports.TimeoutNode=a([p({displayName:"超时",category:"装饰器",type:exports.NodeType.Decorator,icon:"Clock",description:"子节点执行超时则返回失败",color:"#FF9800"}),n.ECSComponent("TimeoutNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.TimeoutNode),exports.BehaviorTreeNode=class extends n.Component{constructor(){super(...arguments),this.nodeType=exports.NodeType.Action,this.nodeName="Node",this.status=exports.TaskStatus.Invalid,this.currentChildIndex=0}reset(){this.status=exports.TaskStatus.Invalid,this.currentChildIndex=0}invalidate(){this.reset()}},a([n.Serialize(),d("design:type",String)],exports.BehaviorTreeNode.prototype,"nodeType",void 0),a([n.Serialize(),d("design:type",String)],exports.BehaviorTreeNode.prototype,"nodeName",void 0),a([n.IgnoreSerialization(),d("design:type",Number)],exports.BehaviorTreeNode.prototype,"status",void 0),a([n.IgnoreSerialization(),d("design:type",Number)],exports.BehaviorTreeNode.prototype,"currentChildIndex",void 0),exports.BehaviorTreeNode=a([n.ECSComponent("BehaviorTreeNode"),n.Serializable({version:1})],exports.BehaviorTreeNode);class x{constructor(){this.variables=new Map}dispose(){this.variables.clear()}defineVariable(e,t,o,s){this.variables.set(e,{name:e,type:t,value:o,readonly:s?.readonly??!1,description:s?.description})}getValue(e){const t=this.variables.get(e);return t?.value}setValue(e,t,o=!1){const s=this.variables.get(e);return!!s&&(!(s.readonly&&!o)&&(s.value=t,!0))}hasVariable(e){return this.variables.has(e)}removeVariable(e){return this.variables.delete(e)}getVariableNames(){return Array.from(this.variables.keys())}getAllVariables(){return Array.from(this.variables.values())}clear(){this.variables.clear()}setVariables(e){for(const[t,o]of Object.entries(e)){const e=this.variables.get(t);e&&!e.readonly&&(e.value=o)}}getVariables(e){const t={};for(const o of e){const e=this.getValue(o);void 0!==e&&(t[o]=e)}return t}exportConfig(){return{version:"1.0",variables:Array.from(this.variables.values())}}importConfig(e){this.variables.clear();for(const t of e.variables)this.variables.set(t.name,t)}toJSON(){return JSON.stringify(this.exportConfig(),null,2)}static fromJSON(e){return JSON.parse(e)}}exports.BlackboardComponent=class extends n.Component{constructor(){super(...arguments),this.variables=new Map,this.useGlobalBlackboard=!0}defineVariable(e,t,o,s){this.variables.set(e,{name:e,type:t,value:o,readonly:s?.readonly??!1,description:s?.description})}getValue(e){const t=this.variables.get(e);return void 0!==t?t.value:this.useGlobalBlackboard?n.Core.services.resolve(x).getValue(e):void 0}getLocalValue(e){const t=this.variables.get(e);return t?.value}setValue(e,t,o=!1){const s=this.variables.get(e);return s?!(s.readonly&&!o)&&(s.value=t,!0):!!this.useGlobalBlackboard&&n.Core.services.resolve(x).setValue(e,t,o)}setLocalValue(e,t,o=!1){const s=this.variables.get(e);return!!s&&(!(s.readonly&&!o)&&(s.value=t,!0))}hasVariable(e){return!!this.variables.has(e)||!!this.useGlobalBlackboard&&n.Core.services.resolve(x).hasVariable(e)}hasLocalVariable(e){return this.variables.has(e)}removeVariable(e){return this.variables.delete(e)}getVariableNames(){return Array.from(this.variables.keys())}clear(){this.variables.clear()}setUseGlobalBlackboard(e){this.useGlobalBlackboard=e}isUsingGlobalBlackboard(){return this.useGlobalBlackboard}getAllVariables(){const e=Array.from(this.variables.values());if(this.useGlobalBlackboard){const t=n.Core.services.resolve(x).getAllVariables(),o=new Set(this.variables.keys()),s=t.filter((e=>!o.has(e.name)));return[...e,...s]}return e}static getGlobalBlackboard(){return n.Core.services.resolve(x)}},a([n.Serialize(),d("design:type",Map)],exports.BlackboardComponent.prototype,"variables",void 0),exports.BlackboardComponent=a([n.ECSComponent("Blackboard"),n.Serializable({version:1})],exports.BlackboardComponent),exports.ActiveNode=class extends n.Component{},exports.ActiveNode=a([n.ECSComponent("ActiveNode")],exports.ActiveNode);class g extends n.Component{constructor(){super(...arguments),this.bindings=new Map}addBinding(e,t){this.bindings.set(e,t)}getBinding(e){return this.bindings.get(e)}hasBinding(e){return this.bindings.has(e)}clearBindings(){this.bindings.clear()}}exports.LogOutput=class extends n.Component{constructor(){super(...arguments),this.messages=[]}addMessage(e,t="log"){this.messages.push({timestamp:Date.now(),message:e,level:t})}clear(){this.messages=[]}},exports.LogOutput=a([n.ECSComponent("LogOutput")],exports.LogOutput),exports.BehaviorTreeAssetMetadata=class extends n.Component{constructor(){super(...arguments),this.assetId="",this.assetVersion="",this.assetName="",this.loadedAt=0,this.description=""}initialize(e,t,o){this.assetId=e,this.assetVersion=t,this.assetName=o||e,this.loadedAt=Date.now()}},a([n.Serialize(),d("design:type",String)],exports.BehaviorTreeAssetMetadata.prototype,"assetId",void 0),a([n.Serialize(),d("design:type",String)],exports.BehaviorTreeAssetMetadata.prototype,"assetVersion",void 0),a([n.Serialize(),d("design:type",String)],exports.BehaviorTreeAssetMetadata.prototype,"assetName",void 0),a([n.Serialize(),d("design:type",Number)],exports.BehaviorTreeAssetMetadata.prototype,"loadedAt",void 0),a([n.Serialize(),d("design:type",String)],exports.BehaviorTreeAssetMetadata.prototype,"description",void 0),exports.BehaviorTreeAssetMetadata=a([n.ECSComponent("BehaviorTreeAssetMetadata"),n.Serializable({version:1})],exports.BehaviorTreeAssetMetadata),exports.RootNode=class extends exports.CompositeNodeComponent{constructor(){super(),this.compositeType=exports.CompositeType.Sequence}},exports.RootNode=a([p({displayName:"根节点",category:"根节点",type:exports.NodeType.Composite,icon:"TreePine",description:"行为树的根节点",color:"#FFD700"}),n.ECSComponent("RootNode"),n.Serializable({version:1}),d("design:paramtypes",[])],exports.RootNode);const f=new TextEncoder;function b(e,t,o){e.length>50?function(e,t,o){f.encodeInto(e,t.subarray(o))}(e,t,o):function(e,t,o){const s=e.length;let r=o,i=0;for(;i<s;){let o=e.charCodeAt(i++);if(4294967168&o){if(4294965248&o){if(o>=55296&&o<=56319&&i<s){const t=e.charCodeAt(i);56320==(64512&t)&&(++i,o=((1023&o)<<10)+(1023&t)+65536)}4294901760&o?(t[r++]=o>>18&7|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128):(t[r++]=o>>12&15|224,t[r++]=o>>6&63|128)}else t[r++]=o>>6&31|192;t[r++]=63&o|128}else t[r++]=o}}(e,t,o)}function C(e,t,o){let s=t;const r=s+o,i=[];let n="";for(;s<r;){const t=e[s++];if(128&t)if(192==(224&t)){const o=63&e[s++];i.push((31&t)<<6|o)}else if(224==(240&t)){const o=63&e[s++],r=63&e[s++];i.push((31&t)<<12|o<<6|r)}else if(240==(248&t)){let o=(7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++];o>65535&&(o-=65536,i.push(o>>>10&1023|55296),o=56320|1023&o),i.push(o)}else i.push(t);else i.push(t);i.length>=4096&&(n+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(n+=String.fromCharCode(...i)),n}const T=new TextDecoder;function S(e,t,o){return o>200?function(e,t,o){const s=e.subarray(t,t+o);return T.decode(s)}(e,t,o):C(e,t,o)}class v{constructor(e,t){this.type=e,this.data=t}}class N extends Error{constructor(e){super(e);const t=Object.create(N.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:N.name})}}const w=4294967295;function k(e,t,o){const s=Math.floor(o/4294967296),r=o;e.setUint32(t,s),e.setUint32(t+4,r)}function B(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}const A={type:-1,encode:function(e){if(e instanceof Date){return function({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=17179869183){if(0===t&&e<=4294967295){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}{const o=e/4294967296,s=4294967295&e,r=new Uint8Array(8),i=new DataView(r.buffer);return i.setUint32(0,t<<2|3&o),i.setUint32(4,s),r}}{const o=new Uint8Array(12),s=new DataView(o.buffer);return s.setUint32(0,t),k(s,4,e),o}}(function(e){const t=e.getTime(),o=Math.floor(t/1e3),s=1e6*(t-1e3*o),r=Math.floor(s/1e9);return{sec:o+r,nsec:s-1e9*r}}(e))}return null},decode:function(e){const t=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{const e=t.getUint32(0);return{sec:4294967296*(3&e)+t.getUint32(4),nsec:e>>>2}}case 12:return{sec:B(t,4),nsec:t.getUint32(0)};default:throw new N(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}};class E{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(A)}register({type:e,encode:t,decode:o}){if(e>=0)this.encoders[e]=t,this.decoders[e]=o;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=o}}tryToEncode(e,t){for(let o=0;o<this.builtInEncoders.length;o++){const s=this.builtInEncoders[o];if(null!=s){const r=s(e,t);if(null!=r){return new v(-1-o,r)}}}for(let o=0;o<this.encoders.length;o++){const s=this.encoders[o];if(null!=s){const r=s(e,t);if(null!=r){return new v(o,r)}}}return e instanceof v?e:null}decode(e,t,o){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,o):new v(t,e)}}function R(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):function(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}(e)?new Uint8Array(e):Uint8Array.from(e)}E.defaultCodec=new E;class I{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??E.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??100,this.initialBufferSize=e?.initialBufferSize??2048,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new I({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered){return this.clone().encodeSharedRef(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered){return this.clone().encode(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.useBigInt64&&"bigint"==typeof e?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)}resizeBuffer(e){const t=new ArrayBuffer(e),o=new Uint8Array(t),s=new DataView(t);o.set(this.bytes),this.view=s,this.bytes=o}encodeNil(){this.writeU8(192)}encodeBoolean(e){!1===e?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too long string: ${e} bytes in UTF-8`);this.writeU8(219),this.writeU32(e)}}encodeString(e){const t=function(e){const t=e.length;let o=0,s=0;for(;s<t;){let r=e.charCodeAt(s++);if(4294967168&r)if(4294965248&r){if(r>=55296&&r<=56319&&s<t){const t=e.charCodeAt(s);56320==(64512&t)&&(++s,r=((1023&r)<<10)+(1023&t)+65536)}o+=4294901760&r?4:3}else o+=2;else o++}return o}(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),b(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const o=this.extensionCodec.tryToEncode(e,this.context);if(null!=o)this.encodeExtension(o);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);this.encodeMap(e,t)}}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large binary: ${t}`);this.writeU8(198),this.writeU32(t)}const o=R(e);this.writeU8a(o)}encodeArray(e,t){const o=e.length;if(o<16)this.writeU8(144+o);else if(o<65536)this.writeU8(220),this.writeU16(o);else{if(!(o<4294967296))throw new Error(`Too large array: ${o}`);this.writeU8(221),this.writeU32(o)}for(const o of e)this.doEncode(o,t+1)}countWithoutUndefined(e,t){let o=0;for(const s of t)void 0!==e[s]&&o++;return o}encodeMap(e,t){const o=Object.keys(e);this.sortKeys&&o.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,o):o.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else{if(!(s<4294967296))throw new Error(`Too large map object: ${s}`);this.writeU8(223),this.writeU32(s)}for(const s of o){const o=e[s];this.ignoreUndefined&&void 0===o||(this.encodeString(s),this.doEncode(o,t+1))}}encodeExtension(e){if("function"==typeof e.data){const t=e.data(this.pos+6),o=t.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);return this.writeU8(201),this.writeU32(o),this.writeI8(e.type),void this.writeU8a(t)}const t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),function(e,t,o){const s=o/4294967296,r=o;e.setUint32(t,s),e.setUint32(t+4,r)}(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),k(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function L(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}const F="array",$="map_key",U="map_value",z=e=>{if("string"==typeof e||"number"==typeof e)return e;throw new N("The type of key must be string or number but "+typeof e)};class P{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=F,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=$,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===F){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===$||e.type===U){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const M=new DataView(new ArrayBuffer(0)),D=new Uint8Array(M.buffer);try{M.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const V=new RangeError("Insufficient data"),O=new class{constructor(e=16,t=16){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,o){const s=this.caches[o-1];e:for(const r of s){const s=r.bytes;for(let r=0;r<o;r++)if(s[r]!==e[t+r])continue e;return r.str}return null}store(e,t){const o=this.caches[e.length-1],s={bytes:e,str:t};o.length>=this.maxLengthPerKey?o[Math.random()*o.length|0]=s:o.push(s)}decode(e,t,o){const s=this.find(e,t,o);if(null!=s)return this.hit++,s;this.miss++;const r=C(e,t,o),i=Uint8Array.prototype.slice.call(e,t,t+o);return this.store(i,r),r}};class q{constructor(e){this.totalPos=0,this.pos=0,this.view=M,this.bytes=D,this.headByte=-1,this.stack=new P,this.entered=!1,this.extensionCodec=e?.extensionCodec??E.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??w,this.maxBinLength=e?.maxBinLength??w,this.maxArrayLength=e?.maxArrayLength??w,this.maxMapLength=e?.maxMapLength??w,this.maxExtLength=e?.maxExtLength??w,this.keyDecoder=void 0!==e?.keyDecoder?e.keyDecoder:O,this.mapKeyConverter=e?.mapKeyConverter??z}clone(){return new q({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(e){const t=R(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(-1!==this.headByte||this.hasRemaining(1)){const t=this.bytes.subarray(this.pos),o=R(e),s=new Uint8Array(t.length+o.length);s.set(t),s.set(o,t.length),this.setBuffer(s)}else this.setBuffer(e)}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:o}=this;return new RangeError(`Extra ${t.byteLength-o} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered){return this.clone().decode(e)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){const t=this.clone();yield*t.decodeMulti(e)}else try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered){return this.clone().decodeAsync(e)}try{this.entered=!0;let t,o=!1;for await(const s of e){if(o)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(s);try{t=this.doDecodeSync(),o=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(o){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return t}const{headByte:s,pos:r,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${L(s)} at ${i} (${r} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){const o=this.clone();yield*o.decodeMultiAsync(e,t)}else try{this.entered=!0;let o=t,s=-1;for await(const r of e){if(t&&0===s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(r),o&&(s=this.readArraySize(),o=!1,this.complete());try{for(;yield this.doDecodeSync(),0!==--s;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const o=e-128;if(0!==o){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){const o=e-144;if(0!==o){this.pushArrayState(o),this.complete();continue e}t=[]}else{const o=e-160;t=this.decodeString(o,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===e){const e=this.lookU8();t=this.decodeString(e,1)}else if(218===e){const e=this.lookU16();t=this.decodeString(e,2)}else if(219===e){const e=this.lookU32();t=this.decodeString(e,4)}else if(220===e){const e=this.readU16();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(221===e){const e=this.readU32();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(222===e){const e=this.readU16();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(223===e){const e=this.readU32();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(196===e){const e=this.lookU8();t=this.decodeBinary(e,1)}else if(197===e){const e=this.lookU16();t=this.decodeBinary(e,2)}else if(198===e){const e=this.lookU32();t=this.decodeBinary(e,4)}else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e){const e=this.lookU8();t=this.decodeExtension(e,1)}else if(200===e){const e=this.lookU16();t=this.decodeExtension(e,2)}else{if(201!==e)throw new N(`Unrecognized type byte: ${L(e)}`);{const e=this.lookU32();t=this.decodeExtension(e,4)}}this.complete();const o=this.stack;for(;o.length>0;){const e=o.top();if(e.type===F){if(e.array[e.position]=t,e.position++,e.position!==e.size)continue e;t=e.array,o.release(e)}else{if(e.type===$){if("__proto__"===t)throw new N("The key __proto__ is not allowed");e.key=this.mapKeyConverter(t),e.type=U;continue e}if(e.map[e.key]=t,e.readCount++,e.readCount!==e.size){e.key=null,e.type=$;continue e}t=e.map,o.release(e)}}return t}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new N(`Unrecognized array type byte: ${L(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new N(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new N(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new N(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw V;const o=this.pos+t;let s;return s=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,o,e):S(this.bytes,o,e),this.pos+=t+e,s}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===$}return!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new N(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw V;const o=this.pos+t,s=this.bytes.subarray(o,o+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new N(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const o=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,o,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=(t=this.view,o=this.pos,4294967296*t.getUint32(o)+t.getUint32(o+4));var t,o;return this.pos+=8,e}readI64(){const e=B(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function j(e,t){return new q(t).decode(e)}class W{static validate(e){const t=[],o=[];if(e.version||t.push("Missing version field"),e.metadata&&e.metadata.name||t.push("Missing or invalid metadata"),e.rootNodeId||t.push("Missing rootNodeId"),e.nodes&&Array.isArray(e.nodes)){const s=new Set;e.nodes.find((t=>t.id===e.rootNodeId))||t.push(`Root node '${e.rootNodeId}' not found in nodes array`);for(const o of e.nodes)if(o.id){if(s.has(o.id)&&t.push(`Duplicate node id: ${o.id}`),s.add(o.id),o.nodeType||t.push(`Node ${o.id} missing nodeType`),o.children)for(const s of o.children)e.nodes.find((e=>e.id===s))||t.push(`Node ${o.id} references non-existent child: ${s}`)}else t.push("Node missing id field");const r=new Set([e.rootNodeId]),i=t=>{const o=e.nodes.find((e=>e.id===t));if(o&&o.children)for(const e of o.children)r.add(e),i(e)};i(e.rootNodeId);for(const t of e.nodes)r.has(t.id)||o.push(`Orphaned node detected: ${t.id} (${t.name})`)}else t.push("Missing or invalid nodes array");if(e.blackboard&&Array.isArray(e.blackboard)){const o=new Set;for(const s of e.blackboard)s.name?(o.has(s.name)&&t.push(`Duplicate blackboard variable: ${s.name}`),o.add(s.name),s.type||t.push(`Blackboard variable ${s.name} missing type`)):t.push("Blackboard variable missing name")}if(e.propertyBindings&&Array.isArray(e.propertyBindings)){const o=new Set(e.nodes.map((e=>e.id))),s=new Set(e.blackboard?.map((e=>e.name))||[]);for(const r of e.propertyBindings)o.has(r.nodeId)||t.push(`Property binding references non-existent node: ${r.nodeId}`),s.has(r.variableName)||t.push(`Property binding references non-existent variable: ${r.variableName}`),r.propertyName||t.push("Property binding missing propertyName")}return{valid:0===t.length,errors:t.length>0?t:void 0,warnings:o.length>0?o:void 0}}static getStats(e){let t=0,o=0,s=0,r=0;for(const i of e.nodes)switch(i.nodeType){case exports.NodeType.Action:t++;break;case exports.NodeType.Condition:o++;break;case exports.NodeType.Composite:s++;break;case exports.NodeType.Decorator:r++}const i=(t,o=0)=>{const s=e.nodes.find((e=>e.id===t));if(!s||!s.children||0===s.children.length)return o;let r=o;for(const e of s.children){const t=i(e,o+1);r=Math.max(r,t)}return r};return{nodeCount:e.nodes.length,actionCount:t,conditionCount:o,compositeCount:s,decoratorCount:r,blackboardVariableCount:e.blackboard?.length||0,propertyBindingCount:e.propertyBindings?.length||0,maxDepth:i(e.rootNodeId)}}}const J=n.createLogger("EditorFormatConverter");class G{static toAsset(e,t){J.info("开始转换编辑器格式到资产格式");const o=this.findRootNode(e.nodes);if(!o)throw new Error("未找到根节点");const s={name:t?.name||e.metadata?.name||"Untitled Behavior Tree",description:t?.description||e.metadata?.description,version:t?.version||e.version||"1.0.0",createdAt:t?.createdAt||e.metadata?.createdAt,modifiedAt:t?.modifiedAt||(new Date).toISOString()},r=this.convertNodes(e.nodes),i=this.convertBlackboard(e.blackboard),n=this.convertPropertyBindings(e.connections,e.nodes,i),a={version:"1.0.0",metadata:s,rootNodeId:o.id,nodes:r,blackboard:i,propertyBindings:n.length>0?n:void 0};return J.info(`转换完成: ${r.length}个节点, ${i.length}个黑板变量, ${n.length}个属性绑定`),a}static findRootNode(e){return e.find((e=>"根节点"===e.template.category||"root"===e.data.nodeType))||null}static convertNodes(e){return e.map((e=>this.convertNode(e)))}static convertNode(e){const t={...e.data};return delete t.nodeType,{id:e.id,name:e.template.displayName||e.data.name||"Node",nodeType:e.template.type,data:t,children:e.children||[]}}static convertBlackboard(e){const t=[];for(const[o,s]of Object.entries(e)){const e=this.inferBlackboardType(s);t.push({name:o,type:e,defaultValue:s})}return t}static inferBlackboardType(e){return"number"==typeof e?exports.BlackboardValueType.Number:"string"==typeof e?exports.BlackboardValueType.String:"boolean"==typeof e?exports.BlackboardValueType.Boolean:exports.BlackboardValueType.Object}static convertPropertyBindings(e,t,o){const s=[],r=new Set(o.map((e=>e.name))),i=e.filter((e=>"property"===e.connectionType));for(const e of i){const o=t.find((t=>t.id===e.from)),i=t.find((t=>t.id===e.to));if(!o||!i||!e.toProperty){J.warn(`跳过无效的属性连接: from=${e.from}, to=${e.to}`);continue}let n;"blackboard-variable"===o.data.nodeType?n=o.data.variableName:e.fromProperty&&(n=e.fromProperty),n?r.has(n)?s.push({nodeId:i.id,propertyName:e.toProperty,variableName:n}):J.warn(`属性绑定引用了不存在的黑板变量: ${n}`):J.warn(`无法确定变量名: from节点=${o.template.displayName}`)}return s}static fromAsset(e){J.info("开始转换资产格式到编辑器格式");const t=this.convertNodesFromAsset(e.nodes),o={};for(const t of e.blackboard)o[t.name]=t.defaultValue;const s=this.convertPropertyBindingsToConnections(e.propertyBindings||[],e.nodes),r=this.buildNodeConnections(e.nodes);s.push(...r);const i={version:e.metadata.version,metadata:{name:e.metadata.name,description:e.metadata.description,createdAt:e.metadata.createdAt,modifiedAt:e.metadata.modifiedAt},nodes:t,connections:s,blackboard:o,canvasState:{offset:{x:0,y:0},scale:1}};return J.info(`转换完成: ${t.length}个节点, ${s.length}个连接`),i}static convertNodesFromAsset(e){return e.map(((e,t)=>{const o={x:100+t%5*250,y:100+150*Math.floor(t/5)};return{id:e.id,template:{displayName:e.name,category:this.inferCategory(e.nodeType),type:e.nodeType},data:{...e.data},position:o,children:e.children}}))}static inferCategory(e){switch(e){case exports.NodeType.Action:return"动作";case exports.NodeType.Condition:return"条件";case exports.NodeType.Composite:return"组合";case exports.NodeType.Decorator:return"装饰器";default:return"其他"}}static convertPropertyBindingsToConnections(e,t){const o=[];for(const t of e)o.push({from:"blackboard",to:t.nodeId,toProperty:t.propertyName,connectionType:"property"});return o}static buildNodeConnections(e){const t=[];for(const o of e)for(const e of o.children)t.push({from:o.id,to:e,connectionType:"node"});return t}}const H=n.createLogger("BehaviorTreeAssetSerializer");class _{static serialize(e,t={format:"json",pretty:!0}){if(!1!==t.validate){const t=W.validate(e);if(!t.valid){const e=t.errors?.join(", ")||"Unknown error";throw new Error(`资产验证失败: ${e}`)}t.warnings&&t.warnings.length>0&&H.warn(`资产验证警告: ${t.warnings.join(", ")}`)}return"json"===t.format?this.serializeToJSON(e,t.pretty):this.serializeToBinary(e)}static serializeToJSON(e,t=!0){try{const o=t?JSON.stringify(e,null,2):JSON.stringify(e);return H.info(`已序列化为JSON: ${o.length} 字符`),o}catch(e){throw new Error(`JSON序列化失败: ${e}`)}}static serializeToBinary(e){try{const s=(t=e,new I(o).encodeSharedRef(t));return H.info(`已序列化为二进制: ${s.length} 字节`),s}catch(e){throw new Error(`二进制序列化失败: ${e}`)}var t,o}static deserialize(e,t={validate:!0,strict:!0}){let o;try{o="string"==typeof e?this.deserializeFromJSON(e):this.deserializeFromBinary(e)}catch(e){throw new Error(`反序列化失败: ${e}`)}if(!1!==t.validate){const e=W.validate(o);if(!e.valid){const o=e.errors?.join(", ")||"Unknown error";if(t.strict)throw new Error(`资产验证失败: ${o}`);H.error(`资产验证失败: ${o}`)}e.warnings&&e.warnings.length>0&&H.warn(`资产验证警告: ${e.warnings.join(", ")}`)}return o}static deserializeFromJSON(e){try{const t=JSON.parse(e);if(!t.rootNodeId&&t.nodes&&t.connections){H.info("检测到编辑器格式,正在转换为运行时资产格式...");const e=t,o=G.toAsset(e);return H.info(`已从编辑器格式转换: ${o.nodes.length} 个节点`),o}{const e=t;return H.info(`已从运行时资产格式反序列化: ${e.nodes.length} 个节点`),e}}catch(e){throw new Error(`JSON解析失败: ${e}`)}}static deserializeFromBinary(e){try{const t=j(e);return H.info(`已从二进制反序列化: ${t.nodes.length} 个节点`),t}catch(e){throw new Error(`二进制解码失败: ${e}`)}}static detectFormat(e){return"string"==typeof e?"json":"binary"}static getInfo(e){try{const t=this.detectFormat(e);let o;o="json"===t?JSON.parse(e):j(e);const s=e.length;return{format:t,name:o.metadata.name,version:o.version,nodeCount:o.nodes.length,blackboardVariableCount:o.blackboard.length,size:s}}catch(e){return H.error(`获取资产信息失败: ${e}`),null}}static convert(e,t,o=!0){const s=this.deserialize(e,{validate:!1});return this.serialize(s,{format:t,pretty:o,validate:!1})}static compareSize(e,t){const o=e.length,s=t.length,r=o-s;return{jsonSize:o,binarySize:s,compressionRatio:r/o*100,savedBytes:r}}}const K=n.createLogger("FileSystemAssetLoader");class X{constructor(e){this.cache=new Map,this.config={basePath:e.basePath,format:e.format,extension:e.extension||("json"===e.format?".btree.json":".btree.bin"),enableCache:e.enableCache??!0,readFile:e.readFile||this.defaultReadFile.bind(this)},this.config.basePath=this.config.basePath.replace(/\\/g,"/").replace(/\/$/,"")}async loadBehaviorTree(e){if(this.config.enableCache&&this.cache.has(e))return K.debug(`从缓存加载资产: ${e}`),this.cache.get(e);K.info(`加载行为树资产: ${e}`);try{const t=this.resolveAssetPath(e),o=await this.config.readFile(t),s={validate:!0,strict:!0},r=_.deserialize(o,s);return this.config.enableCache&&this.cache.set(e,r),K.info(`成功加载资产: ${e}`),r}catch(t){throw K.error(`加载资产失败: ${e}`,t),new Error(`Failed to load behavior tree asset '${e}': ${t}`)}}async exists(e){if(this.config.enableCache&&this.cache.has(e))return!0;try{const t=this.resolveAssetPath(e);return await this.config.readFile(t),!0}catch{return!1}}async preload(e){K.info(`预加载 ${e.length} 个资产...`);const t=e.map((e=>this.loadBehaviorTree(e).catch((t=>{K.warn(`预加载资产失败: ${e}`,t)}))));await Promise.all(t),K.info("预加载完成")}unload(e){this.cache.has(e)&&(this.cache.delete(e),K.debug(`卸载资产: ${e}`))}clearCache(){this.cache.clear(),K.info("缓存已清空")}getCacheSize(){return this.cache.size}dispose(){this.clearCache()}resolveAssetPath(e){const t=e.replace(/^\/+/,"");return`${this.config.basePath}/${t}${this.config.extension}`}async defaultReadFile(e){if("undefined"!=typeof window&&"undefined"!=typeof fetch){const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);if("binary"===this.config.format){const e=await t.arrayBuffer();return new Uint8Array(e)}return await t.text()}if("undefined"==typeof require)throw new Error("No default file reading implementation available. Please provide a custom readFile function in the config.");try{const t=require("fs").promises;if("binary"===this.config.format){const o=await t.readFile(e);return new Uint8Array(o)}return await t.readFile(e,"utf-8")}catch(t){throw new Error(`Failed to read file '${e}': ${t}`)}}}const Z=n.createLogger("BehaviorTreeAssetLoader");class Q{static instantiate(e,t,o={}){Z.info(`开始实例化行为树: ${e.metadata.name}`);const s=new Map;for(const t of e.nodes)s.set(t.id,t);const r=s.get(e.rootNodeId);if(!r)throw new Error(`未找到根节点: ${e.rootNodeId}`);const i=new Map,n=this.createEntityTree(r,s,i,t,o.namePrefix,o.asSubTree);return this.setupBlackboard(n,e.blackboard,o.blackboardOverrides),e.propertyBindings&&e.propertyBindings.length>0&&this.setupPropertyBindings(e.propertyBindings,i),Z.info(`行为树实例化完成: ${e.nodes.length} 个节点`),n}static createEntityTree(e,t,o,s,r,i,n=!0){const a=r?`${r}_${e.name}`:e.name,d=s.createEntity(a);o.set(e.id,d);const c=d.addComponent(new exports.BehaviorTreeNode);c.nodeType=e.nodeType,c.nodeName=e.name,this.addNodeComponents(d,e,i&&n);for(const n of e.children){const e=t.get(n);if(!e){Z.warn(`子节点未找到: ${n}`);continue}const a=this.createEntityTree(e,t,o,s,r,i,!1);d.addChild(a)}return d}static addNodeComponents(e,t,o=!1){const{nodeType:s,data:r,name:i}=t;Z.debug(`addNodeComponents: name=${i}, data.nodeType=${r.nodeType}, skipRootNode=${o}`),"root"===r.nodeType||"根节点"===i||"Root"===i?o?(Z.debug(`跳过为子树根节点添加 RootNode: ${i}`),this.addCompositeComponent(e,"序列",r)):(Z.debug(`添加 RootNode 组件: ${i}`),e.addComponent(new exports.RootNode)):s===exports.NodeType.Composite?this.addCompositeComponent(e,i,r):s===exports.NodeType.Decorator?this.addDecoratorComponent(e,i,r):s===exports.NodeType.Action?this.addActionComponent(e,i,r):s===exports.NodeType.Condition&&this.addConditionComponent(e,i,r)}static addCompositeComponent(e,t,o){const s=t.toLowerCase();if(s.includes("sequence")||s.includes("序列")){e.addComponent(new exports.SequenceNode).abortType=o.abortType??exports.AbortType.None}else if(s.includes("selector")||s.includes("选择")){e.addComponent(new exports.SelectorNode).abortType=o.abortType??exports.AbortType.None}else if(s.includes("parallelselector")||s.includes("并行选择")){e.addComponent(new exports.ParallelSelectorNode).failurePolicy=o.failurePolicy??"one"}else if(s.includes("parallel")||s.includes("并行")){const t=e.addComponent(new exports.ParallelNode);t.successPolicy=o.successPolicy??"all",t.failurePolicy=o.failurePolicy??"one"}else s.includes("randomsequence")||s.includes("随机序列")?e.addComponent(new exports.RandomSequenceNode):s.includes("randomselector")||s.includes("随机选择")?e.addComponent(new exports.RandomSelectorNode):Z.warn(`未知的组合节点类型: ${t}`)}static addDecoratorComponent(e,t,o){const s=t.toLowerCase();if(s.includes("inverter")||s.includes("反转"))e.addComponent(new exports.InverterNode);else if(s.includes("repeater")||s.includes("重复")){const t=e.addComponent(new exports.RepeaterNode);t.repeatCount=o.repeatCount??-1,t.endOnFailure=o.endOnFailure??!1}else if(s.includes("untilsuccess")||s.includes("直到成功"))e.addComponent(new exports.UntilSuccessNode);else if(s.includes("untilfail")||s.includes("直到失败"))e.addComponent(new exports.UntilFailNode);else if(s.includes("alwayssucceed")||s.includes("总是成功"))e.addComponent(new exports.AlwaysSucceedNode);else if(s.includes("alwaysfail")||s.includes("总是失败"))e.addComponent(new exports.AlwaysFailNode);else if(s.includes("conditional")||s.includes("条件装饰")){const t=e.addComponent(new exports.ConditionalNode);t.conditionCode=o.conditionCode??"",t.shouldReevaluate=o.shouldReevaluate??!0}else if(s.includes("cooldown")||s.includes("冷却")){e.addComponent(new exports.CooldownNode).cooldownTime=o.cooldownTime??1}else if(s.includes("timeout")||s.includes("超时")){e.addComponent(new exports.TimeoutNode).timeoutDuration=o.timeoutDuration??1}else Z.warn(`未知的装饰器类型: ${t}`)}static addActionComponent(e,t,o){const s=t.toLowerCase();if(s.includes("wait")||s.includes("等待")){e.addComponent(new exports.WaitAction).waitTime=o.waitTime??1}else if(s.includes("log")||s.includes("日志")){const t=e.addComponent(new exports.LogAction);t.message=o.message??"",t.level=o.level??"log"}else if(s.includes("setblackboard")||s.includes("setvalue")||s.includes("设置变量")){const t=e.addComponent(new exports.SetBlackboardValueAction);t.variableName=o.variableName??"",t.value=o.value}else if(s.includes("modifyblackboard")||s.includes("modifyvalue")||s.includes("修改变量")){const t=e.addComponent(new exports.ModifyBlackboardValueAction);t.variableName=o.variableName??"",t.operation=o.operation??"add",t.operand=o.operand??0}else if(s.includes("execute")||s.includes("自定义")){e.addComponent(new exports.ExecuteAction).actionCode=o.actionCode??"return TaskStatus.Success;"}else Z.warn(`未知的动作类型: ${t}`)}static addConditionComponent(e,t,o){const s=t.toLowerCase();if(s.includes("compare")||s.includes("比较变量")){const t=e.addComponent(new exports.BlackboardCompareCondition);t.variableName=o.variableName??"",t.operator=o.operator??exports.CompareOperator.Equal,t.compareValue=o.compareValue,t.invertResult=o.invertResult??!1}else if(s.includes("exists")||s.includes("变量存在")){const t=e.addComponent(new exports.BlackboardExistsCondition);t.variableName=o.variableName??"",t.checkNotNull=o.checkNotNull??!1,t.invertResult=o.invertResult??!1}else if(s.includes("random")||s.includes("概率")){e.addComponent(new exports.RandomProbabilityCondition).probability=o.probability??.5}else if(s.includes("execute")||s.includes("执行条件")){const t=e.addComponent(new exports.ExecuteCondition);t.conditionCode=o.conditionCode??"",t.invertResult=o.invertResult??!1}else Z.warn(`未知的条件类型: ${t}`)}static setupBlackboard(e,t,o){const s=e.addComponent(new exports.BlackboardComponent);for(const e of t){const t=o&&void 0!==o[e.name]?o[e.name]:e.defaultValue;s.defineVariable(e.name,e.type,t,{readonly:e.readonly,description:e.description})}Z.info(`已设置黑板: ${t.length} 个变量`)}static setupPropertyBindings(e,t){for(const o of e){const e=t.get(o.nodeId);if(!e){Z.warn(`属性绑定引用的节点不存在: ${o.nodeId}`);continue}let s=e.getComponent(g);s||(s=e.addComponent(new g)),s.addBinding(o.propertyName,o.variableName)}Z.info(`已设置属性绑定: ${e.length} 个绑定`)}}var Y,ee;!function(e){e[e.NotStarted=0]="NotStarted",e[e.Loading=1]="Loading",e[e.Completed=2]="Completed",e[e.Failed=3]="Failed"}(Y||(Y={}));class te extends n.EntitySystem{constructor(){super(n.Matcher.empty().all(exports.BehaviorTreeNode,exports.ActiveNode)),this.preloadStates=new Map,this.preloadTasks=new Map,this.updateOrder=350}process(e){for(const t of e){const e=t.getComponent(exports.BehaviorTreeNode);e.nodeType===exports.NodeType.Composite&&(t.hasComponent(exports.RootNode)&&this.executeRoot(t,e))}}executeRoot(e,t){const o=this.preloadStates.get(e.id)||Y.NotStarted;if(o===Y.NotStarted)return void this.startPreload(e,t);if(o===Y.Loading)return void(t.status=exports.TaskStatus.Running);if(o===Y.Failed)return t.status=exports.TaskStatus.Failure,void e.removeComponentByType(exports.ActiveNode);const s=e.children;if(0===s.length)return void(t.status=exports.TaskStatus.Success);const r=s[0],i=r.getComponent(exports.BehaviorTreeNode);if(i)return r.hasComponent(exports.ActiveNode)?void(i.status===exports.TaskStatus.Running?t.status=exports.TaskStatus.Running:i.status===exports.TaskStatus.Success?(t.status=exports.TaskStatus.Success,e.removeComponentByType(exports.ActiveNode)):i.status===exports.TaskStatus.Failure&&(t.status=exports.TaskStatus.Failure,e.removeComponentByType(exports.ActiveNode))):(r.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running));t.status=exports.TaskStatus.Failure}startPreload(e,t){const o=this.scanSubTreeNodes(e);if(0===o.length)return this.preloadStates.set(e.id,Y.Completed),void this.outputLog(e,"没有需要预加载的子树","info");this.preloadStates.set(e.id,Y.Loading),t.status=exports.TaskStatus.Running,this.outputLog(e,`开始预加载 ${o.length} 个子树...`,"info");const s=this.preloadAllSubTrees(e,o);this.preloadTasks.set(e.id,s),s.then((()=>{this.preloadStates.set(e.id,Y.Completed),this.outputLog(e,"所有子树预加载完成","info")})).catch((t=>{this.preloadStates.set(e.id,Y.Failed),this.outputLog(e,`子树预加载失败: ${t.message}`,"error")}))}scanSubTreeNodes(e){const t=[],o=e.getComponent(exports.SubTreeNode);o&&o.preload&&t.push({entity:e,subTree:o});for(const o of e.children)t.push(...this.scanSubTreeNodes(o));return t}async preloadAllSubTrees(e,t){if(!this.assetLoader)try{this.assetLoader=n.Core.services.resolve(X)}catch(e){throw new Error("AssetLoader 未配置,无法预加载子树")}await Promise.all(t.map((({entity:t,subTree:o})=>this.preloadSingleSubTree(e,t,o))))}async preloadSingleSubTree(e,t,o){try{this.outputLog(e,`预加载子树: ${o.assetId}`,"info");const s=await this.assetLoader.loadBehaviorTree(o.assetId),r=Q.instantiate(s,this.scene,{asSubTree:!0});o.setSubTreeRoot(r),t.addChild(r);r.addComponent(new exports.BehaviorTreeAssetMetadata).initialize(o.assetId,"1.0.0"),o.inheritParentBlackboard&&this.setupBlackboardInheritance(t,r),this.outputLog(e,`=== 预加载子树 ${o.assetId} 的内部结构 ===`,"info"),this.logSubTreeStructure(e,r,0),this.outputLog(e,"=== 预加载子树结构结束 ===","info"),this.outputLog(e,`✓ 子树 ${o.assetId} 预加载完成`,"info")}catch(t){throw this.outputLog(e,`✗ 子树 ${o.assetId} 预加载失败: ${t.message}`,"error"),t}}setupBlackboardInheritance(e,t){if(!this.findBlackboard(e))return;const o=t.getComponent(exports.BlackboardComponent);o&&o.setUseGlobalBlackboard(!0)}findBlackboard(e){let t=e;for(;t;){const e=t.getComponent(exports.BlackboardComponent);if(e)return e;t=t.parent}}findRootEntity(e){let t=e;for(;t;){if(!t.parent)return t;t=t.parent}return null}outputLog(e,t,o="info"){switch(o){case"info":default:this.logger.info(t);break;case"warn":this.logger.warn(t);break;case"error":this.logger.error(t)}const s=this.findRootEntity(e);if(s){const e=s.getComponent(exports.LogOutput);e&&e.addMessage(t,o)}}logSubTreeStructure(e,t,o){const s=" ".repeat(o);t.getComponent(exports.BehaviorTreeNode);const r=t.components.map((e=>e.constructor.name)).find((e=>"BehaviorTreeNode"!==e&&"ActiveNode"!==e&&"BlackboardComponent"!==e&&"LogOutput"!==e&&"PropertyBindings"!==e&&"BehaviorTreeAssetMetadata"!==e))||"Unknown";let i=t.name;"Unknown"!==r&&(i=`${i} [${r}]`),this.outputLog(e,`${s}└─ ${i}`,"info"),t.children.length>0&&(this.outputLog(e,`${s} 子节点数: ${t.children.length}`,"info"),t.children.forEach((t=>{this.logSubTreeStructure(e,t,o+1)})))}onDestroy(){this.preloadStates.clear(),this.preloadTasks.clear(),super.onDestroy()}getLoggerName(){return"RootExecutionSystem"}}class oe extends n.EntitySystem{constructor(){super(n.Matcher.empty().all(exports.BehaviorTreeNode,exports.ActiveNode)),this.updateOrder=100}process(e){for(const t of e){const e=t.getComponent(exports.BehaviorTreeNode);e.nodeType===exports.NodeType.Action?this.executeAction(t,e):e.nodeType===exports.NodeType.Condition&&this.executeCondition(t,e)}}executeAction(e,t){let o=exports.TaskStatus.Failure;const{displayName:s,nodeIdShort:r}=this.getNodeInfo(e);e.hasComponent(exports.WaitAction)?o=this.executeWaitAction(e):e.hasComponent(exports.LogAction)?o=this.executeLogAction(e):e.hasComponent(exports.SetBlackboardValueAction)?o=this.executeSetBlackboardValue(e):e.hasComponent(exports.ModifyBlackboardValueAction)?o=this.executeModifyBlackboardValue(e):e.hasComponent(exports.ExecuteAction)?o=this.executeCustomAction(e):this.outputLog(e,"动作节点没有找到任何已知的动作组件","warn"),t.status=o;const i=o===exports.TaskStatus.Success?"Success":o===exports.TaskStatus.Failure?"Failure":o===exports.TaskStatus.Running?"Running":"Unknown";o!==exports.TaskStatus.Running&&this.outputLog(e,`[${s}#${r}] 执行完成 -> ${i}`,o===exports.TaskStatus.Success?"info":"warn"),o!==exports.TaskStatus.Running&&(this.deactivateNode(e),this.notifyParent(e))}executeWaitAction(e){const t=e.getComponent(exports.WaitAction);e.getComponent(exports.BehaviorTreeNode);const{displayName:o,nodeIdShort:s}=this.getNodeInfo(e),r=this.resolvePropertyValue(e,"waitTime",t.waitTime);return t.elapsedTime+=n.Time.deltaTime,this.outputLog(e,`[${o}#${s}] deltaTime=${n.Time.deltaTime.toFixed(3)}s, elapsed=${t.elapsedTime.toFixed(3)}s/${r.toFixed(3)}s`,"info"),t.elapsedTime>=r?(t.reset(),this.outputLog(e,`[${o}#${s}] 等待完成,返回成功`,"info"),exports.TaskStatus.Success):exports.TaskStatus.Running}executeLogAction(e){const t=e.getComponent(exports.LogAction),o=e.getComponent(exports.BehaviorTreeNode);let s=this.resolvePropertyValue(e,"message",t.message);const{displayName:r,nodeIdShort:i}=this.getNodeInfo(e);switch(o&&(s=`[${r}#${i}] ${s}`),t.includeEntityInfo&&(s=`[Entity: ${e.name}] ${s}`),t.level){case"info":console.info(s);break;case"warn":console.warn(s);break;case"error":console.error(s);break;default:console.log(s)}const n=this.findRootEntity(e);if(n){const e=n.getComponent(exports.LogOutput);e&&e.addMessage(s,t.level)}return exports.TaskStatus.Success}findRootEntity(e){let t=e;for(;t;){if(!t.parent)return t;t=t.parent}return null}executeSetBlackboardValue(e){const t=e.getComponent(exports.SetBlackboardValueAction),o=this.findBlackboard(e);if(!o)return this.outputLog(e,"未找到黑板组件","warn"),exports.TaskStatus.Failure;let s;if(t.sourceVariable){if(!o.hasVariable(t.sourceVariable))return this.outputLog(e,`源变量不存在: ${t.sourceVariable}`,"warn"),exports.TaskStatus.Failure;s=o.getValue(t.sourceVariable)}else s=this.resolvePropertyValue(e,"value",t.value);return o.setValue(t.variableName,s,t.force)?exports.TaskStatus.Success:exports.TaskStatus.Failure}executeModifyBlackboardValue(e){const t=e.getComponent(exports.ModifyBlackboardValueAction),o=this.findBlackboard(e);if(!o)return this.outputLog(e,"未找到黑板组件","warn"),exports.TaskStatus.Failure;if(!o.hasVariable(t.variableName))return this.outputLog(e,`变量不存在: ${t.variableName}`,"warn"),exports.TaskStatus.Failure;let s,r=o.getValue(t.variableName),i=this.resolvePropertyValue(e,"operand",t.operand);switch(t.operation){case exports.ModifyOperation.Add:s=Number(r)+Number(i);break;case exports.ModifyOperation.Subtract:s=Number(r)-Number(i);break;case exports.ModifyOperation.Multiply:s=Number(r)*Number(i);break;case exports.ModifyOperation.Divide:if(0===Number(i))return this.outputLog(e,"除数不能为0","warn"),exports.TaskStatus.Failure;s=Number(r)/Number(i);break;case exports.ModifyOperation.Modulo:s=Number(r)%Number(i);break;case exports.ModifyOperation.Append:if(Array.isArray(r))s=[...r,i];else{if("string"!=typeof r)return this.outputLog(e,`变量 ${t.variableName} 不支持 append 操作`,"warn"),exports.TaskStatus.Failure;s=r+i}break;case exports.ModifyOperation.Remove:if(!Array.isArray(r))return this.outputLog(e,`变量 ${t.variableName} 不是数组,不支持 remove 操作`,"warn"),exports.TaskStatus.Failure;s=r.filter((e=>e!==i));break;default:return exports.TaskStatus.Failure}return o.setValue(t.variableName,s,t.force)?exports.TaskStatus.Success:exports.TaskStatus.Failure}executeCustomAction(e){const t=e.getComponent(exports.ExecuteAction).getFunction();if(!t)return exports.TaskStatus.Failure;return t(e,this.findBlackboard(e),n.Time.deltaTime)}executeCondition(e,t){let o=!1;const{displayName:s,nodeIdShort:r}=this.getNodeInfo(e);e.hasComponent(exports.BlackboardCompareCondition)?o=this.evaluateBlackboardCompare(e):e.hasComponent(exports.BlackboardExistsCondition)?o=this.evaluateBlackboardExists(e):e.hasComponent(exports.RandomProbabilityCondition)?o=this.evaluateRandomProbability(e):e.hasComponent(exports.ExecuteCondition)?o=this.evaluateCustomCondition(e):this.outputLog(e,"条件节点没有找到任何已知的条件组件","warn"),t.status=o?exports.TaskStatus.Success:exports.TaskStatus.Failure;const i=o?"Success (true)":"Failure (false)";this.outputLog(e,`[${s}#${r}] 条件评估 -> ${i}`,o?"info":"warn"),this.deactivateNode(e),this.notifyParent(e)}evaluateBlackboardCompare(e){const t=e.getComponent(exports.BlackboardCompareCondition),o=this.findBlackboard(e);if(!o||!o.hasVariable(t.variableName))return!1;const s=o.getValue(t.variableName);let r=this.resolvePropertyValue(e,"compareValue",t.compareValue),i=!1;switch(t.operator){case exports.CompareOperator.Equal:i=s===r;break;case exports.CompareOperator.NotEqual:i=s!==r;break;case exports.CompareOperator.Greater:i=s>r;break;case exports.CompareOperator.GreaterOrEqual:i=s>=r;break;case exports.CompareOperator.Less:i=s<r;break;case exports.CompareOperator.LessOrEqual:i=s<=r;break;case exports.CompareOperator.Contains:("string"==typeof s||Array.isArray(s))&&(i=s.includes(r));break;case exports.CompareOperator.Matches:if("string"==typeof s&&"string"==typeof r){i=new RegExp(r).test(s)}}return t.invertResult?!i:i}evaluateBlackboardExists(e){const t=e.getComponent(exports.BlackboardExistsCondition),o=this.findBlackboard(e);if(!o)return!1;let s=o.hasVariable(t.variableName);if(s&&t.checkNotNull){const e=o.getValue(t.variableName);s=null!=e}return t.invertResult?!s:s}evaluateRandomProbability(e){const t=e.getComponent(exports.RandomProbabilityCondition),o=this.resolvePropertyValue(e,"probability",t.probability);return(t.alwaysRandomize||void 0===t.cachedResult)&&(t.cachedResult=Math.random()<o),t.cachedResult}evaluateCustomCondition(e){const t=e.getComponent(exports.ExecuteCondition),o=t.getFunction();if(!o)return!1;const s=o(e,this.findBlackboard(e),n.Time.deltaTime);return t.invertResult?!s:s}resolvePropertyValue(e,t,o){const s=e.getComponent(g);if(!s||!s.hasBinding(t))return o;const r=s.getBinding(t),i=this.findBlackboard(e);if(!i)return this.outputLog(e,`[属性绑定] 未找到黑板组件,实体: ${e.name}`,"warn"),o;if(!i.hasVariable(r))return this.outputLog(e,`[属性绑定] 黑板变量不存在: ${r}`,"warn"),o;return i.getValue(r)}deactivateNode(e){e.removeComponentByType(exports.ActiveNode)}notifyParent(e){e.parent&&e.parent.hasComponent(exports.BehaviorTreeNode)&&(e.parent.hasComponent(exports.ActiveNode)||e.parent.addComponent(new exports.ActiveNode))}findBlackboard(e){let t=e;for(;t;){const e=t.getComponent(exports.BlackboardComponent);if(e)return e;t=t.parent}}getNodeInfo(e){let t="Node",o="";if(e.name&&e.name.includes("#")){const s=e.name.split("#");t=s[0],o=s[1]}else o=e.id.toString().substring(0,8);return{displayName:t,nodeIdShort:o}}outputLog(e,t,o="info"){switch(o){case"info":default:this.logger.info(t);break;case"warn":this.logger.warn(t);break;case"error":this.logger.error(t)}const s=this.findRootEntity(e);if(s){const e=s.getComponent(exports.LogOutput);e&&e.addMessage(t,o)}}getLoggerName(){return"LeafExecutionSystem"}}class se extends n.EntitySystem{constructor(){super(n.Matcher.empty().all(exports.BehaviorTreeNode,exports.ActiveNode)),this.updateOrder=200}process(e){for(const t of e){const e=t.getComponent(exports.BehaviorTreeNode);if(e.nodeType!==exports.NodeType.Decorator)continue;const o=t.getComponentByType(exports.DecoratorNodeComponent);o&&this.executeDecorator(t,e,o)}}executeDecorator(e,t,o){const s=e.children;if(0===s.length)return this.logger.warn("装饰器节点没有子节点"),t.status=exports.TaskStatus.Failure,void this.completeNode(e);const r=s[0],i=r.getComponent(exports.BehaviorTreeNode);if(!i)return t.status=exports.TaskStatus.Failure,void this.completeNode(e);switch(o.decoratorType){case exports.DecoratorType.Inverter:this.handleInverter(e,t,r,i);break;case exports.DecoratorType.Repeater:this.handleRepeater(e,t,o,r,i);break;case exports.DecoratorType.UntilSuccess:this.handleUntilSuccess(e,t,r,i);break;case exports.DecoratorType.UntilFail:this.handleUntilFail(e,t,r,i);break;case exports.DecoratorType.AlwaysSucceed:this.handleAlwaysSucceed(e,t,r,i);break;case exports.DecoratorType.AlwaysFail:this.handleAlwaysFail(e,t,r,i);break;case exports.DecoratorType.Conditional:this.handleConditional(e,t,o,r,i);break;case exports.DecoratorType.Cooldown:this.handleCooldown(e,t,o,r,i);break;case exports.DecoratorType.Timeout:this.handleTimeout(e,t,o,r,i);break;default:t.status=exports.TaskStatus.Failure,this.completeNode(e)}}handleInverter(e,t,o,s){o.hasComponent(exports.ActiveNode)||o.addComponent(new exports.ActiveNode),t.status=exports.TaskStatus.Running,s.status!==exports.TaskStatus.Success&&s.status!==exports.TaskStatus.Failure||(t.status=s.status===exports.TaskStatus.Success?exports.TaskStatus.Failure:exports.TaskStatus.Success,this.completeNode(e))}handleRepeater(e,t,o,s,r){const i=o,n=this.resolvePropertyValue(e,"repeatCount",i.repeatCount),a=this.resolvePropertyValue(e,"endOnFailure",i.endOnFailure);if(!s.hasComponent(exports.ActiveNode))return s.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running);if(r.status===exports.TaskStatus.Running)return void(t.status=exports.TaskStatus.Running);if(r.status===exports.TaskStatus.Failure&&a)return t.status=exports.TaskStatus.Failure,i.reset(),void this.completeNode(e);i.incrementRepeat();-1===n||i.currentRepeatCount<n?(r.invalidate(),s.addComponent(new exports.ActiveNode),t.status=exports.TaskStatus.Running):(t.status=exports.TaskStatus.Success,i.reset(),this.completeNode(e))}handleUntilSuccess(e,t,o,s){if(!o.hasComponent(exports.ActiveNode))return o.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running);s.status!==exports.TaskStatus.Running?s.status===exports.TaskStatus.Success?(t.status=exports.TaskStatus.Success,this.completeNode(e)):(s.invalidate(),o.addComponent(new exports.ActiveNode),t.status=exports.TaskStatus.Running):t.status=exports.TaskStatus.Running}handleUntilFail(e,t,o,s){if(!o.hasComponent(exports.ActiveNode))return o.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running);s.status!==exports.TaskStatus.Running?s.status===exports.TaskStatus.Failure?(t.status=exports.TaskStatus.Success,this.completeNode(e)):(s.invalidate(),o.addComponent(new exports.ActiveNode),t.status=exports.TaskStatus.Running):t.status=exports.TaskStatus.Running}handleAlwaysSucceed(e,t,o,s){if(!o.hasComponent(exports.ActiveNode))return o.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running);s.status===exports.TaskStatus.Running?t.status=exports.TaskStatus.Running:(t.status=exports.TaskStatus.Success,this.completeNode(e))}handleAlwaysFail(e,t,o,s){if(!o.hasComponent(exports.ActiveNode))return o.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running);s.status===exports.TaskStatus.Running?t.status=exports.TaskStatus.Running:(t.status=exports.TaskStatus.Failure,this.completeNode(e))}handleConditional(e,t,o,s,r){return o.evaluateCondition(e,this.findBlackboard(e))?s.hasComponent(exports.ActiveNode)?(t.status=r.status,void(r.status!==exports.TaskStatus.Running&&this.completeNode(e))):(s.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running)):(t.status=exports.TaskStatus.Failure,void this.completeNode(e))}handleCooldown(e,t,o,s,r){const i=o,a=this.resolvePropertyValue(e,"cooldownTime",i.cooldownTime),d=n.Time.totalTime-i.lastExecutionTime,c=0===i.lastExecutionTime||d>=a;return this.outputLog(e,`[冷却检查] Time.totalTime=${n.Time.totalTime.toFixed(3)}, lastExecution=${i.lastExecutionTime.toFixed(3)}, cooldownTime=${a}, timeSince=${d.toFixed(3)}, canExecute=${c}, childStatus=${r.status}`,"info"),c?r.status!==exports.TaskStatus.Invalid&&r.status!==exports.TaskStatus.Running?(t.status=r.status,i.recordExecution(n.Time.totalTime),this.outputLog(e,`[冷却记录] 记录执行时间: ${n.Time.totalTime.toFixed(3)}, 下次可执行时间: ${(n.Time.totalTime+a).toFixed(3)}`,"info"),void this.completeNode(e)):(s.hasComponent(exports.ActiveNode)||s.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running)):(t.status=exports.TaskStatus.Failure,void this.completeNode(e))}handleTimeout(e,t,o,s,r){const i=o,a=this.resolvePropertyValue(e,"timeoutDuration",i.timeoutDuration);i.recordStartTime(n.Time.totalTime);return i.startTime>0&&n.Time.totalTime-i.startTime>=a?(t.status=exports.TaskStatus.Failure,i.reset(),s.removeComponentByType(exports.ActiveNode),void this.completeNode(e)):s.hasComponent(exports.ActiveNode)?(t.status=r.status,void(r.status!==exports.TaskStatus.Running&&(i.reset(),this.completeNode(e)))):(s.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running))}completeNode(e){e.removeComponentByType(exports.ActiveNode),e.parent&&e.parent.hasComponent(exports.BehaviorTreeNode)&&(e.parent.hasComponent(exports.ActiveNode)||e.parent.addComponent(new exports.ActiveNode))}findBlackboard(e){let t=e;for(;t;){const e=t.getComponent(exports.BlackboardComponent);if(e)return e;t=t.parent}}resolvePropertyValue(e,t,o){const s=e.getComponent(g);if(!s||!s.hasBinding(t))return o;const r=s.getBinding(t),i=this.findBlackboard(e);return i&&i.hasVariable(r)?i.getValue(r):o}findRootEntity(e){let t=e;for(;t;){if(!t.parent)return t;t=t.parent}return null}outputLog(e,t,o="info"){switch(o){case"info":default:this.logger.info(t);break;case"warn":this.logger.warn(t);break;case"error":this.logger.error(t)}const s=this.findRootEntity(e);if(s){const e=s.getComponent(exports.LogOutput);e&&e.addMessage(t,o)}}getLoggerName(){return"DecoratorExecutionSystem"}}class re extends n.EntitySystem{constructor(){super(n.Matcher.empty().all(exports.BehaviorTreeNode,exports.ActiveNode).exclude(exports.RootNode,exports.SubTreeNode)),this.updateOrder=300}process(e){for(const t of e){const e=t.getComponent(exports.BehaviorTreeNode);if(e.nodeType!==exports.NodeType.Composite)continue;const o=t.getComponentByType(exports.CompositeNodeComponent);if(o)this.executeComposite(t,e,o);else{this.logger.warn(`复合节点 ${t.name} 没有找到复合节点组件`);const e=t.components.map((e=>e.constructor.name)).join(", ");this.logger.warn(` 组件列表: ${e}`)}}}executeComposite(e,t,o){const s=e.children;if(0===s.length)return t.status=exports.TaskStatus.Success,void this.completeNode(e);switch(o.compositeType){case exports.CompositeType.Sequence:this.handleSequence(e,t,s);break;case exports.CompositeType.Selector:this.handleSelector(e,t,s);break;case exports.CompositeType.Parallel:this.handleParallel(e,t,s);break;case exports.CompositeType.ParallelSelector:this.handleParallelSelector(e,t,s);break;case exports.CompositeType.RandomSequence:this.handleRandomSequence(e,t,o,s);break;case exports.CompositeType.RandomSelector:this.handleRandomSelector(e,t,o,s);break;default:t.status=exports.TaskStatus.Failure,this.completeNode(e)}}handleSequence(e,t,o){const s=e.getComponentByType(exports.SequenceNode);if(s&&s.abortType!==exports.AbortType.None&&this.shouldAbort(e,t,o,s.abortType))return void this.abortExecution(e,t,o);if(t.currentChildIndex>=o.length)return t.status=exports.TaskStatus.Success,t.currentChildIndex=0,void this.completeNode(e);const r=o[t.currentChildIndex],i=r.getComponent(exports.BehaviorTreeNode);return i?i.status===exports.TaskStatus.Invalid?(r.hasComponent(exports.ActiveNode)||r.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running)):void(i.status===exports.TaskStatus.Running?t.status=exports.TaskStatus.Running:i.status===exports.TaskStatus.Failure?(t.status=exports.TaskStatus.Failure,t.currentChildIndex=0,this.completeNode(e)):i.status===exports.TaskStatus.Success&&(i.reset(),t.currentChildIndex++,t.status=exports.TaskStatus.Running)):(t.status=exports.TaskStatus.Failure,void this.completeNode(e))}handleSelector(e,t,o){const s=e.getComponentByType(exports.SelectorNode);if(s&&s.abortType!==exports.AbortType.None&&this.shouldAbort(e,t,o,s.abortType))return void this.abortExecution(e,t,o);if(t.currentChildIndex>=o.length)return t.status=exports.TaskStatus.Failure,t.currentChildIndex=0,void this.completeNode(e);const r=o[t.currentChildIndex],i=r.getComponent(exports.BehaviorTreeNode);return i?i.status===exports.TaskStatus.Invalid?(r.hasComponent(exports.ActiveNode)||r.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running)):void(i.status===exports.TaskStatus.Running?t.status=exports.TaskStatus.Running:i.status===exports.TaskStatus.Success?(t.status=exports.TaskStatus.Success,t.currentChildIndex=0,this.completeNode(e)):i.status===exports.TaskStatus.Failure&&(i.reset(),t.currentChildIndex++,t.status=exports.TaskStatus.Running)):(t.status=exports.TaskStatus.Failure,void this.completeNode(e))}handleParallel(e,t,o){let s=!1,r=!1;for(const e of o){e.hasComponent(exports.ActiveNode)||e.addComponent(new exports.ActiveNode);const t=e.getComponent(exports.BehaviorTreeNode);t&&(t.status===exports.TaskStatus.Running?s=!0:t.status===exports.TaskStatus.Failure&&(r=!0))}s?t.status=exports.TaskStatus.Running:r?(t.status=exports.TaskStatus.Failure,t.currentChildIndex=0,this.completeNode(e)):(t.status=exports.TaskStatus.Success,t.currentChildIndex=0,this.completeNode(e))}handleParallelSelector(e,t,o){let s=!1,r=!1;for(const e of o){e.hasComponent(exports.ActiveNode)||e.addComponent(new exports.ActiveNode);const t=e.getComponent(exports.BehaviorTreeNode);t&&(t.status===exports.TaskStatus.Running?s=!0:t.status===exports.TaskStatus.Success&&(r=!0))}if(r){t.status=exports.TaskStatus.Success,t.currentChildIndex=0;for(const e of o)e.removeComponentByType(exports.ActiveNode);this.completeNode(e)}else s?t.status=exports.TaskStatus.Running:(t.status=exports.TaskStatus.Failure,t.currentChildIndex=0,this.completeNode(e))}handleRandomSequence(e,t,o,s){const r=o.getNextChildIndex(t.currentChildIndex,s.length);if(r>=s.length)return t.status=exports.TaskStatus.Success,t.currentChildIndex=0,o.resetShuffle(),void this.completeNode(e);const i=s[r],n=i.getComponent(exports.BehaviorTreeNode);return n?n.status===exports.TaskStatus.Invalid?(i.hasComponent(exports.ActiveNode)||i.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running)):void(n.status===exports.TaskStatus.Running?t.status=exports.TaskStatus.Running:n.status===exports.TaskStatus.Failure?(t.status=exports.TaskStatus.Failure,t.currentChildIndex=0,o.resetShuffle(),this.completeNode(e)):n.status===exports.TaskStatus.Success&&(n.reset(),t.currentChildIndex++,t.status=exports.TaskStatus.Running)):(t.status=exports.TaskStatus.Failure,void this.completeNode(e))}handleRandomSelector(e,t,o,s){const r=o.getNextChildIndex(t.currentChildIndex,s.length);if(r>=s.length)return t.status=exports.TaskStatus.Failure,t.currentChildIndex=0,o.resetShuffle(),void this.completeNode(e);const i=s[r],n=i.getComponent(exports.BehaviorTreeNode);return n?n.status===exports.TaskStatus.Invalid?(i.hasComponent(exports.ActiveNode)||i.addComponent(new exports.ActiveNode),void(t.status=exports.TaskStatus.Running)):void(n.status===exports.TaskStatus.Running?t.status=exports.TaskStatus.Running:n.status===exports.TaskStatus.Success?(t.status=exports.TaskStatus.Success,t.currentChildIndex=0,o.resetShuffle(),this.completeNode(e)):n.status===exports.TaskStatus.Failure&&(n.reset(),t.currentChildIndex++,t.status=exports.TaskStatus.Running)):(t.status=exports.TaskStatus.Failure,void this.completeNode(e))}shouldAbort(e,t,o,s){const r=t.currentChildIndex;if(0===r)return!1;if(s===exports.AbortType.Self||s===exports.AbortType.Both)for(let e=0;e<r;e++){const t=o[e].getComponent(exports.BehaviorTreeNode);if(t&&t.nodeType===exports.NodeType.Condition&&t.status===exports.TaskStatus.Failure)return!0}if(s===exports.AbortType.LowerPriority||s===exports.AbortType.Both)for(let e=0;e<r;e++){const t=o[e],s=t.getComponent(exports.BehaviorTreeNode);if(s)if(s.nodeType===exports.NodeType.Condition){if(this.evaluateCondition(t,s))return!0}else if(s.nodeType===exports.NodeType.Composite&&t.children.length>0){const e=t.children[0],o=e.getComponent(exports.BehaviorTreeNode);if(o&&o.nodeType===exports.NodeType.Condition&&this.evaluateCondition(e,o))return!0}}return!1}evaluateCondition(e,t){if(t.nodeType!==exports.NodeType.Condition)return!1;let o=!1;return e.hasComponent(exports.BlackboardCompareCondition)?o=this.evaluateBlackboardCompare(e):e.hasComponent(exports.BlackboardExistsCondition)?o=this.evaluateBlackboardExists(e):e.hasComponent(exports.RandomProbabilityCondition)?o=this.evaluateRandomProbability(e):e.hasComponent(exports.ExecuteCondition)&&(o=this.evaluateCustomCondition(e)),o}evaluateBlackboardCompare(e){const t=e.getComponent(exports.BlackboardCompareCondition),o=this.findBlackboard(e);if(!o||!o.hasVariable(t.variableName))return!1;const s=o.getValue(t.variableName);let r=t.compareValue;"string"==typeof r&&(r=this.resolveVariableReferences(r,o));let i=!1;switch(t.operator){case exports.CompareOperator.Equal:i=s===r;break;case exports.CompareOperator.NotEqual:i=s!==r;break;case exports.CompareOperator.Greater:i=s>r;break;case exports.CompareOperator.GreaterOrEqual:i=s>=r;break;case exports.CompareOperator.Less:i=s<r;break;case exports.CompareOperator.LessOrEqual:i=s<=r;break;case exports.CompareOperator.Contains:("string"==typeof s||Array.isArray(s))&&(i=s.includes(r));break;case exports.CompareOperator.Matches:if("string"==typeof s&&"string"==typeof r){i=new RegExp(r).test(s)}}return t.invertResult?!i:i}evaluateBlackboardExists(e){const t=e.getComponent(exports.BlackboardExistsCondition),o=this.findBlackboard(e);if(!o)return!1;let s=o.hasVariable(t.variableName);if(s&&t.checkNotNull){const e=o.getValue(t.variableName);s=null!=e}return t.invertResult?!s:s}evaluateRandomProbability(e){return e.getComponent(exports.RandomProbabilityCondition).evaluate()}evaluateCustomCondition(e){const t=e.getComponent(exports.ExecuteCondition),o=t.getFunction();if(!o)return!1;const s=o(e,this.findBlackboard(e),0);return t.invertResult?!s:s}resolveVariableReferences(e,t){const o=e.match(/^{{\s*(\w+)\s*}}$/);if(o){const s=o[1];return t.hasVariable(s)?t.getValue(s):e}return e.replace(/\{\{(\w+)\}\}/g,((e,o)=>{if(t.hasVariable(o)){const s=t.getValue(o);return void 0!==s?String(s):e}return e}))}findBlackboard(e){let t=e;for(;t;){const e=t.getComponent(exports.BlackboardComponent);if(e)return e;t=t.parent}}abortExecution(e,t,o){const s=t.currentChildIndex;if(s<o.length){const e=o[s];this.deactivateNode(e)}t.currentChildIndex=0,t.status=exports.TaskStatus.Running}deactivateNode(e){e.removeComponentByType(exports.ActiveNode);const t=e.getComponent(exports.BehaviorTreeNode);t&&t.reset();for(const t of e.children)this.deactivateNode(t)}resetAllChildren(e){for(const t of e.children){const e=t.getComponent(exports.BehaviorTreeNode);e&&e.reset(),this.resetAllChildren(t)}}completeNode(e){e.removeComponentByType(exports.ActiveNode);const t=e.getComponent(exports.BehaviorTreeNode);t&&t.nodeType===exports.NodeType.Composite&&this.resetAllChildren(e),e.parent&&e.parent.hasComponent(exports.BehaviorTreeNode)&&(e.parent.hasComponent(exports.ActiveNode)||e.parent.addComponent(new exports.ActiveNode))}getLoggerName(){return"CompositeExecutionSystem"}}exports.LoadingState=void 0,(ee=exports.LoadingState||(exports.LoadingState={})).Idle="idle",ee.Pending="pending",ee.Loading="loading",ee.Loaded="loaded",ee.Failed="failed",ee.Timeout="timeout",ee.Cancelled="cancelled";class ie extends Error{constructor(e){super(e),this.name="TimeoutError"}}class ne extends Error{constructor(e){super(e),this.name="CircularDependencyError"}}class ae extends Error{constructor(e){super(e),this.name="EntityDestroyedError"}}const de=n.createLogger("AssetLoadingManager");class ce{constructor(){this.tasks=new Map,this.loadingStack=new Set,this.defaultOptions={timeoutMs:5e3,maxRetries:3,retryDelayBase:100,maxRetryDelay:2e3}}startLoading(e,t,o,s={}){const r={...this.defaultOptions,...s};if(s.parentAssetId&&this.detectCircularDependency(e,s.parentAssetId)){const t=new ne(`检测到循环引用: ${s.parentAssetId} → ${e}\n加载栈: ${Array.from(this.loadingStack).join(" → ")}`);throw de.error(t.message),t}const i=this.tasks.get(e);if(i)return de.debug(`资产 ${e} 已在加载中,返回现有任务`),this.createHandle(i);const n={assetId:e,promise:null,startTime:Date.now(),lastRetryTime:0,retryCount:0,maxRetries:r.maxRetries,timeoutMs:r.timeoutMs,state:exports.LoadingState.Pending,parentEntityId:t.id,parentEntity:t,parentAssetId:s.parentAssetId};return this.loadingStack.add(e),n.promise=this.loadWithTimeoutAndRetry(n,o,r),n.state=exports.LoadingState.Loading,this.tasks.set(e,n),de.info(`开始加载资产: ${e}`,{timeoutMs:r.timeoutMs,maxRetries:r.maxRetries,parentAssetId:s.parentAssetId}),this.createHandle(n)}async loadWithTimeoutAndRetry(e,t,o){let s=null;for(let r=0;r<=e.maxRetries;r++){if(e.parentEntity.isDestroyed){const t=new ae(`父实体已销毁,取消加载: ${e.assetId}`);throw e.state=exports.LoadingState.Cancelled,this.cleanup(e.assetId),de.warn(t.message),t}try{e.retryCount=r,e.lastRetryTime=Date.now(),de.debug(`加载尝试 ${r+1}/${e.maxRetries+1}: ${e.assetId}`);const o=await this.withTimeout(t(),e.timeoutMs,`加载资产 ${e.assetId} 超时(${e.timeoutMs}ms)`);return e.state=exports.LoadingState.Loaded,e.result=o,this.cleanup(e.assetId),de.info(`资产加载成功: ${e.assetId}`,{attempts:r+1,elapsedMs:Date.now()-e.startTime}),o}catch(t){if(s=t,t instanceof ie)e.state=exports.LoadingState.Timeout,de.warn(`资产加载超时: ${e.assetId} (尝试 ${r+1})`);else{if(t instanceof ae)throw t;de.warn(`资产加载失败: ${e.assetId} (尝试 ${r+1})`,t)}if(r===e.maxRetries)throw e.state=exports.LoadingState.Failed,e.error=s,this.cleanup(e.assetId),de.error(`资产加载最终失败: ${e.assetId}`,{attempts:r+1,error:s.message}),s;const i=Math.min(Math.pow(2,r)*o.retryDelayBase,o.maxRetryDelay);de.debug(`等待 ${i}ms 后重试...`),await this.delay(i)}}throw s}withTimeout(e,t,o){let s;const r=new Promise(((e,r)=>{s=setTimeout((()=>{r(new ie(o))}),t)}));return Promise.race([e.then((e=>(clearTimeout(s),e))),r]).catch((e=>{throw clearTimeout(s),e}))}detectCircularDependency(e,t){return!!this.loadingStack.has(t)}getTaskState(e){return this.tasks.get(e)?.state??exports.LoadingState.Idle}getTask(e){return this.tasks.get(e)}cancelLoading(e){const t=this.tasks.get(e);t&&(t.state=exports.LoadingState.Cancelled,this.cleanup(e),de.info(`取消加载: ${e}`))}cleanup(e){const t=this.tasks.get(e);t&&(t.parentEntity=null),this.tasks.delete(e),this.loadingStack.delete(e)}delay(e){return new Promise((t=>setTimeout(t,e)))}createHandle(e){return{assetId:e.assetId,getState:()=>e.state,getError:()=>e.error,getProgress:()=>{const t=Date.now()-e.startTime,o=Math.max(0,e.timeoutMs-t);return{state:e.state,elapsedMs:t,remainingTimeoutMs:o,retryCount:e.retryCount,maxRetries:e.maxRetries}},cancel:()=>this.cancelLoading(e.assetId),promise:e.promise}}getLoadingAssets(){return Array.from(this.tasks.keys())}getStats(){const e=Array.from(this.tasks.values());return{totalTasks:e.length,loadingTasks:e.filter((e=>e.state===exports.LoadingState.Loading)).length,failedTasks:e.filter((e=>e.state===exports.LoadingState.Failed)).length,timeoutTasks:e.filter((e=>e.state===exports.LoadingState.Timeout)).length}}clear(){de.info("清空所有加载任务",this.getStats()),this.tasks.clear(),this.loadingStack.clear()}dispose(){this.clear()}}class pe extends n.EntitySystem{constructor(e){super(n.Matcher.empty().all(exports.SubTreeNode,exports.ActiveNode,exports.BehaviorTreeNode)),this.assetLoaderInitialized=!1,this.hasLoggedMissingAssetLoader=!1,this.loadingTasks=new Map,this.updateOrder=300,this.loadingManager=e||new ce}onInitialize(){}process(e){for(const t of e){const e=t.getComponent(exports.SubTreeNode),o=t.getComponent(exports.BehaviorTreeNode);this.executeSubTree(t,e,o)}}executeSubTree(e,t,o){const s=t.validate();if(s.length>0)return this.logger.error(`SubTree 节点配置错误: ${s.join(", ")}`),o.status=exports.TaskStatus.Failure,void this.completeNode(e);const r=t.getSubTreeRoot();if(r){const s=r.getComponent(exports.BehaviorTreeNode);if(s){const i=exports.TaskStatus[s.status],n=r.hasComponent(exports.ActiveNode);if(this.outputLog(e,`检查预加载子树 ${t.assetId}: status=${i}, hasActive=${n}`,"info"),s.status===exports.TaskStatus.Invalid){if(this.outputLog(e,`使用预加载的子树: ${t.assetId}`,"info"),this.outputLog(e,`激活前:子树根节点 ${r.name} 有 ${r.children.length} 个子节点`,"info"),r.children.length>0){const t=r.children[0];this.outputLog(e,` 第一个子节点: ${t.name}`,"info")}r.hasComponent(exports.ActiveNode)||(r.addComponent(new exports.ActiveNode),this.outputLog(e,`为子树根节点添加 ActiveNode: ${r.name}`,"info"));const s=r.getComponent(exports.BehaviorTreeNode);return s&&(this.outputLog(e,`设置子树根节点状态: ${r.name} -> Running`,"info"),s.status=exports.TaskStatus.Running),this.outputLog(e,`激活后:子树根节点 ${r.name} 有 ${r.children.length} 个子节点`,"info"),this.outputLog(e,`激活预加载的子树: ${t.assetId}`,"info"),void(o.status=exports.TaskStatus.Running)}}this.updateSubTree(e,t,o)}else this.outputLog(e,`子树未预加载,开始运行时加载: ${t.assetId}`,"info"),this.loadAndInstantiateSubTree(e,t,o)}ensureAssetLoaderInitialized(){if(!this.assetLoaderInitialized)try{this.assetLoader=n.Core.services.resolve(X),this.assetLoaderInitialized=!0,this.logger.debug("AssetLoader 已初始化")}catch(e){return this.assetLoaderInitialized=!0,this.assetLoader=void 0,this.hasLoggedMissingAssetLoader||(this.logger.warn("AssetLoader 未配置。SubTree 节点需要 AssetLoader 来加载子树资产。\n如果您在编辑器中,请确保已打开项目并配置了项目路径。\n如果您在运行时环境,请确保已正确注册 FileSystemAssetLoader 服务。"),this.hasLoggedMissingAssetLoader=!0),!1}return void 0!==this.assetLoader}loadAndInstantiateSubTree(e,t,o){if(!this.ensureAssetLoaderInitialized())return this.logger.debug("AssetLoader 不可用,SubTree 节点执行失败"),o.status=exports.TaskStatus.Failure,void this.completeNode(e);const s=t.assetId;let r=this.loadingTasks.get(e.id);if(r){switch(r.getState()){case exports.LoadingState.Loading:case exports.LoadingState.Pending:o.status=exports.TaskStatus.Running;const i=r.getProgress();return void(i.elapsedMs>1e3&&this.logger.debug(`子树加载中: ${s} (已耗时: ${Math.round(i.elapsedMs/1e3)}s, 重试: ${i.retryCount}/${i.maxRetries})`));case exports.LoadingState.Loaded:return void this.onLoadingComplete(e,t,o,r);case exports.LoadingState.Failed:case exports.LoadingState.Timeout:const n=r.getError();return this.outputLog(e,`子树加载失败: ${s} - ${n?.message||"未知错误"}`,"error"),o.status=exports.TaskStatus.Failure,this.loadingTasks.delete(e.id),void this.completeNode(e);case exports.LoadingState.Cancelled:return void this.loadingTasks.delete(e.id)}}this.startNewLoading(e,t,o)}startNewLoading(e,t,o){const s=t.assetId,r=this.getParentTreeAssetId(e);try{const t=this.loadingManager.startLoading(s,e,(()=>this.loadAsset(s)),{timeoutMs:5e3,maxRetries:2,parentAssetId:r});this.loadingTasks.set(e.id,t),o.status=exports.TaskStatus.Running,this.outputLog(e,`开始加载子树: ${s} (父树: ${r||"none"})`,"info")}catch(t){t instanceof ne?this.outputLog(e,`检测到循环引用: ${t.message}`,"error"):this.outputLog(e,`启动加载失败: ${s}`,"error"),o.status=exports.TaskStatus.Failure,this.completeNode(e)}}onLoadingComplete(e,t,o,s){s.promise.then((o=>{if(e.isDestroyed)return this.logger.warn(`父实体已销毁,丢弃加载结果: ${s.assetId}`),void o.destroy();t.setSubTreeRoot(o),e.addChild(o);o.addComponent(new exports.BehaviorTreeAssetMetadata).initialize(s.assetId,"1.0.0"),t.inheritParentBlackboard&&this.setupBlackboardInheritance(e,o),this.outputLog(e,`子树 ${s.assetId} 加载成功并激活`,"info"),this.outputLog(e,`=== 子树 ${s.assetId} 内部结构 ===`,"info"),this.logSubTreeStructure(e,o,0),this.outputLog(e,"=== 子树结构结束 ===","info"),this.startSubTreeExecution(o,e),this.loadingTasks.delete(e.id)})).catch((e=>{e instanceof ae||this.logger.error("意外错误:",e)}))}async loadAsset(e){if(!this.scene)throw new Error("Scene 不存在");const t=await this.assetLoader.loadBehaviorTree(e);return Q.instantiate(t,this.scene,{asSubTree:!0})}setupBlackboardInheritance(e,t){if(!this.findBlackboard(e))return;const o=t.getComponent(exports.BlackboardComponent);o&&o.setUseGlobalBlackboard(!0)}findBlackboard(e){let t=e;for(;t;){const e=t.getComponent(exports.BlackboardComponent);if(e)return e;t=t.parent}}startSubTreeExecution(e,t){t&&this.outputLog(t,`子树根节点 ${e.name} 有 ${e.children.length} 个子节点`,"info"),e.hasComponent(exports.ActiveNode)||(e.addComponent(new exports.ActiveNode),t&&this.outputLog(t,`为子树根节点添加 ActiveNode: ${e.name}`,"info"));const o=e.getComponent(exports.BehaviorTreeNode);o&&(t&&this.outputLog(t,`设置子树根节点状态: ${e.name} -> Running`,"info"),o.status=exports.TaskStatus.Running)}updateSubTree(e,t,o){const s=t.getSubTreeRoot();if(!s)return;const r=s.getComponent(exports.BehaviorTreeNode);if(!r)return;const i=exports.TaskStatus[r.status];this.outputLog(e,`子树 ${t.assetId} 当前状态: ${i}`,"info"),r.status!==exports.TaskStatus.Running?this.onSubTreeCompleted(e,t,o,r.status):o.status=exports.TaskStatus.Running}onSubTreeCompleted(e,t,o,s){this.outputLog(e,`子树完成,状态: ${exports.TaskStatus[s]}`,"info"),this.outputLog(e,`完成前:SubTreeNode ${e.name} 有 ${e.children.length} 个子节点`,"info"),t.markSubTreeCompleted(s),s===exports.TaskStatus.Success?o.status=exports.TaskStatus.Success:s===exports.TaskStatus.Failure?t.propagateFailure?o.status=exports.TaskStatus.Failure:o.status=exports.TaskStatus.Success:o.status=s,this.cleanupSubTree(t),this.outputLog(e,`清理后:SubTreeNode ${e.name} 有 ${e.children.length} 个子节点`,"info"),this.completeNode(e)}cleanupSubTree(e){const t=e.getSubTreeRoot();t&&(e.preload?(this.logger.debug(`重置预加载子树以便复用: ${e.assetId}`),this.resetSubTreeRecursively(t),e.resetCompletionState()):(this.logger.debug(`销毁运行时加载的子树: ${e.assetId}`),t.destroy(),e.setSubTreeRoot(void 0),e.reset()))}resetSubTreeRecursively(e){e.hasComponent(exports.ActiveNode)&&e.removeComponentByType(exports.ActiveNode);const t=e.getComponent(exports.BehaviorTreeNode);t&&(t.status=exports.TaskStatus.Invalid);for(const t of e.children)this.resetSubTreeRecursively(t)}completeNode(e){e.removeComponentByType(exports.ActiveNode),e.parent&&e.parent.hasComponent(exports.BehaviorTreeNode)&&(e.parent.hasComponent(exports.ActiveNode)||e.parent.addComponent(new exports.ActiveNode))}getParentTreeAssetId(e){let t=e;for(;t;){const e=t.getComponent(exports.BehaviorTreeAssetMetadata);if(e&&e.assetId)return e.assetId;t=t.parent}}onDestroy(){for(const e of this.loadingTasks.values())e.cancel();this.loadingTasks.clear(),super.onDestroy()}findRootEntity(e){let t=e;for(;t;){if(!t.parent)return t;t=t.parent}return null}outputLog(e,t,o="info"){switch(o){case"info":default:this.logger.info(t);break;case"warn":this.logger.warn(t);break;case"error":this.logger.error(t)}const s=this.findRootEntity(e);if(s){const e=s.getComponent(exports.LogOutput);e&&e.addMessage(t,o)}}logSubTreeStructure(e,t,o){const s=" ".repeat(o);t.getComponent(exports.BehaviorTreeNode);const r=t.components.map((e=>e.constructor.name)).find((e=>"BehaviorTreeNode"!==e&&"ActiveNode"!==e&&"BlackboardComponent"!==e&&"LogOutput"!==e&&"PropertyBindings"!==e&&"BehaviorTreeAssetMetadata"!==e))||"Unknown";let i=t.name;"Unknown"!==r&&(i=`${i} [${r}]`),this.outputLog(e,`${s}└─ ${i}`,"info"),t.children.length>0&&(this.outputLog(e,`${s} 子节点数: ${t.children.length}`,"info"),t.children.forEach((t=>{this.logSubTreeStructure(e,t,o+1)})))}getLoggerName(){return"SubTreeExecutionSystem"}}var le;exports.AssetType=void 0,(le=exports.AssetType||(exports.AssetType={})).BehaviorTree="behavior-tree",le.Blackboard="blackboard",le.Unknown="unknown";class ue{constructor(e,t){this.entityStack=[],this.scene=e,this.currentEntity=e.createEntity(t)}static create(e,t="BehaviorTreeRoot"){return new ue(e,t)}blackboard(){return this.blackboardEntity=this.currentEntity,this.currentEntity.addComponent(new exports.BlackboardComponent),this}defineVariable(e,t,o,s){if(!this.blackboardEntity)throw new Error("Must call blackboard() first");const r=this.blackboardEntity.getComponent(exports.BlackboardComponent);return r&&r.defineVariable(e,t,o,s),this}endBlackboard(){return this.blackboardEntity=void 0,this}sequence(e="Sequence"){return this.composite(e,exports.CompositeType.Sequence)}selector(e="Selector"){return this.composite(e,exports.CompositeType.Selector)}parallel(e="Parallel"){return this.composite(e,exports.CompositeType.Parallel)}parallelSelector(e="ParallelSelector"){return this.composite(e,exports.CompositeType.ParallelSelector)}randomSequence(e="RandomSequence"){return this.composite(e,exports.CompositeType.RandomSequence)}randomSelector(e="RandomSelector"){return this.composite(e,exports.CompositeType.RandomSelector)}composite(e,t){this.entityStack.push(this.currentEntity);const o=this.scene.createEntity(e);this.currentEntity.addChild(o);const s=o.addComponent(new exports.BehaviorTreeNode);s.nodeType=exports.NodeType.Composite,s.nodeName=e;return o.addComponent(new exports.CompositeNodeComponent).compositeType=t,this.currentEntity=o,this}inverter(e="Inverter"){this.entityStack.push(this.currentEntity);const t=this.scene.createEntity(e);this.currentEntity.addChild(t);const o=t.addComponent(new exports.BehaviorTreeNode);return o.nodeType=exports.NodeType.Decorator,o.nodeName=e,t.addComponent(new exports.InverterNode),this.currentEntity=t,this}repeater(e="Repeater",t=-1,o=!1){this.entityStack.push(this.currentEntity);const s=this.scene.createEntity(e);this.currentEntity.addChild(s);const r=s.addComponent(new exports.BehaviorTreeNode);r.nodeType=exports.NodeType.Decorator,r.nodeName=e;const i=s.addComponent(new exports.RepeaterNode);return i.repeatCount=t,i.endOnFailure=o,this.currentEntity=s,this}untilSuccess(e="UntilSuccess"){this.entityStack.push(this.currentEntity);const t=this.scene.createEntity(e);this.currentEntity.addChild(t);const o=t.addComponent(new exports.BehaviorTreeNode);return o.nodeType=exports.NodeType.Decorator,o.nodeName=e,t.addComponent(new exports.UntilSuccessNode),this.currentEntity=t,this}untilFail(e="UntilFail"){this.entityStack.push(this.currentEntity);const t=this.scene.createEntity(e);this.currentEntity.addChild(t);const o=t.addComponent(new exports.BehaviorTreeNode);return o.nodeType=exports.NodeType.Decorator,o.nodeName=e,t.addComponent(new exports.UntilFailNode),this.currentEntity=t,this}alwaysSucceed(e="AlwaysSucceed"){this.entityStack.push(this.currentEntity);const t=this.scene.createEntity(e);this.currentEntity.addChild(t);const o=t.addComponent(new exports.BehaviorTreeNode);return o.nodeType=exports.NodeType.Decorator,o.nodeName=e,t.addComponent(new exports.AlwaysSucceedNode),this.currentEntity=t,this}alwaysFail(e="AlwaysFail"){this.entityStack.push(this.currentEntity);const t=this.scene.createEntity(e);this.currentEntity.addChild(t);const o=t.addComponent(new exports.BehaviorTreeNode);return o.nodeType=exports.NodeType.Decorator,o.nodeName=e,t.addComponent(new exports.AlwaysFailNode),this.currentEntity=t,this}conditional(e,t){this.entityStack.push(this.currentEntity);const o=this.scene.createEntity(e);this.currentEntity.addChild(o);const s=o.addComponent(new exports.BehaviorTreeNode);s.nodeType=exports.NodeType.Decorator,s.nodeName=e;return o.addComponent(new exports.ConditionalNode).conditionCode=t,this.currentEntity=o,this}cooldown(e="Cooldown",t=1){this.entityStack.push(this.currentEntity);const o=this.scene.createEntity(e);this.currentEntity.addChild(o);const s=o.addComponent(new exports.BehaviorTreeNode);s.nodeType=exports.NodeType.Decorator,s.nodeName=e;return o.addComponent(new exports.CooldownNode).cooldownTime=t,this.currentEntity=o,this}timeout(e="Timeout",t=5){this.entityStack.push(this.currentEntity);const o=this.scene.createEntity(e);this.currentEntity.addChild(o);const s=o.addComponent(new exports.BehaviorTreeNode);s.nodeType=exports.NodeType.Decorator,s.nodeName=e;return o.addComponent(new exports.TimeoutNode).timeoutDuration=t,this.currentEntity=o,this}wait(e,t="Wait"){const o=this.scene.createEntity(t);this.currentEntity.addChild(o);const s=o.addComponent(new exports.BehaviorTreeNode);s.nodeType=exports.NodeType.Action,s.nodeName=t;return o.addComponent(new exports.WaitAction).waitTime=e,this}log(e,t="log",o="Log"){const s=this.scene.createEntity(o);this.currentEntity.addChild(s);const r=s.addComponent(new exports.BehaviorTreeNode);r.nodeType=exports.NodeType.Action,r.nodeName=o;const i=s.addComponent(new exports.LogAction);return i.message=e,i.level=t,this}setBlackboardValue(e,t,o="SetValue"){const s=this.scene.createEntity(o);this.currentEntity.addChild(s);const r=s.addComponent(new exports.BehaviorTreeNode);r.nodeType=exports.NodeType.Action,r.nodeName=o;const i=s.addComponent(new exports.SetBlackboardValueAction);return i.variableName=e,i.value=t,this}modifyBlackboardValue(e,t,o,s="ModifyValue"){const r=this.scene.createEntity(s);this.currentEntity.addChild(r);const i=r.addComponent(new exports.BehaviorTreeNode);i.nodeType=exports.NodeType.Action,i.nodeName=s;const n=r.addComponent(new exports.ModifyBlackboardValueAction);return n.variableName=e,n.operation=t,n.operand=o,this}action(e,t){const o=this.scene.createEntity(e);this.currentEntity.addChild(o);const s=o.addComponent(new exports.BehaviorTreeNode);s.nodeType=exports.NodeType.Action,s.nodeName=e;return o.addComponent(new exports.ExecuteAction).setFunction(t),this}compareBlackboardValue(e,t,o,s="Compare"){const r=this.scene.createEntity(s);this.currentEntity.addChild(r);const i=r.addComponent(new exports.BehaviorTreeNode);i.nodeType=exports.NodeType.Condition,i.nodeName=s;const n=r.addComponent(new exports.BlackboardCompareCondition);return n.variableName=e,n.operator=t,n.compareValue=o,this}checkBlackboardExists(e,t=!1,o="Exists"){const s=this.scene.createEntity(o);this.currentEntity.addChild(s);const r=s.addComponent(new exports.BehaviorTreeNode);r.nodeType=exports.NodeType.Condition,r.nodeName=o;const i=s.addComponent(new exports.BlackboardExistsCondition);return i.variableName=e,i.checkNotNull=t,this}randomProbability(e,t="Random"){const o=this.scene.createEntity(t);this.currentEntity.addChild(o);const s=o.addComponent(new exports.BehaviorTreeNode);s.nodeType=exports.NodeType.Condition,s.nodeName=t;return o.addComponent(new exports.RandomProbabilityCondition).probability=e,this}condition(e,t="Condition"){const o=this.scene.createEntity(t);this.currentEntity.addChild(o);const s=o.addComponent(new exports.BehaviorTreeNode);s.nodeType=exports.NodeType.Condition,s.nodeName=t;return o.addComponent(new exports.ExecuteCondition).setFunction(e),this}end(){if(0===this.entityStack.length)throw new Error("No parent node to return to");return this.currentEntity=this.entityStack.pop(),this}build(){for(;this.entityStack.length>0;)this.currentEntity=this.entityStack.pop();return this.currentEntity}}exports.AssetLoadingManager=ce,exports.BehaviorNode=p,exports.BehaviorProperty=l,exports.BehaviorTreeAssetLoader=Q,exports.BehaviorTreeAssetSerializer=_,exports.BehaviorTreeAssetValidator=W,exports.BehaviorTreeBuilder=ue,exports.BehaviorTreePersistence=class{static serialize(e,t=!0){if(!e.hasComponent(exports.BehaviorTreeNode))throw new Error("Entity must have BehaviorTreeNode component");if(!e.scene)throw new Error("Entity must be attached to a scene");return n.SceneSerializer.serialize(e.scene,{format:"json",pretty:t,includeMetadata:!0})}static deserialize(e,t){n.SceneSerializer.deserialize(e,t,{strategy:"merge"})}static toJSON(e,t=!0){const o=this.serialize(e,t);return JSON.stringify(o,null,t?2:0)}static fromJSON(e,t){this.deserialize(e,t)}static async saveToFile(e,t){throw this.toJSON(e,!0),new Error("saveToFile requires Tauri environment. Use toJSON() for manual saving.")}static async loadFromFile(e,t){throw new Error("loadFromFile requires Tauri environment. Use fromJSON() for manual loading.")}static validate(e){try{const t=JSON.parse(e);if(!t||"object"!=typeof t)return!1;if(!t.name||"number"!=typeof t.version||!Array.isArray(t.entities)||!Array.isArray(t.componentTypeRegistry))return!1;return t.entities.some((e=>e.components.some((e=>"BehaviorTreeNode"===e.type))))}catch{return!1}}static clone(e,t){const o=this.serialize(t),s=e.entities.count;this.deserialize(e,o);const r=Array.from(e.entities.buffer);for(let e=r.length-1;e>=s;e--){const t=r[e];if(t.hasComponent(exports.BehaviorTreeNode)&&!t.parent)return t}throw new Error("Failed to find cloned root entity")}},exports.BehaviorTreePlugin=class{constructor(){this.name="@esengine/behavior-tree",this.version="1.0.0",this.worldManager=null,this.services=null}async install(e,t){this.services=t,t.registerSingleton(x),this.worldManager=t.resolve(n.WorldManager)}async uninstall(){this.services&&this.services.unregister(x),this.worldManager=null,this.services=null}setupScene(e){e.addSystem(new oe),e.addSystem(new se),e.addSystem(new re),e.addSystem(new pe)}setupAllScenes(){if(!this.worldManager)throw new Error("Plugin not installed");const e=this.worldManager.getAllWorlds();for(const t of e)for(const e of t.getAllScenes())this.setupScene(e)}},exports.BehaviorTreeStarter=class{static start(e){if(!e.hasComponent(exports.BehaviorTreeNode))throw new Error("Entity must have BehaviorTreeNode component");e.hasComponent(exports.ActiveNode)||e.addComponent(new exports.ActiveNode)}static stop(e){this.stopRecursive(e)}static stopRecursive(e){e.hasComponent(exports.ActiveNode)&&e.removeComponentByType(exports.ActiveNode);const t=e.getComponent(exports.BehaviorTreeNode);t&&t.reset();for(const t of e.children)this.stopRecursive(t)}static pause(e){this.pauseRecursive(e)}static pauseRecursive(e){e.hasComponent(exports.ActiveNode)&&e.removeComponentByType(exports.ActiveNode);for(const t of e.children)this.pauseRecursive(t)}static resume(e){this.resumeRecursive(e)}static resumeRecursive(e){const t=e.getComponent(exports.BehaviorTreeNode);if(t){t.status===exports.TaskStatus.Running&&(e.hasComponent(exports.ActiveNode)||e.addComponent(new exports.ActiveNode));for(const t of e.children)this.resumeRecursive(t)}}static restart(e){this.stop(e),this.start(e)}static isRunning(e){return e.hasComponent(exports.ActiveNode)}},exports.CircularDependencyError=ne,exports.CompositeExecutionSystem=re,exports.DecoratorExecutionSystem=se,exports.EditorFormatConverter=G,exports.EntityDestroyedError=ae,exports.FileSystemAssetLoader=X,exports.GlobalBlackboardService=x,exports.LeafExecutionSystem=oe,exports.NodeClassRegistry=c,exports.NodeProperty=u,exports.NodeTemplates=class{static getAllTemplates(){return h()}static getTemplate(e,t){return this.getAllTemplates().find((o=>{if(o.type!==e)return!1;const s=o.defaultConfig;switch(e){case exports.NodeType.Composite:return s.compositeType===t;case exports.NodeType.Decorator:return s.decoratorType===t;case exports.NodeType.Action:return s.actionType===t;case exports.NodeType.Condition:return s.conditionType===t;default:return!1}}))}},exports.PropertyBindings=g,exports.RootExecutionSystem=te,exports.SubTreeExecutionSystem=pe,exports.TimeoutError=ie,exports.WorkspaceService=class{constructor(){this.config=null,this.assetMap=new Map,this.assetPathMap=new Map}initialize(e){this.config=e,this.rebuildAssetMaps()}rebuildAssetMaps(){if(this.assetMap.clear(),this.assetPathMap.clear(),this.config)for(const e of this.config.assets)this.assetMap.set(e.id,e),this.assetPathMap.set(e.path,e)}getConfig(){return this.config}updateConfig(e){this.config=e,this.rebuildAssetMaps()}registerAsset(e){if(!this.config)throw new Error("工作区未初始化");const t=this.config.assets.find((t=>t.id===e.id));t?Object.assign(t,e):this.config.assets.push(e),this.rebuildAssetMaps()}unregisterAsset(e){if(!this.config)return;const t=this.config.assets.findIndex((t=>t.id===e));-1!==t&&(this.config.assets.splice(t,1),this.rebuildAssetMaps())}getAssetById(e){return this.assetMap.get(e)}getAssetByPath(e){return this.assetPathMap.get(e)}getAllAssets(){return this.config?.assets||[]}getAssetsByType(e){return this.getAllAssets().filter((t=>t.type===e))}getBehaviorTreeAssets(){return this.getAssetsByType(exports.AssetType.BehaviorTree)}getBlackboardAssets(){return this.getAssetsByType(exports.AssetType.Blackboard)}getAssetDependencies(e,t=new Set){if(t.has(e))return[];t.add(e);const o=this.getAssetById(e);if(!o)return[];const s=[];for(const e of o.dependencies){const o=this.getAssetById(e);o&&(s.push(o),s.push(...this.getAssetDependencies(e,t)))}return s}detectCircularDependency(e){const t=new Set,o=[],s=e=>{if(o.includes(e))return o.push(e),!0;if(t.has(e))return!1;t.add(e),o.push(e);const r=this.getAssetById(e);if(r)for(const e of r.dependencies)if(s(e))return!0;return o.pop(),!1};return s(e)?o:null}canAddDependency(e,t){const o=this.getAssetById(e);if(!o)return!1;const s=[...o.dependencies];o.dependencies.push(t);const r=null!==this.detectCircularDependency(e);return o.dependencies=s,!r}addAssetDependency(e,t){if(!this.canAddDependency(e,t))return!1;const o=this.getAssetById(e);return!!o&&(o.dependencies.includes(t)||o.dependencies.push(t),!0)}removeAssetDependency(e,t){const o=this.getAssetById(e);if(!o)return;const s=o.dependencies.indexOf(t);-1!==s&&o.dependencies.splice(s,1)}resolveAssetPath(e){return this.config?e.startsWith("/")||e.match(/^[A-Za-z]:/)?e:`${this.config.rootPath}/${e}`.replace(/\\/g,"/"):e}getRelativePath(e){if(!this.config)return e;const t=this.config.rootPath.replace(/\\/g,"/"),o=e.replace(/\\/g,"/");return o.startsWith(t)?o.substring(t.length+1):e}dispose(){this.config=null,this.assetMap.clear(),this.assetPathMap.clear()}},exports.clearRegisteredNodes=function(){c.clear()},exports.getRegisteredNodeTemplates=h;
|
|
1
|
+
"use strict";var e,t=require("@esengine/ecs-framework");exports.TaskStatus=void 0,(e=exports.TaskStatus||(exports.TaskStatus={}))[e.Invalid=0]="Invalid",e[e.Success=1]="Success",e[e.Failure=2]="Failure",e[e.Running=3]="Running";const r={Composite:"composite",Decorator:"decorator",Action:"action",Condition:"condition"};var o,s,a,n;function i(){return{status:exports.TaskStatus.Invalid,currentChildIndex:0}}function c(e,t,r,o){var s,a=arguments.length,n=a<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,o);else for(var i=e.length-1;i>=0;i--)(s=e[i])&&(n=(a<3?s(n):a>3?s(t,r,n):s(t,r))||n);return a>3&&n&&Object.defineProperty(t,r,n),n}function d(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}exports.CompositeType=void 0,(o=exports.CompositeType||(exports.CompositeType={})).Sequence="sequence",o.Selector="selector",o.Parallel="parallel",o.ParallelSelector="parallel-selector",o.RandomSequence="random-sequence",o.RandomSelector="random-selector",exports.DecoratorType=void 0,(s=exports.DecoratorType||(exports.DecoratorType={})).Inverter="inverter",s.Repeater="repeater",s.UntilSuccess="until-success",s.UntilFail="until-fail",s.AlwaysSucceed="always-succeed",s.AlwaysFail="always-fail",s.Conditional="conditional",s.Cooldown="cooldown",s.Timeout="timeout",exports.AbortType=void 0,(a=exports.AbortType||(exports.AbortType={})).None="none",a.Self="self",a.LowerPriority="lower-priority",a.Both="both",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","function"==typeof SuppressedError&&SuppressedError,exports.BehaviorTreeRuntimeComponent=class extends t.Component{constructor(){super(...arguments),this.treeAssetId="",this.autoStart=!0,this.isRunning=!1,this.nodeStates=new Map,this.blackboard=new Map,this.blackboardObservers=new Map,this.activeNodeIds=new Set,this.needsReset=!1,this.nodesToAbort=new Set}getNodeState(e){return this.nodeStates.has(e)||this.nodeStates.set(e,i()),this.nodeStates.get(e)}resetNodeState(e){const t=this.getNodeState(e);t.status=exports.TaskStatus.Invalid,t.currentChildIndex=0,delete t.startTime,delete t.lastExecutionTime,delete t.repeatCount,delete t.cachedResult,delete t.shuffledIndices,delete t.isAborted,delete t.lastConditionResult,delete t.observedKeys}resetAllStates(){this.nodeStates.clear(),this.activeNodeIds.clear()}getBlackboardValue(e){return this.blackboard.get(e)}setBlackboardValue(e,t){const r=this.blackboard.get(e);this.blackboard.set(e,t),r!==t&&this.notifyBlackboardChange(e,t,r)}hasBlackboardKey(e){return this.blackboard.has(e)}initializeBlackboard(e){e&&e.forEach(((e,t)=>{this.blackboard.has(t)||this.blackboard.set(t,e)}))}clearBlackboard(){this.blackboard.clear()}start(){this.isRunning=!0,this.resetAllStates()}stop(){this.isRunning=!1,this.activeNodeIds.clear()}pause(){this.isRunning=!1}resume(){this.isRunning=!0}observeBlackboard(e,t,r){const o={nodeId:e,keys:new Set(t),callback:r};for(const e of t)this.blackboardObservers.has(e)||this.blackboardObservers.set(e,[]),this.blackboardObservers.get(e).push(o)}unobserveBlackboard(e){for(const t of this.blackboardObservers.values()){const r=t.findIndex((t=>t.nodeId===e));-1!==r&&t.splice(r,1)}}notifyBlackboardChange(e,t,r){const o=this.blackboardObservers.get(e);if(o)for(const s of o)try{s.callback(e,t,r)}catch(e){console.error(`黑板观察者回调错误 (节点: ${s.nodeId}):`,e)}}requestAbort(e){this.nodesToAbort.add(e)}shouldAbort(e){return this.nodesToAbort.has(e)}clearAbortRequest(e){this.nodesToAbort.delete(e)}clearAllAbortRequests(){this.nodesToAbort.clear()}},c([t.Serialize(),d("design:type",String)],exports.BehaviorTreeRuntimeComponent.prototype,"treeAssetId",void 0),c([t.Serialize(),d("design:type",Boolean)],exports.BehaviorTreeRuntimeComponent.prototype,"autoStart",void 0),c([t.IgnoreSerialization(),d("design:type",Boolean)],exports.BehaviorTreeRuntimeComponent.prototype,"isRunning",void 0),c([t.IgnoreSerialization(),d("design:type",Map)],exports.BehaviorTreeRuntimeComponent.prototype,"nodeStates",void 0),c([t.IgnoreSerialization(),d("design:type",Map)],exports.BehaviorTreeRuntimeComponent.prototype,"blackboard",void 0),c([t.IgnoreSerialization(),d("design:type",Map)],exports.BehaviorTreeRuntimeComponent.prototype,"blackboardObservers",void 0),c([t.IgnoreSerialization(),d("design:type",Set)],exports.BehaviorTreeRuntimeComponent.prototype,"activeNodeIds",void 0),c([t.IgnoreSerialization(),d("design:type",Boolean)],exports.BehaviorTreeRuntimeComponent.prototype,"needsReset",void 0),c([t.IgnoreSerialization(),d("design:type",Set)],exports.BehaviorTreeRuntimeComponent.prototype,"nodesToAbort",void 0),exports.BehaviorTreeRuntimeComponent=c([t.ECSComponent("BehaviorTreeRuntime"),t.Serializable({version:1})],exports.BehaviorTreeRuntimeComponent);const l=t.createLogger("BehaviorTreeAssetManager");class u{constructor(){this.assets=new Map}loadAsset(e){this.assets.has(e.id)&&l.warn(`行为树资产已存在,将被覆盖: ${e.id}`),this.assets.set(e.id,e),l.info(`行为树资产已加载: ${e.name} (${e.nodes.size}个节点)`)}getAsset(e){return this.assets.get(e)}hasAsset(e){return this.assets.has(e)}unloadAsset(e){const t=this.assets.delete(e);return t&&l.info(`行为树资产已卸载: ${e}`),t}clearAll(){this.assets.clear(),l.info("所有行为树资产已清空")}getAssetCount(){return this.assets.size}getAllAssetIds(){return Array.from(this.assets.keys())}dispose(){this.clearAll()}}class p{static getValue(e,t,r){const{nodeData:o,runtime:s}=e;if(o.bindings&&o.bindings[t]){const e=o.bindings[t],a=s.getBlackboardValue(e);return void 0!==a?a:r}const a=o.config[t];return void 0!==a?a:r}static hasBinding(e,t){return!(!e.nodeData.bindings||!e.nodeData.bindings[t])}static getBindingKey(e,t){return e.nodeData.bindings?.[t]}}class h{constructor(){this.executors=new Map}register(e,t){this.executors.has(e)&&console.warn(`执行器已存在,将被覆盖: ${e}`),this.executors.set(e,t)}get(e){return this.executors.get(e)}has(e){return this.executors.has(e)}unregister(e){return this.executors.delete(e)}clear(){this.executors.clear()}}class m{static register(e,t){this.metadataMap.set(t.implementationType,t),this.executorClassMap.set(e,t.implementationType),this.executorConstructors.set(t.implementationType,e)}static getMetadata(e){return this.metadataMap.get(e)}static getAllMetadata(){return Array.from(this.metadataMap.values())}static getByCategory(e){return this.getAllMetadata().filter((t=>t.category===e))}static getByNodeType(e){return this.getAllMetadata().filter((t=>t.nodeType===e))}static getImplementationType(e){return this.executorClassMap.get(e)}static getExecutorConstructor(e){return this.executorConstructors.get(e)}static getAllExecutorConstructors(){return new Map(this.executorConstructors)}}function g(e){return function(t){m.register(t,e)}}m.metadataMap=new Map,m.executorClassMap=new Map,m.executorConstructors=new Map,exports.SequenceExecutor=class{execute(e){const{nodeData:t,state:r}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Success;for(;r.currentChildIndex<t.children.length;){const o=t.children[r.currentChildIndex],s=e.executeChild(o);if(s===exports.TaskStatus.Running)return exports.TaskStatus.Running;if(s===exports.TaskStatus.Failure)return r.currentChildIndex=0,exports.TaskStatus.Failure;r.currentChildIndex++}return r.currentChildIndex=0,exports.TaskStatus.Success}reset(e){e.state.currentChildIndex=0}},exports.SequenceExecutor=c([g({implementationType:"Sequence",nodeType:r.Composite,displayName:"序列",description:"按顺序执行子节点,全部成功才成功",category:"Composite"})],exports.SequenceExecutor),exports.SelectorExecutor=class{execute(e){const{nodeData:t,state:r}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Failure;for(;r.currentChildIndex<t.children.length;){const o=t.children[r.currentChildIndex],s=e.executeChild(o);if(s===exports.TaskStatus.Running)return exports.TaskStatus.Running;if(s===exports.TaskStatus.Success)return r.currentChildIndex=0,exports.TaskStatus.Success;r.currentChildIndex++}return r.currentChildIndex=0,exports.TaskStatus.Failure}reset(e){e.state.currentChildIndex=0}},exports.SelectorExecutor=c([g({implementationType:"Selector",nodeType:r.Composite,displayName:"选择器",description:"按顺序执行子节点,任一成功则成功",category:"Composite"})],exports.SelectorExecutor),exports.ParallelExecutor=class{execute(e){const{nodeData:t}=e,r=p.getValue(e,"successPolicy","all"),o=p.getValue(e,"failurePolicy","one");if(!t.children||0===t.children.length)return exports.TaskStatus.Success;let s=!1,a=0,n=0;for(const r of t.children){const t=e.executeChild(r);t===exports.TaskStatus.Running?s=!0:t===exports.TaskStatus.Success?a++:t===exports.TaskStatus.Failure&&n++}return"one"===r&&a>0?(this.stopAllChildren(e),exports.TaskStatus.Success):"all"===r&&a===t.children.length?exports.TaskStatus.Success:"one"===o&&n>0?(this.stopAllChildren(e),exports.TaskStatus.Failure):"all"===o&&n===t.children.length?exports.TaskStatus.Failure:s?exports.TaskStatus.Running:exports.TaskStatus.Success}stopAllChildren(e){const{nodeData:t,runtime:r}=e;if(t.children)for(const e of t.children)r.activeNodeIds.delete(e),r.resetNodeState(e)}reset(e){const{nodeData:t,runtime:r}=e;if(t.children)for(const e of t.children)r.resetNodeState(e)}},exports.ParallelExecutor=c([g({implementationType:"Parallel",nodeType:r.Composite,displayName:"并行",description:"同时执行所有子节点",category:"Composite",configSchema:{successPolicy:{type:"string",default:"all",description:"成功策略",options:["all","one"]},failurePolicy:{type:"string",default:"one",description:"失败策略",options:["all","one"]}}})],exports.ParallelExecutor),exports.ParallelSelectorExecutor=class{execute(e){const{nodeData:t}=e,r=p.getValue(e,"failurePolicy","all");if(!t.children||0===t.children.length)return exports.TaskStatus.Failure;let o=!1,s=0,a=0;for(const r of t.children){const t=e.executeChild(r);t===exports.TaskStatus.Running?o=!0:t===exports.TaskStatus.Success?s++:t===exports.TaskStatus.Failure&&a++}return s>0?(this.stopAllChildren(e),exports.TaskStatus.Success):"one"===r&&a>0?(this.stopAllChildren(e),exports.TaskStatus.Failure):"all"===r&&a===t.children.length?exports.TaskStatus.Failure:o?exports.TaskStatus.Running:exports.TaskStatus.Failure}stopAllChildren(e){const{nodeData:t,runtime:r}=e;if(t.children)for(const e of t.children)r.activeNodeIds.delete(e),r.resetNodeState(e)}reset(e){const{nodeData:t,runtime:r}=e;if(t.children)for(const e of t.children)r.resetNodeState(e)}},exports.ParallelSelectorExecutor=c([g({implementationType:"ParallelSelector",nodeType:r.Composite,displayName:"并行选择器",description:"并行执行子节点,任一成功则成功",category:"Composite",configSchema:{failurePolicy:{type:"string",default:"all",description:"失败策略",options:["all","one"]}}})],exports.ParallelSelectorExecutor),exports.RandomSequenceExecutor=class{execute(e){const{nodeData:t,state:r}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Success;for(r.shuffledIndices&&0!==r.shuffledIndices.length||(r.shuffledIndices=this.shuffleIndices(t.children.length));r.currentChildIndex<r.shuffledIndices.length;){const o=r.shuffledIndices[r.currentChildIndex],s=t.children[o],a=e.executeChild(s);if(a===exports.TaskStatus.Running)return exports.TaskStatus.Running;if(a===exports.TaskStatus.Failure)return r.currentChildIndex=0,delete r.shuffledIndices,exports.TaskStatus.Failure;r.currentChildIndex++}return r.currentChildIndex=0,delete r.shuffledIndices,exports.TaskStatus.Success}shuffleIndices(e){const t=Array.from({length:e},((e,t)=>t));for(let e=t.length-1;e>0;e--){const r=Math.floor(Math.random()*(e+1)),o=t[e];t[e]=t[r],t[r]=o}return t}reset(e){e.state.currentChildIndex=0,delete e.state.shuffledIndices}},exports.RandomSequenceExecutor=c([g({implementationType:"RandomSequence",nodeType:r.Composite,displayName:"随机序列",description:"随机顺序执行子节点,全部成功才成功",category:"Composite"})],exports.RandomSequenceExecutor),exports.RandomSelectorExecutor=class{execute(e){const{nodeData:t,state:r}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Failure;for(r.shuffledIndices&&0!==r.shuffledIndices.length||(r.shuffledIndices=this.shuffleIndices(t.children.length));r.currentChildIndex<r.shuffledIndices.length;){const o=r.shuffledIndices[r.currentChildIndex],s=t.children[o],a=e.executeChild(s);if(a===exports.TaskStatus.Running)return exports.TaskStatus.Running;if(a===exports.TaskStatus.Success)return r.currentChildIndex=0,delete r.shuffledIndices,exports.TaskStatus.Success;r.currentChildIndex++}return r.currentChildIndex=0,delete r.shuffledIndices,exports.TaskStatus.Failure}shuffleIndices(e){const t=Array.from({length:e},((e,t)=>t));for(let e=t.length-1;e>0;e--){const r=Math.floor(Math.random()*(e+1)),o=t[e];t[e]=t[r],t[r]=o}return t}reset(e){e.state.currentChildIndex=0,delete e.state.shuffledIndices}},exports.RandomSelectorExecutor=c([g({implementationType:"RandomSelector",nodeType:r.Composite,displayName:"随机选择器",description:"随机顺序执行子节点,任一成功则成功",category:"Composite"})],exports.RandomSelectorExecutor),exports.InverterExecutor=class{execute(e){const{nodeData:t}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Failure;const r=t.children[0],o=e.executeChild(r);return o===exports.TaskStatus.Running?exports.TaskStatus.Running:o===exports.TaskStatus.Success?exports.TaskStatus.Failure:o===exports.TaskStatus.Failure?exports.TaskStatus.Success:exports.TaskStatus.Failure}reset(e){e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}},exports.InverterExecutor=c([g({implementationType:"Inverter",nodeType:r.Decorator,displayName:"反转",description:"反转子节点的执行结果",category:"Decorator"})],exports.InverterExecutor),exports.RepeaterExecutor=class{execute(e){const{nodeData:t,state:r,runtime:o}=e,s=p.getValue(e,"repeatCount",1),a=p.getValue(e,"endOnFailure",!1);if(!t.children||0===t.children.length)return exports.TaskStatus.Success;const n=t.children[0];r.repeatCount||(r.repeatCount=0);const i=e.executeChild(n);if(i===exports.TaskStatus.Running)return exports.TaskStatus.Running;if(i===exports.TaskStatus.Failure&&a)return r.repeatCount=0,exports.TaskStatus.Failure;r.repeatCount++,o.resetNodeState(n);return-1===s||r.repeatCount<s?exports.TaskStatus.Running:(r.repeatCount=0,exports.TaskStatus.Success)}reset(e){delete e.state.repeatCount,e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}},exports.RepeaterExecutor=c([g({implementationType:"Repeater",nodeType:r.Decorator,displayName:"重复",description:"重复执行子节点指定次数",category:"Decorator",configSchema:{repeatCount:{type:"number",default:1,description:"重复次数(-1表示无限循环)",supportBinding:!0},endOnFailure:{type:"boolean",default:!1,description:"子节点失败时是否结束"}}})],exports.RepeaterExecutor),exports.AlwaysSucceedExecutor=class{execute(e){const{nodeData:t}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Success;const r=t.children[0];return e.executeChild(r)===exports.TaskStatus.Running?exports.TaskStatus.Running:exports.TaskStatus.Success}reset(e){e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}},exports.AlwaysSucceedExecutor=c([g({implementationType:"AlwaysSucceed",nodeType:r.Decorator,displayName:"总是成功",description:"无论子节点结果如何都返回成功",category:"Decorator"})],exports.AlwaysSucceedExecutor),exports.AlwaysFailExecutor=class{execute(e){const{nodeData:t}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Failure;const r=t.children[0];return e.executeChild(r)===exports.TaskStatus.Running?exports.TaskStatus.Running:exports.TaskStatus.Failure}reset(e){e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}},exports.AlwaysFailExecutor=c([g({implementationType:"AlwaysFail",nodeType:r.Decorator,displayName:"总是失败",description:"无论子节点结果如何都返回失败",category:"Decorator"})],exports.AlwaysFailExecutor),exports.UntilSuccessExecutor=class{execute(e){const{nodeData:t,runtime:r}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Failure;const o=t.children[0],s=e.executeChild(o);return s===exports.TaskStatus.Running?exports.TaskStatus.Running:s===exports.TaskStatus.Success?exports.TaskStatus.Success:(r.resetNodeState(o),exports.TaskStatus.Running)}reset(e){e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}},exports.UntilSuccessExecutor=c([g({implementationType:"UntilSuccess",nodeType:r.Decorator,displayName:"直到成功",description:"重复执行子节点直到成功",category:"Decorator"})],exports.UntilSuccessExecutor),exports.UntilFailExecutor=class{execute(e){const{nodeData:t,runtime:r}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Success;const o=t.children[0],s=e.executeChild(o);return s===exports.TaskStatus.Running?exports.TaskStatus.Running:s===exports.TaskStatus.Failure?exports.TaskStatus.Failure:(r.resetNodeState(o),exports.TaskStatus.Running)}reset(e){e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}},exports.UntilFailExecutor=c([g({implementationType:"UntilFail",nodeType:r.Decorator,displayName:"直到失败",description:"重复执行子节点直到失败",category:"Decorator"})],exports.UntilFailExecutor),exports.ConditionalExecutor=class{execute(e){const{nodeData:t,runtime:r,state:o}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Failure;const s=p.getValue(e,"blackboardKey",""),a=p.getValue(e,"expectedValue"),n=p.getValue(e,"operator","equals"),i=t.abortType||exports.AbortType.None;if(!s)return exports.TaskStatus.Failure;const c=r.getBlackboardValue(s),d=this.evaluateCondition(c,a,n),l=o.status===exports.TaskStatus.Running;if(i!==exports.AbortType.None&&(o.observedKeys&&0!==o.observedKeys.length||(o.observedKeys=[s],this.setupObserver(e,s,a,n,i)),void 0!==o.lastConditionResult&&o.lastConditionResult!==d&&(d?this.handleConditionBecameTrue(e,i):l&&this.handleConditionBecameFalse(e,i))),o.lastConditionResult=d,!d)return exports.TaskStatus.Failure;const u=t.children[0];return e.executeChild(u)}evaluateCondition(e,t,r){switch(r){case"equals":return e===t;case"notEquals":return e!==t;case"greaterThan":return e>t;case"lessThan":return e<t;case"greaterOrEqual":return e>=t;case"lessOrEqual":return e<=t;default:return!1}}setupObserver(e,t,r,o,s){const{nodeData:a,runtime:n}=e;n.observeBlackboard(a.id,[t],((t,a)=>{const n=this.evaluateCondition(a,r,o),i=e.state.lastConditionResult;void 0!==i&&i!==n&&(n?this.handleConditionBecameTrue(e,s):this.handleConditionBecameFalse(e,s)),e.state.lastConditionResult=n}))}handleConditionBecameTrue(e,t){t!==exports.AbortType.LowerPriority&&t!==exports.AbortType.Both||this.requestAbortLowerPriority(e)}handleConditionBecameFalse(e,t){const{nodeData:r,runtime:o}=e;t!==exports.AbortType.Self&&t!==exports.AbortType.Both||r.children&&r.children.length>0&&o.requestAbort(r.children[0])}requestAbortLowerPriority(e){const{runtime:t}=e;t.requestAbort("__lower_priority__")}reset(e){const{nodeData:t,runtime:r,state:o}=e;o.observedKeys&&o.observedKeys.length>0&&(r.unobserveBlackboard(t.id),delete o.observedKeys),delete o.lastConditionResult,t.children&&t.children.length>0&&r.resetNodeState(t.children[0])}},exports.ConditionalExecutor=c([g({implementationType:"Conditional",nodeType:r.Decorator,displayName:"条件",description:"根据条件决定是否执行子节点",category:"Decorator",configSchema:{blackboardKey:{type:"string",default:"",description:"黑板变量名"},expectedValue:{type:"object",description:"期望值",supportBinding:!0},operator:{type:"string",default:"equals",description:"比较运算符",options:["equals","notEquals","greaterThan","lessThan","greaterOrEqual","lessOrEqual"]},abortType:{type:"string",default:"none",description:"中止类型",options:["none","self","lower-priority","both"]}}})],exports.ConditionalExecutor),exports.CooldownExecutor=class{execute(e){const{nodeData:t,state:r,totalTime:o}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Failure;const s=p.getValue(e,"cooldownTime",1);if(void 0!==r.lastExecutionTime){if(o-r.lastExecutionTime<s)return exports.TaskStatus.Failure}const a=t.children[0],n=e.executeChild(a);return n===exports.TaskStatus.Running?exports.TaskStatus.Running:n===exports.TaskStatus.Success?(r.lastExecutionTime=o,exports.TaskStatus.Success):exports.TaskStatus.Failure}reset(e){delete e.state.lastExecutionTime,e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}},exports.CooldownExecutor=c([g({implementationType:"Cooldown",nodeType:r.Decorator,displayName:"冷却",description:"子节点执行成功后进入冷却时间",category:"Decorator",configSchema:{cooldownTime:{type:"number",default:1,description:"冷却时间(秒)",min:0,supportBinding:!0}}})],exports.CooldownExecutor),exports.TimeoutExecutor=class{execute(e){const{nodeData:t,state:r,totalTime:o}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Failure;const s=p.getValue(e,"timeout",1);void 0===r.startTime&&(r.startTime=o);if(o-r.startTime>=s)return delete r.startTime,exports.TaskStatus.Failure;const a=t.children[0],n=e.executeChild(a);return n===exports.TaskStatus.Running?exports.TaskStatus.Running:(delete r.startTime,n)}reset(e){delete e.state.startTime,e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}},exports.TimeoutExecutor=c([g({implementationType:"Timeout",nodeType:r.Decorator,displayName:"超时",description:"限制子节点的执行时间",category:"Decorator",configSchema:{timeout:{type:"number",default:1,description:"超时时间(秒)",min:0,supportBinding:!0}}})],exports.TimeoutExecutor);class x{static register(e,t){this.services.set(e,t)}static get(e){return this.services.get(e)}static has(e){return this.services.has(e)}static unregister(e){return this.services.delete(e)}}x.services=new Map,exports.ServiceDecorator=class{execute(e){const{nodeData:t,state:r,totalTime:o}=e;if(!t.children||0===t.children.length)return exports.TaskStatus.Failure;const s=p.getValue(e,"serviceName",""),a=p.getValue(e,"tickInterval",0);if(!s)return exports.TaskStatus.Failure;const n=x.get(s);if(!n)return console.warn(`未找到Service: ${s}`),exports.TaskStatus.Failure;r.status!==exports.TaskStatus.Running&&(r.startTime=o,r.lastExecutionTime=o,n.onServiceStart&&n.onServiceStart(e));(0===a||void 0!==r.lastExecutionTime&&o-r.lastExecutionTime>=a)&&(n.onServiceTick(e),r.lastExecutionTime=o);const i=t.children[0],c=e.executeChild(i);return c!==exports.TaskStatus.Running&&n.onServiceEnd&&n.onServiceEnd(e),c}reset(e){const{nodeData:t,runtime:r,state:o}=e,s=p.getValue(e,"serviceName","");if(s){const t=x.get(s);t&&t.onServiceEnd&&t.onServiceEnd(e)}delete o.startTime,delete o.lastExecutionTime,t.children&&t.children.length>0&&r.resetNodeState(t.children[0])}},exports.ServiceDecorator=c([g({implementationType:"Service",nodeType:r.Decorator,displayName:"Service",description:"在子节点执行期间持续运行后台逻辑",category:"Decorator",configSchema:{serviceName:{type:"string",default:"",description:"Service名称"},tickInterval:{type:"number",default:0,description:"Service更新间隔(秒,0表示每帧更新)",supportBinding:!0}}})],exports.ServiceDecorator),exports.WaitAction=class{execute(e){const{state:t,totalTime:r}=e,o=p.getValue(e,"duration",1);return t.startTime?r-t.startTime>=o?exports.TaskStatus.Success:exports.TaskStatus.Running:(t.startTime=r,exports.TaskStatus.Running)}reset(e){delete e.state.startTime}},exports.WaitAction=c([g({implementationType:"Wait",nodeType:r.Action,displayName:"等待",description:"等待指定时间后返回成功",category:"Action",configSchema:{duration:{type:"number",default:1,description:"等待时长(秒)",min:0,supportBinding:!0}}})],exports.WaitAction),exports.LogAction=class{execute(e){const{runtime:t}=e,r=p.getValue(e,"message",""),o=p.getValue(e,"logLevel","info"),s=this.replaceBlackboardVariables(r,t);return this.log(s,o),exports.TaskStatus.Success}replaceBlackboardVariables(e,t){return e.includes("{")&&e.includes("}")?e.replace(/\{([\w.]{1,100})\}/g,((e,r)=>{const o=t.getBlackboardValue(r.trim());return void 0!==o?String(o):`{${r}}`})):e}log(e,t){switch(t){case"error":console.error(e);break;case"warn":console.warn(e);break;default:console.log(e)}}},exports.LogAction=c([g({implementationType:"Log",nodeType:r.Action,displayName:"日志",description:"输出日志信息",category:"Action",configSchema:{message:{type:"string",default:"",description:"日志消息,支持{key}占位符引用黑板变量",supportBinding:!0},logLevel:{type:"string",default:"info",description:"日志级别",options:["info","warn","error"]}}})],exports.LogAction),exports.SetBlackboardValue=class{execute(e){const{runtime:t}=e,r=p.getValue(e,"key",""),o=p.getValue(e,"value");return r?(t.setBlackboardValue(r,o),exports.TaskStatus.Success):exports.TaskStatus.Failure}},exports.SetBlackboardValue=c([g({implementationType:"SetBlackboardValue",nodeType:r.Action,displayName:"设置黑板值",description:"设置黑板中的变量值",category:"Action",configSchema:{key:{type:"string",default:"",description:"黑板变量名"},value:{type:"object",description:"要设置的值",supportBinding:!0}}})],exports.SetBlackboardValue),exports.ModifyBlackboardValue=class{execute(e){const{runtime:t}=e,r=p.getValue(e,"key",""),o=p.getValue(e,"operation","add"),s=p.getValue(e,"value",0);if(!r)return exports.TaskStatus.Failure;const a=t.getBlackboardValue(r)||0;let n;switch(o){case"add":n=a+s;break;case"subtract":n=a-s;break;case"multiply":n=a*s;break;case"divide":n=0!==s?a/s:a;break;case"set":n=s;break;default:return exports.TaskStatus.Failure}return t.setBlackboardValue(r,n),exports.TaskStatus.Success}},exports.ModifyBlackboardValue=c([g({implementationType:"ModifyBlackboardValue",nodeType:r.Action,displayName:"修改黑板值",description:"对黑板中的数值进行运算",category:"Action",configSchema:{key:{type:"string",default:"",description:"黑板变量名"},operation:{type:"string",default:"add",description:"运算类型",options:["add","subtract","multiply","divide","set"]},value:{type:"number",default:0,description:"操作数",supportBinding:!0}}})],exports.ModifyBlackboardValue),exports.ExecuteAction=class{execute(e){const{runtime:t,entity:r}=e,o=p.getValue(e,"actionName","");if(!o)return exports.TaskStatus.Failure;const s=t.getBlackboardValue(`action_${o}`);if(!s||"function"!=typeof s)return exports.TaskStatus.Failure;try{return s(r)}catch(e){return console.error(`ExecuteAction failed: ${e}`),exports.TaskStatus.Failure}}},exports.ExecuteAction=c([g({implementationType:"ExecuteAction",nodeType:r.Action,displayName:"执行动作",description:"执行自定义动作逻辑",category:"Action",configSchema:{actionName:{type:"string",default:"",description:"动作名称(黑板中action_前缀的函数)"}}})],exports.ExecuteAction),exports.SubTreeExecutor=class{constructor(){this.assetManager=null}getAssetManager(){return this.assetManager||(this.assetManager=t.Core.services.resolve(u)),this.assetManager}execute(e){const{runtime:t,state:r,entity:o}=e,s=p.getValue(e,"treeAssetId",""),a=p.getValue(e,"shareBlackboard",!0);if(!s)return exports.TaskStatus.Failure;const n=this.getAssetManager().getAsset(s);if(!n)return console.warn(`未找到子树资产: ${s}`),exports.TaskStatus.Failure;const i=n.nodes.get(n.rootNodeId);if(!i)return console.warn(`子树根节点未找到: ${n.rootNodeId}`),exports.TaskStatus.Failure;if(!a&&r.status!==exports.TaskStatus.Running&&n.blackboardVariables)for(const[e,r]of n.blackboardVariables.entries())t.hasBlackboardKey(e)||t.setBlackboardValue(e,r);const c={entity:o,nodeData:i,state:t.getNodeState(i.id),runtime:t,treeData:n,deltaTime:e.deltaTime,totalTime:e.totalTime,executeChild:r=>{const s=n.nodes.get(r);if(!s)return console.warn(`子树节点未找到: ${r}`),exports.TaskStatus.Failure;const a={entity:o,nodeData:s,state:t.getNodeState(r),runtime:t,treeData:n,deltaTime:e.deltaTime,totalTime:e.totalTime,executeChild:c.executeChild};return this.executeSubTreeNode(a)}};return this.executeSubTreeNode(c)}executeSubTreeNode(e){const{nodeData:t,runtime:r}=e,o=r.getNodeState(t.id);if(!t.children||0===t.children.length)return exports.TaskStatus.Success;const s=t.children[o.currentChildIndex],a=e.executeChild(s);return a===exports.TaskStatus.Running?exports.TaskStatus.Running:a===exports.TaskStatus.Failure?(o.currentChildIndex=0,exports.TaskStatus.Failure):(o.currentChildIndex++,o.currentChildIndex>=t.children.length?(o.currentChildIndex=0,exports.TaskStatus.Success):exports.TaskStatus.Running)}reset(e){const t=p.getValue(e,"treeAssetId","");if(t){const r=this.getAssetManager().getAsset(t);if(r){const t=r.nodes.get(r.rootNodeId);if(t&&(e.runtime.resetNodeState(t.id),t.children))for(const r of t.children)e.runtime.resetNodeState(r)}}}},exports.SubTreeExecutor=c([g({implementationType:"SubTree",nodeType:r.Action,displayName:"子树",description:"引用并执行其他行为树",category:"Special",configSchema:{treeAssetId:{type:"string",default:"",description:"要执行的行为树资产ID",supportBinding:!0},shareBlackboard:{type:"boolean",default:!0,description:"是否共享黑板数据"}}})],exports.SubTreeExecutor),exports.BlackboardCompare=class{execute(e){const{runtime:t}=e,r=p.getValue(e,"key",""),o=p.getValue(e,"compareValue"),s=p.getValue(e,"operator","equals");if(!r)return exports.TaskStatus.Failure;const a=t.getBlackboardValue(r);return this.compare(a,o,s)?exports.TaskStatus.Success:exports.TaskStatus.Failure}compare(e,t,r){switch(r){case"equals":return e===t;case"notEquals":return e!==t;case"greaterThan":return e>t;case"lessThan":return e<t;case"greaterOrEqual":return e>=t;case"lessOrEqual":return e<=t;default:return!1}}},exports.BlackboardCompare=c([g({implementationType:"BlackboardCompare",nodeType:r.Condition,displayName:"黑板比较",description:"比较黑板中的值",category:"Condition",configSchema:{key:{type:"string",default:"",description:"黑板变量名"},compareValue:{type:"object",description:"比较值",supportBinding:!0},operator:{type:"string",default:"equals",description:"比较运算符",options:["equals","notEquals","greaterThan","lessThan","greaterOrEqual","lessOrEqual"]}}})],exports.BlackboardCompare),exports.BlackboardExists=class{execute(e){const{runtime:t}=e,r=p.getValue(e,"key",""),o=p.getValue(e,"checkNull",!1);if(!r)return exports.TaskStatus.Failure;const s=t.getBlackboardValue(r);return void 0===s||o&&null===s?exports.TaskStatus.Failure:exports.TaskStatus.Success}},exports.BlackboardExists=c([g({implementationType:"BlackboardExists",nodeType:r.Condition,displayName:"黑板存在",description:"检查黑板中是否存在指定的键",category:"Condition",configSchema:{key:{type:"string",default:"",description:"黑板变量名"},checkNull:{type:"boolean",default:!1,description:"检查是否为null"}}})],exports.BlackboardExists),exports.RandomProbability=class{execute(e){const t=p.getValue(e,"probability",.5),r=Math.max(0,Math.min(1,t));return Math.random()<r?exports.TaskStatus.Success:exports.TaskStatus.Failure}},exports.RandomProbability=c([g({implementationType:"RandomProbability",nodeType:r.Condition,displayName:"随机概率",description:"根据概率返回成功或失败",category:"Condition",configSchema:{probability:{type:"number",default:.5,description:"成功概率(0-1)",min:0,max:1,supportBinding:!0}}})],exports.RandomProbability),exports.ExecuteCondition=class{execute(e){const{runtime:t,entity:r}=e,o=p.getValue(e,"conditionName","");if(!o)return exports.TaskStatus.Failure;const s=t.getBlackboardValue(`condition_${o}`);if(!s||"function"!=typeof s)return exports.TaskStatus.Failure;try{return s(r)?exports.TaskStatus.Success:exports.TaskStatus.Failure}catch(e){return console.error(`ExecuteCondition failed: ${e}`),exports.TaskStatus.Failure}}},exports.ExecuteCondition=c([g({implementationType:"ExecuteCondition",nodeType:r.Condition,displayName:"执行条件",description:"执行自定义条件逻辑",category:"Condition",configSchema:{conditionName:{type:"string",default:"",description:"条件名称(黑板中condition_前缀的函数)"}}})],exports.ExecuteCondition),exports.BehaviorTreeExecutionSystem=class extends t.EntitySystem{constructor(){super(t.Matcher.empty().all(exports.BehaviorTreeRuntimeComponent)),this.assetManager=t.Core.services.resolve(u),this.executorRegistry=new h,this.registerBuiltInExecutors()}registerBuiltInExecutors(){const e=m.getAllExecutorConstructors();for(const[t,r]of e)try{const e=new r;this.executorRegistry.register(t,e)}catch(e){this.logger.error(`注册执行器失败: ${t}`,e)}}getExecutorRegistry(){return this.executorRegistry}process(e){for(const t of e){const e=t.getComponent(exports.BehaviorTreeRuntimeComponent);if(!e.isRunning)continue;const r=this.assetManager.getAsset(e.treeAssetId);r?(e.needsReset&&(e.resetAllStates(),e.needsReset=!1),this.executeTree(t,e,r)):this.logger.warn(`未找到行为树资产: ${e.treeAssetId}`)}}executeTree(e,t,r){const o=r.nodes.get(r.rootNodeId);if(!o)return void this.logger.error(`未找到根节点: ${r.rootNodeId}`);this.executeNode(e,t,o,r)!==exports.TaskStatus.Running?t.needsReset=!0:t.needsReset=!1}executeNode(e,t,r,o){const s=t.getNodeState(r.id);if(t.shouldAbort(r.id)){t.clearAbortRequest(r.id),s.isAborted=!0;const a=this.executorRegistry.get(r.implementationType);if(a&&a.reset){const s=this.createContext(e,t,r,o);a.reset(s)}return t.activeNodeIds.delete(r.id),s.status=exports.TaskStatus.Failure,exports.TaskStatus.Failure}t.activeNodeIds.add(r.id),s.isAborted=!1;const a=this.executorRegistry.get(r.implementationType);if(!a)return this.logger.error(`未找到执行器: ${r.implementationType}`),s.status=exports.TaskStatus.Failure,exports.TaskStatus.Failure;const n=this.createContext(e,t,r,o);try{const e=a.execute(n);return s.status=e,e!==exports.TaskStatus.Running&&(t.activeNodeIds.delete(r.id),a.reset&&a.reset(n)),e}catch(e){return this.logger.error(`执行节点时发生错误: ${r.name}`,e),s.status=exports.TaskStatus.Failure,t.activeNodeIds.delete(r.id),exports.TaskStatus.Failure}}createContext(e,r,o,s){return{entity:e,nodeData:o,state:r.getNodeState(o.id),runtime:r,treeData:s,deltaTime:t.Time.deltaTime,totalTime:t.Time.totalTime,executeChild:t=>{const o=s.nodes.get(t);return o?this.executeNode(e,r,o,s):(this.logger.warn(`未找到子节点: ${t}`),exports.TaskStatus.Failure)}}}executeChildren(e,t){const{nodeData:r,treeData:o,entity:s,runtime:a}=e;if(!r.children||0===r.children.length)return[];const n=[],i=t||Array.from({length:r.children.length},((e,t)=>t));for(const e of i){if(e>=r.children.length)continue;const t=r.children[e],i=o.nodes.get(t);if(!i){this.logger.warn(`未找到子节点: ${t}`),n.push(exports.TaskStatus.Failure);continue}const c=this.executeNode(s,a,i,o);n.push(c)}return n}},exports.BehaviorTreeExecutionSystem=c([t.ECSSystem("BehaviorTreeExecution"),d("design:paramtypes",[])],exports.BehaviorTreeExecutionSystem);class y{constructor(e){this.nodeStack=[],this.nodeIdCounter=0,this.treeData={id:`tree_${Date.now()}`,name:e,rootNodeId:"",nodes:new Map,blackboardVariables:new Map}}static create(e="BehaviorTree"){return new y(e)}defineBlackboardVariable(e,t){return this.treeData.blackboardVariables||(this.treeData.blackboardVariables=new Map),this.treeData.blackboardVariables.set(e,t),this}sequence(e){return this.addCompositeNode("Sequence",e||"Sequence")}selector(e){return this.addCompositeNode("Selector",e||"Selector")}parallel(e,t){return this.addCompositeNode("Parallel",e||"Parallel",t)}parallelSelector(e,t){return this.addCompositeNode("ParallelSelector",e||"ParallelSelector",t)}randomSequence(e){return this.addCompositeNode("RandomSequence",e||"RandomSequence")}randomSelector(e){return this.addCompositeNode("RandomSelector",e||"RandomSelector")}inverter(e){return this.addDecoratorNode("Inverter",e||"Inverter")}repeater(e,t){return this.addDecoratorNode("Repeater",t||"Repeater",{repeatCount:e})}alwaysSucceed(e){return this.addDecoratorNode("AlwaysSucceed",e||"AlwaysSucceed")}alwaysFail(e){return this.addDecoratorNode("AlwaysFail",e||"AlwaysFail")}untilSuccess(e){return this.addDecoratorNode("UntilSuccess",e||"UntilSuccess")}untilFail(e){return this.addDecoratorNode("UntilFail",e||"UntilFail")}conditional(e,t,r,o){return this.addDecoratorNode("Conditional",o||"Conditional",{blackboardKey:e,expectedValue:t,operator:r||"equals"})}cooldown(e,t){return this.addDecoratorNode("Cooldown",t||"Cooldown",{cooldownTime:e})}timeout(e,t){return this.addDecoratorNode("Timeout",t||"Timeout",{timeout:e})}wait(e,t){return this.addActionNode("Wait",t||"Wait",{duration:e})}log(e,t){return this.addActionNode("Log",t||"Log",{message:e})}setBlackboardValue(e,t,r){return this.addActionNode("SetBlackboardValue",r||"SetBlackboardValue",{key:e,value:t})}modifyBlackboardValue(e,t,r,o){return this.addActionNode("ModifyBlackboardValue",o||"ModifyBlackboardValue",{key:e,operation:t,value:r})}executeAction(e,t){return this.addActionNode("ExecuteAction",t||"ExecuteAction",{actionName:e})}blackboardCompare(e,t,r,o){return this.addConditionNode("BlackboardCompare",o||"BlackboardCompare",{key:e,compareValue:t,operator:r||"equals"})}blackboardExists(e,t){return this.addConditionNode("BlackboardExists",t||"BlackboardExists",{key:e})}randomProbability(e,t){return this.addConditionNode("RandomProbability",t||"RandomProbability",{probability:e})}executeCondition(e,t){return this.addConditionNode("ExecuteCondition",t||"ExecuteCondition",{conditionName:e})}end(){return this.nodeStack.length>0&&this.nodeStack.pop(),this}build(){if(!this.treeData.rootNodeId)throw new Error("No root node defined. Add at least one node to the tree.");return this.treeData}addCompositeNode(e,t,o={}){const s=this.generateNodeId(),a={id:s,name:t,nodeType:r.Composite,implementationType:e,children:[],config:o};if(this.treeData.nodes.set(s,a),this.treeData.rootNodeId||(this.treeData.rootNodeId=s),this.nodeStack.length>0){const e=this.nodeStack[this.nodeStack.length-1],t=this.treeData.nodes.get(e);t&&t.children&&t.children.push(s)}return this.nodeStack.push(s),this}addDecoratorNode(e,t,o={}){const s=this.generateNodeId(),a={id:s,name:t,nodeType:r.Decorator,implementationType:e,children:[],config:o};if(this.treeData.nodes.set(s,a),this.treeData.rootNodeId||(this.treeData.rootNodeId=s),this.nodeStack.length>0){const e=this.nodeStack[this.nodeStack.length-1],t=this.treeData.nodes.get(e);t&&t.children&&t.children.push(s)}return this.nodeStack.push(s),this}addActionNode(e,t,o={}){const s=this.generateNodeId(),a={id:s,name:t,nodeType:r.Action,implementationType:e,config:o};if(this.treeData.nodes.set(s,a),this.treeData.rootNodeId||(this.treeData.rootNodeId=s),this.nodeStack.length>0){const e=this.nodeStack[this.nodeStack.length-1],t=this.treeData.nodes.get(e);t&&t.children&&t.children.push(s)}return this}addConditionNode(e,t,o={}){const s=this.generateNodeId(),a={id:s,name:t,nodeType:r.Condition,implementationType:e,config:o};if(this.treeData.nodes.set(s,a),this.treeData.rootNodeId||(this.treeData.rootNodeId=s),this.nodeStack.length>0){const e=this.nodeStack[this.nodeStack.length-1],t=this.treeData.nodes.get(e);t&&t.children&&t.children.push(s)}return this}generateNodeId(){return"node_"+this.nodeIdCounter++}}const S={String:"string",Number:"number",Boolean:"boolean",Select:"select",Blackboard:"blackboard",Code:"code",Variable:"variable",Asset:"asset"};class f{static validate(e){const t=[],r=[];if(e.version||t.push("Missing version field"),e.metadata&&e.metadata.name||t.push("Missing or invalid metadata"),e.rootNodeId||t.push("Missing rootNodeId"),e.nodes&&Array.isArray(e.nodes)){const o=new Set;e.nodes.find((t=>t.id===e.rootNodeId))||t.push(`Root node '${e.rootNodeId}' not found in nodes array`);for(const r of e.nodes)if(r.id){if(o.has(r.id)&&t.push(`Duplicate node id: ${r.id}`),o.add(r.id),r.nodeType||t.push(`Node ${r.id} missing nodeType`),r.children)for(const o of r.children)e.nodes.find((e=>e.id===o))||t.push(`Node ${r.id} references non-existent child: ${o}`)}else t.push("Node missing id field");const s=new Set([e.rootNodeId]),a=t=>{const r=e.nodes.find((e=>e.id===t));if(r&&r.children)for(const e of r.children)s.add(e),a(e)};a(e.rootNodeId);for(const t of e.nodes)s.has(t.id)||r.push(`Orphaned node detected: ${t.id} (${t.name})`)}else t.push("Missing or invalid nodes array");if(e.blackboard&&Array.isArray(e.blackboard)){const r=new Set;for(const o of e.blackboard)o.name?(r.has(o.name)&&t.push(`Duplicate blackboard variable: ${o.name}`),r.add(o.name),o.type||t.push(`Blackboard variable ${o.name} missing type`)):t.push("Blackboard variable missing name")}if(e.propertyBindings&&Array.isArray(e.propertyBindings)){const r=new Set(e.nodes.map((e=>e.id))),o=new Set(e.blackboard?.map((e=>e.name))||[]);for(const s of e.propertyBindings)r.has(s.nodeId)||t.push(`Property binding references non-existent node: ${s.nodeId}`),o.has(s.variableName)||t.push(`Property binding references non-existent variable: ${s.variableName}`),s.propertyName||t.push("Property binding missing propertyName")}const o={valid:0===t.length};return t.length>0&&(o.errors=t),r.length>0&&(o.warnings=r),o}static getStats(e){let t=0,o=0,s=0,a=0;for(const n of e.nodes)switch(n.nodeType){case r.Action:t++;break;case r.Condition:o++;break;case r.Composite:s++;break;case r.Decorator:a++}const n=(t,r=0)=>{const o=e.nodes.find((e=>e.id===t));if(!o||!o.children||0===o.children.length)return r;let s=r;for(const e of o.children){const t=n(e,r+1);s=Math.max(s,t)}return s};return{nodeCount:e.nodes.length,actionCount:t,conditionCount:o,compositeCount:s,decoratorCount:a,blackboardVariableCount:e.blackboard?.length||0,propertyBindingCount:e.propertyBindings?.length||0,maxDepth:n(e.rootNodeId)}}}const T=t.createLogger("EditorFormatConverter");class b{static toAsset(e,t){T.info("开始转换编辑器格式到资产格式");const r=this.findRootNode(e.nodes);if(!r)throw new Error("未找到根节点");const o={name:t?.name||e.metadata?.name||"Untitled Behavior Tree",version:t?.version||e.version||"1.0.0"},s=t?.description||e.metadata?.description;s&&(o.description=s);const a=t?.createdAt||e.metadata?.createdAt;a&&(o.createdAt=a);const n=t?.modifiedAt||(new Date).toISOString();n&&(o.modifiedAt=n);const i=this.convertNodes(e.nodes),c=this.convertBlackboard(e.blackboard),d=this.convertPropertyBindings(e.connections,e.nodes,c),l={version:"1.0.0",metadata:o,rootNodeId:r.id,nodes:i,blackboard:c};return d.length>0&&(l.propertyBindings=d),T.info(`转换完成: ${i.length}个节点, ${c.length}个黑板变量, ${d.length}个属性绑定`),l}static findRootNode(e){return e.find((e=>"根节点"===e.template.category||"root"===e.data.nodeType))||null}static convertNodes(e){return e.map((e=>this.convertNode(e)))}static convertNode(e){const t={...e.data};return delete t.nodeType,e.template.className&&(t.className=e.template.className),{id:e.id,name:e.template.displayName||e.data.name||"Node",nodeType:e.template.type,data:t,children:e.children||[]}}static convertBlackboard(e){const t=[];for(const[r,o]of Object.entries(e)){const e=this.inferBlackboardType(o);t.push({name:r,type:e,defaultValue:o})}return t}static inferBlackboardType(e){return"number"==typeof e?exports.BlackboardValueType.Number:"string"==typeof e?exports.BlackboardValueType.String:"boolean"==typeof e?exports.BlackboardValueType.Boolean:exports.BlackboardValueType.Object}static convertPropertyBindings(e,t,r){const o=[],s=new Set(r.map((e=>e.name))),a=e.filter((e=>"property"===e.connectionType));for(const e of a){const r=t.find((t=>t.id===e.from)),a=t.find((t=>t.id===e.to));if(!r||!a||!e.toProperty){T.warn(`跳过无效的属性连接: from=${e.from}, to=${e.to}`);continue}let n;"blackboard-variable"===r.data.nodeType?n=r.data.variableName:e.fromProperty&&(n=e.fromProperty),n?s.has(n)?o.push({nodeId:a.id,propertyName:e.toProperty,variableName:n}):T.warn(`属性绑定引用了不存在的黑板变量: ${n}`):T.warn(`无法确定变量名: from节点=${r.template.displayName}`)}return o}static fromAsset(e){T.info("开始转换资产格式到编辑器格式");const t=this.convertNodesFromAsset(e.nodes),r={};for(const t of e.blackboard)r[t.name]=t.defaultValue;const o=this.convertPropertyBindingsToConnections(e.propertyBindings||[]),s=this.buildNodeConnections(e.nodes);o.push(...s);const a={name:e.metadata.name};e.metadata.description&&(a.description=e.metadata.description),e.metadata.createdAt&&(a.createdAt=e.metadata.createdAt),e.metadata.modifiedAt&&(a.modifiedAt=e.metadata.modifiedAt);const n={version:e.metadata.version,metadata:a,nodes:t,connections:o,blackboard:r,canvasState:{offset:{x:0,y:0},scale:1}};return T.info(`转换完成: ${t.length}个节点, ${o.length}个连接`),n}static convertNodesFromAsset(e){return e.map(((e,t)=>{const r={x:100+t%5*250,y:100+150*Math.floor(t/5)},o={displayName:e.name,category:this.inferCategory(e.nodeType),type:e.nodeType};return e.data.className&&(o.className=e.data.className),{id:e.id,template:o,data:{...e.data},position:r,children:e.children}}))}static inferCategory(e){switch(e){case r.Action:return"动作";case r.Condition:return"条件";case r.Composite:return"组合";case r.Decorator:return"装饰器";default:return"其他"}}static convertPropertyBindingsToConnections(e){const t=[];for(const r of e)t.push({from:"blackboard",to:r.nodeId,toProperty:r.propertyName,connectionType:"property"});return t}static buildNodeConnections(e){const t=[];for(const r of e)for(const e of r.children)t.push({from:r.id,to:e,connectionType:"node"});return t}}const k=t.createLogger("BehaviorTreeAssetSerializer");class C{constructor(){this.variables=new Map}dispose(){this.variables.clear()}defineVariable(e,t,r,o){const s={name:e,type:t,value:r,readonly:o?.readonly??!1};void 0!==o?.description&&(s.description=o.description),this.variables.set(e,s)}getValue(e){const t=this.variables.get(e);return t?.value}setValue(e,t,r=!1){const o=this.variables.get(e);return!!o&&(!(o.readonly&&!r)&&(o.value=t,!0))}hasVariable(e){return this.variables.has(e)}removeVariable(e){return this.variables.delete(e)}getVariableNames(){return Array.from(this.variables.keys())}getAllVariables(){return Array.from(this.variables.values())}clear(){this.variables.clear()}setVariables(e){for(const[t,r]of Object.entries(e)){const e=this.variables.get(t);e&&!e.readonly&&(e.value=r)}}getVariables(e){const t={};for(const r of e){const e=this.getValue(r);void 0!==e&&(t[r]=e)}return t}exportConfig(){return{version:"1.0",variables:Array.from(this.variables.values())}}importConfig(e){this.variables.clear();for(const t of e.variables)this.variables.set(t.name,t)}toJSON(){return JSON.stringify(this.exportConfig(),null,2)}static fromJSON(e){return JSON.parse(e)}}exports.BehaviorTreeAssetManager=u,exports.BehaviorTreeAssetSerializer=class{static serialize(e,t={format:"json",pretty:!0}){if(!1!==t.validate){const t=f.validate(e);if(!t.valid){const e=t.errors?.join(", ")||"Unknown error";throw new Error(`资产验证失败: ${e}`)}t.warnings&&t.warnings.length>0&&k.warn(`资产验证警告: ${t.warnings.join(", ")}`)}return"json"===t.format?this.serializeToJSON(e,t.pretty):this.serializeToBinary(e)}static serializeToJSON(e,t=!0){try{const r=t?JSON.stringify(e,null,2):JSON.stringify(e);return k.info(`已序列化为JSON: ${r.length} 字符`),r}catch(e){throw new Error(`JSON序列化失败: ${e}`)}}static serializeToBinary(e){try{const r=t.BinarySerializer.encode(e);return k.info(`已序列化为二进制: ${r.length} 字节`),r}catch(e){throw new Error(`二进制序列化失败: ${e}`)}}static deserialize(e,t={validate:!0,strict:!0}){let r;try{r="string"==typeof e?this.deserializeFromJSON(e):this.deserializeFromBinary(e)}catch(e){throw new Error(`反序列化失败: ${e}`)}if(!1!==t.validate){const e=f.validate(r);if(!e.valid){const r=e.errors?.join(", ")||"Unknown error";if(t.strict)throw new Error(`资产验证失败: ${r}`);k.error(`资产验证失败: ${r}`)}e.warnings&&e.warnings.length>0&&k.warn(`资产验证警告: ${e.warnings.join(", ")}`)}return r}static deserializeFromJSON(e){try{const t=JSON.parse(e);if(!t.rootNodeId&&t.nodes&&t.connections){k.info("检测到编辑器格式,正在转换为运行时资产格式...");const e=t,r=b.toAsset(e);return k.info(`已从编辑器格式转换: ${r.nodes.length} 个节点`),r}{const e=t;return k.info(`已从运行时资产格式反序列化: ${e.nodes.length} 个节点`),e}}catch(e){throw new Error(`JSON解析失败: ${e}`)}}static deserializeFromBinary(e){try{const r=t.BinarySerializer.decode(e);return k.info(`已从二进制反序列化: ${r.nodes.length} 个节点`),r}catch(e){throw new Error(`二进制解码失败: ${e}`)}}static detectFormat(e){return"string"==typeof e?"json":"binary"}static getInfo(e){try{const r=this.detectFormat(e);let o;o="json"===r?JSON.parse(e):t.BinarySerializer.decode(e);const s=e.length;return{format:r,name:o.metadata.name,version:o.version,nodeCount:o.nodes.length,blackboardVariableCount:o.blackboard.length,size:s}}catch(e){return k.error(`获取资产信息失败: ${e}`),null}}static convert(e,t,r=!0){const o=this.deserialize(e,{validate:!1});return this.serialize(o,{format:t,pretty:r,validate:!1})}static compareSize(e,t){const r=e.length,o=t.length,s=r-o;return{jsonSize:r,binarySize:o,compressionRatio:s/r*100,savedBytes:s}}},exports.BehaviorTreeAssetValidator=f,exports.BehaviorTreeBuilder=y,exports.BehaviorTreePlugin=class{constructor(){this.name="@esengine/behavior-tree",this.version="1.0.0",this.worldManager=null,this.services=null}async install(e,r){this.services=r,r.registerSingleton(C),r.registerSingleton(u),this.worldManager=r.resolve(t.WorldManager)}async uninstall(){this.services&&(this.services.unregister(C),this.services.unregister(u)),this.worldManager=null,this.services=null}setupScene(e){e.addSystem(new exports.BehaviorTreeExecutionSystem)}setupAllScenes(){if(!this.worldManager)throw new Error("Plugin not installed");const e=this.worldManager.getAllWorlds();for(const t of e)for(const e of t.getAllScenes())this.setupScene(e)}},exports.BehaviorTreeStarter=class{static start(e,r,o=!0){t.Core.services.resolve(u).loadAsset(r);let s=e.getComponent(exports.BehaviorTreeRuntimeComponent);if(s||(s=new exports.BehaviorTreeRuntimeComponent,e.addComponent(s)),s.treeAssetId=r.id,s.autoStart=o,r.blackboardVariables)for(const[e,t]of r.blackboardVariables.entries())s.setBlackboardValue(e,t);o&&(s.isRunning=!0)}static stop(e){const t=e.getComponent(exports.BehaviorTreeRuntimeComponent);t&&(t.isRunning=!1,t.resetAllStates())}static pause(e){const t=e.getComponent(exports.BehaviorTreeRuntimeComponent);t&&(t.isRunning=!1)}static resume(e){const t=e.getComponent(exports.BehaviorTreeRuntimeComponent);t&&(t.isRunning=!0)}static restart(e){const t=e.getComponent(exports.BehaviorTreeRuntimeComponent);t&&(t.resetAllStates(),t.isRunning=!0)}},exports.BindingHelper=p,exports.EditorFormatConverter=b,exports.GlobalBlackboardService=C,exports.NodeExecutorMetadata=g,exports.NodeExecutorRegistry=h,exports.NodeMetadataRegistry=m,exports.NodeTemplates=class{static getAllTemplates(){return m.getAllMetadata().map((e=>this.convertMetadataToTemplate(e)))}static getTemplate(e,t){return this.getAllTemplates().find((o=>{if(o.type!==e)return!1;const s=o.defaultConfig;switch(e){case r.Composite:return s.compositeType===t;case r.Decorator:return s.decoratorType===t;case r.Action:return s.actionType===t;case r.Condition:return s.conditionType===t;default:return!1}}))}static convertMetadataToTemplate(e){const t=this.convertConfigSchemaToProperties(e.configSchema||{}),o={nodeType:this.nodeTypeToString(e.nodeType)};switch(e.nodeType){case r.Composite:o.compositeType=e.implementationType;break;case r.Decorator:o.decoratorType=e.implementationType;break;case r.Action:o.actionType=e.implementationType;break;case r.Condition:o.conditionType=e.implementationType}if(e.configSchema)for(const[t,r]of Object.entries(e.configSchema)){const e=r;void 0!==e.default&&(o[t]=e.default)}const{icon:s,color:a}=this.getIconAndColorByType(e.nodeType,e.category||"");return{type:e.nodeType,displayName:e.displayName,category:e.category||this.getCategoryByNodeType(e.nodeType),description:e.description||"",className:e.implementationType,icon:s,color:a,defaultConfig:o,properties:t}}static convertConfigSchemaToProperties(e){const t=[];for(const[r,o]of Object.entries(e)){const e={name:r,type:this.mapFieldTypeToPropertyType(o),label:r};void 0!==o.description&&(e.description=o.description),void 0!==o.default&&(e.defaultValue=o.default),void 0!==o.min&&(e.min=o.min),void 0!==o.max&&(e.max=o.max),void 0!==o.allowMultipleConnections&&(e.allowMultipleConnections=o.allowMultipleConnections),o.options&&(e.options=o.options.map((e=>({label:e,value:e})))),o.supportBinding&&(e.renderConfig={component:"BindableInput",props:{supportBinding:!0}}),t.push(e)}return t}static mapFieldTypeToPropertyType(e){if(e.options&&e.options.length>0)return S.Select;switch(e.type){case"string":case"array":case"object":default:return S.String;case"number":return S.Number;case"boolean":return S.Boolean}}static nodeTypeToString(e){switch(e){case r.Composite:return"composite";case r.Decorator:return"decorator";case r.Action:return"action";case r.Condition:return"condition";default:return"unknown"}}static getCategoryByNodeType(e){switch(e){case r.Composite:return"组合";case r.Decorator:return"装饰器";case r.Action:return"动作";case r.Condition:return"条件";default:return"其他"}}static getIconAndColorByType(e,t){switch(e){case r.Composite:return{icon:"GitBranch",color:"#1976d2"};case r.Decorator:return{icon:"Settings",color:"#fb8c00"};case r.Action:return{icon:"Play",color:"#388e3c"};case r.Condition:return{icon:"HelpCircle",color:"#d32f2f"};default:return{icon:"Circle",color:"#757575"}}}},exports.NodeType=r,exports.PropertyType=S,exports.ServiceRegistry=x,exports.createDefaultRuntimeState=i;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|