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