// called to update the behavior public virtual BehaviorStatus Update(Entity self, double dt) { if (Child != null) { if (!Child.Initialized) { Child.Init(World, self); } BehaviorStatus status = Child.Update(self, dt); switch (status) { case BehaviorStatus.SUCCESS: case BehaviorStatus.FAIL: Finished = Child; Child = null; break; } return(status); } return(BehaviorStatus.RUN); }
protected override void Execute(float delta) { if (leafNode == null) { status = BehaviorStatus.Success; return; } BehaviorStatus nodeState = leafNode.ProcessLogic(delta); if (nodeState == BehaviorStatus.Success) { if (currentIteration >= iterations && !infinite) { status = BehaviorStatus.Success; return; } currentIteration++; leafNode.ResetNode(); } else if (nodeState == BehaviorStatus.Failure) { status = BehaviorStatus.Failure; return; } status = BehaviorStatus.Running; }
public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus res) { var value = context.GetValue(this); var index = value.RunningIndex; var nres = ExecuteItem(ref context, ref index, res); return(nres != BehaviorStatus.Running, nres); //if (res == BehaviorStatus.Failure) return (true, res); //var value = context.GetValue(this); //for (int i = value.RunningIndex+1; i < Childs.Length; i++) //{ // var b = context.BTNodeOutput(i); // if (b == BehaviorStatus.Failure) return (true, b); // else if(b == BehaviorStatus.Running) // { // context.SetValue(this, new BTSequenceData() // { // RunningIndex = i // }); // return (false, BehaviorStatus.None); // } //} //return (true, BehaviorStatus.Success); }
protected override void OnStatusChangedFrom(BehaviorStatus oldStatus) { base.OnStatusChangedFrom(oldStatus); switch (Status) { case BehaviorStatus.Uninitialized: // Handled in base break; case BehaviorStatus.Initialized: //CreateChildrenIfNeeded(); foreach (var child in Children) { child.Initialize(); // REVIEW - do this in OnInitializing instead? (allow it to be overridden) } //OnInitializedChildren(); break; case BehaviorStatus.Running: break; case BehaviorStatus.Failed: break; case BehaviorStatus.Succeeded: break; default: throw new UnreachableCodeException(); } }
private BehaviorStatus ExecuteItem(ref Context context, ref int itemIndex, BehaviorStatus result = BehaviorStatus.None) { BehaviorStatus res = result; if (res == BehaviorStatus.None) { res = context.BTNodeOutput(itemIndex); } if (res == BehaviorStatus.Failure) { return(BehaviorStatus.Failure); } else if (res == BehaviorStatus.Running) { context.SetValue(this, new BTSequenceData() { RunningIndex = itemIndex }); return(BehaviorStatus.Running); } // else res == BehaviorStatus.success to Next itemIndex += 1; if (itemIndex >= Childs.Length) { return(BehaviorStatus.Success); } else { return(ExecuteItem(ref context, ref itemIndex)); } }
private async void GetBehaviorStatus(object sender, EventArgs e) { string MethodName = "GetBehaviorStatus"; var behaviorTask = Awareness.GetCaptureClient(this).GetBehaviorAsync(); try { await behaviorTask; if (behaviorTask.IsCompleted && behaviorTask.Result != null) { BehaviorStatus behaviorStatus = behaviorTask.Result.BehaviorStatus; DetectedBehavior mostLikelyBehavior = behaviorStatus.MostLikelyBehavior; string logMessage = $"Most likely behavior is {Constant.GetBehavior(mostLikelyBehavior.Type)},the confidence is { mostLikelyBehavior.Confidence}"; log.ShowLog(logMessage); Log.Info(MethodName, logMessage); } else { var exception = behaviorTask.Exception; string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}"; log.ShowLog(errorMessage); Log.Error(MethodName, errorMessage); } } catch (Exception exception) { string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}"; log.ShowLog(errorMessage); Log.Error(MethodName, errorMessage); } }
public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus result) { var status = context.GetValue(this); if (status.Running == 0) {// == 0 说明之前已经因为Success返回了 return(false, BehaviorStatus.None); } if (result == BehaviorStatus.Success) { context.SetValue(this, new BTParallelSelectorData()); return(true, BehaviorStatus.Success); } else { status.Running -= 1; context.SetValue(this, status); if (status.Running <= 0) { return(true, BehaviorStatus.Failure); } else { return(false, BehaviorStatus.Running); } } }
protected override void OnSelectedStatusChangedForTo(IBehavior child, BehaviorStatus oldStatus, BehaviorStatus status) { #if SanityChecks if (child != SelectedChild) { l.Warn("child != SelectedChild"); return; } #endif switch (status) { //case BehaviorStatus.Uninitialized: // break; //case BehaviorStatus.Initialized: // break; case BehaviorStatus.Running: // It is running as expected break; case BehaviorStatus.Failed: Fail(child.StatusMessage); break; case BehaviorStatus.Succeeded: if (Advance() == BehaviorStatus.Succeeded) { Succeed(); } break; //case BehaviorStatus.Disposed: // break; default: l.Warn("UNEXPECTED Sequencer child state: " + child.ToString()); break; } }
public void Initialize(int i, BehaviorStatus status, int stack, int composite) { Index = i; Status = status; StackIndex = stack; CompositeIndex = composite; }
protected override BehaviorStatus OnBehave(ref BehaviorTreeContext context) { try { if (Children == null || Children.Length == 0) { return(BehaviorStatus.Success); } for (int i = 0; i < Children.Length; i++) { BehaviorStatus status = Children[i].Behave(ref context); if (status != BehaviorStatus.Failure) { return(status); } } return(BehaviorStatus.Failure); } catch (System.Exception ex) { Game.LogTrivial($"[{this.GetType().Name}] Exception thrown at OnBehave(): {ex}"); return(BehaviorStatus.Failure); } }
// OLD - use Default RP instead? ///// <summary> ///// If null, throw an exception when trying to run a child with no IHasStatusRecurranceParameters ///// </summary> //TimeSpan? DefaultInterval = null; protected override void OnChildStatusChanged(IBehavior child, BehaviorStatus oldStatus, BehaviorStatus newStatus) { if (child.IsFinished) { var finishedChildrenCopy = finishedChildren; if (finishedChildrenCopy != null) { finishedChildrenCopy.Add(child); } this.children.Remove(child); #if LOG_TASK_FINISHED l.Info("Task finished: " + child.ToString()); #endif } switch (newStatus) { case BehaviorStatus.Uninitialized: break; case BehaviorStatus.Initialized: break; case BehaviorStatus.Running: break; case BehaviorStatus.Failed: break; case BehaviorStatus.Succeeded: break; case BehaviorStatus.Disposed: break; default: break; } }
public void ResetNode(bool isRun = false) { mLastStatue = BehaviorStatus.Failure; foreach (var k in mBuffNodes) { k.Value.ResetNode(isRun); } }
public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus res) { var value = context.GetValue(this); var index = value.RunningIndex; var nres = ExecuteItem(ref context, ref index, res); return(nres != BehaviorStatus.Running, nres); }
/// <summary> /// 再帰的にノードを実行する /// </summary> /// <param name="node">実行するノード</param> private BehaviorStatus Execute(Node node) { // 実行中のノードをActive Stackに積む PushNode(node); // Compositeノードの場合は再帰処理 if (node is CompositeNode) { CompositeNode cnode = node as CompositeNode; while (cnode.CanExecute()) { Node child = cnode.Children[cnode.CurrentChildIndex]; BehaviorStatus childStatus = Execute(child); // 再評価が必要な場合はそれをリストに追加 if (cnode.NeedsConditionalAbort) { if (child is ConditionalNode) { _reevaluateList.Add(new ConditionalReevaluate { Index = child.Index, CompositeIndex = cnode.Index, Status = childStatus, }); } } if (childStatus == BehaviorStatus.Running) { return(BehaviorStatus.Running); } cnode.OnChildExecuted(childStatus); } if (cnode.Status != BehaviorStatus.Running) { // 実行が終了したノードをスタックから外す cnode.OnEnd(); PopNode(); } return(cnode.Status); } else { BehaviorStatus status = node.OnUpdate(); if (status != BehaviorStatus.Running) { node.OnEnd(); PopNode(); } return(status); } }
/// <summary> /// ノードの実行が終了したら呼ばれる /// </summary> public virtual void OnEnd() { if (_status == BehaviorStatus.Completed) { return; } _status = BehaviorStatus.Inactive; }
public override void OnTerminate(BehaviorStatus status) { for (int i = 0; i < mChildrenList.Count; ++i) { if (mChildrenList[i].IsRunning) { mChildrenList[i].Abort(); } } }
/// <summary> /// ツリーの状態をUpdate /// </summary> public void Update() { if (_isCompleted) { return; } int abortIndex = ReevaluateConditionalTasks(); if (abortIndex != -1) { // 中断したノードと現在実行中のノードの共通祖先を見つける int caIndex = CommonAncestorNode(abortIndex, _activeNodeIndex); Node activeNode = _nodeList[_activeNodeIndex]; activeNode.OnAbort(); while (_activeStack.Count != 0) { PopNode(); activeNode = _nodeList[_activeNodeIndex]; activeNode.OnAbort(); if (_activeNodeIndex == caIndex) { break; } ConditionalReevaluate cr = _reevaluateList.FirstOrDefault(r => r.Index == _activeNodeIndex); if (cr != null) { _reevaluateList.Remove(cr); } } } BehaviorStatus status = BehaviorStatus.Inactive; if (_activeNodeIndex == -1) { status = Execute(_rootNode); } else { Node node = _nodeList[_activeNodeIndex]; status = Execute(node); } if (status == BehaviorStatus.Completed) { Debug.Log("Behavior Tree has been completed."); _isCompleted = true; } }
public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus result) { if (result == BehaviorStatus.Running) { return(true, result); } else { return(true, BehaviorStatus.Failure); } }
public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus result) { if (result == BehaviorStatus.Running) { context.Inactive(this); } else { context.Active(this); } return(false, BehaviorStatus.None); }
public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus result) { var value = context.GetValue(this); var index = value.RunningIndex; var nRes = ExecuteItem(ref context, ref index, result); if (nRes == BehaviorStatus.Running) { return(false, nRes); } return(true, nRes); }
public BehaviorTree_FinishWithResultActionControl(BehaviorTree_FinishWithResultActionControlConstructionParams csParam) : base(csParam) { InitConstruction(); NodeName = csParam.NodeName; Result = csParam.Result; mChildNodeContainer = DecoratorPanel; mServiceContainer = ServicePanel; BindingTemplateClassInstanceProperties(); Background = TryFindResource("BehaviorTreeNode_CustomActionColor") as SolidColorBrush; InitializeLinkControl(csParam); }
public BehaviorStatus Tick() { if (status != BehaviorStatus.Running) { OnInitialize(); } status = OnUpdate(); if (status != BehaviorStatus.Running) { OnTerminate(status); } return(status); }
public void ResetNode(bool isRun = false) { if (isRun) { if (mLastStatus == BehaviorStatus.Running) { mLastStatus = BehaviorStatus.Completed; } } else { mLastStatus = BehaviorStatus.Failure; } }
protected override void OnChildStatusChanged(IBehavior child, BehaviorStatus from, BehaviorStatus newStatus) { var ev = ChildStatusChangedForParentAndChildFromTo; if (ev != null) ev(this, child,from,newStatus); if (child == this.Child) { if (child.IsFinished) { base.Child = null; } } base.OnChildStatusChanged(child, from, newStatus); }
public override BehaviorStatus Update(Entity self, double dt) { BehaviorStatus status = base.Update(self, dt); switch (status) { case BehaviorStatus.RUN: PositionComponent position = self.Get <PositionComponent>(); if (PathToFollow == null) { return(BehaviorStatus.FAIL); } else { // move to the target Vector2 targetPos = World.Map.GetPositionFromIndex(PathToFollow.Waypoints[0].X, PathToFollow.Waypoints[0].Y); Vector2 arrivedAt = World.Map.MoveTowards(position.Position, Speed, targetPos); position.X = arrivedAt.X; position.Y = arrivedAt.Y; if (position.Position == targetPos) { position.Index = PathToFollow.Waypoints[0]; PathToFollow.Waypoints.RemoveAt(0); // check the next waypoint to ensure it is still valid if (PathToFollow.Waypoints.Count > 0) { Point nextWaypoint = PathToFollow.Waypoints[0]; // if the next waypoint is blocked, clear the path if (World.Collisions.Map[nextWaypoint] == PathTypes.BLOCKED) { // TODO: alert some failure state? Recalculate the path? return(BehaviorStatus.FAIL); } } else { return(BehaviorStatus.SUCCESS); } } } break; } return(BehaviorStatus.WAIT); }
public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus result) { switch (result) { case BehaviorStatus.Failure: return(true, BehaviorStatus.Success); case BehaviorStatus.Success: context.Active(this); return(false, BehaviorStatus.None); default: return(false, BehaviorStatus.None); } }
public DelayedCondition(TimeSpan delay, BehaviorStatus result) { switch (result) { case BehaviorStatus.Failed: case BehaviorStatus.Succeeded: break; default: throw new ArgumentException("result must be Succeeded or Failed"); } this.Delay = delay; //this.delay = delay; this.result = result; }
/// <summary> /// Behavior tree should run this funtion per tick /// </summary> /// <returns>Node Status after this tick</returns> public BehaviorStatus Tick() { if (Status != BehaviorStatus.Running) { Initialize(); } Status = Update(); if (Status != BehaviorStatus.Running) { Terminate(); } return(Status); }
public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus result) { switch (result) { case BehaviorStatus.Success: return(true, BehaviorStatus.Success); case BehaviorStatus.Failure: context.Active(this); return(false, BehaviorStatus.None); default: return(false, BehaviorStatus.None); //throw new System.Exception("Child node completion cannot be Running "); } }
protected BehaviorStatus TryTick() { bool go = true; if (mLastStatus != BehaviorStatus.Running) { go = Check(); } if (go) { mLastStatus = PlayCallBack(); return(mLastStatus); } return(BehaviorStatus.Failure); }
/// <summary> /// 子ノードの実行が終わった際に呼び出される /// すべての子ノードが実行完了かつSucessの場合はCompleteにする /// </summary> /// <param name="childStatus">子ノードの実行結果</param> public virtual void OnChildExecuted(BehaviorStatus childStatus) { if (_currentChildIndex < _children.Count) { return; } if (NeedsConditionalAbort && _hasConditionalNode) { return; } if (childStatus == BehaviorStatus.Sucess || childStatus == BehaviorStatus.Completed) { _status = BehaviorStatus.Completed; } }
public override BehaviorStatus Update(Entity self, double dt) { BehaviorStatus status = base.Update(self, dt); if (Skip) { return(BehaviorStatus.SUCCESS); } FadeCounter -= dt; DrawableComponent drawable = self.Get <DrawableComponent>(); foreach (GameDrawable d in drawable.Get("Foreground")) { if (d is DrawableSprite) { if (FadeIn) { d.Alpha = 1f - ((float)FadeCounter / (float)FadeTime); } else { d.Alpha = ((float)FadeCounter / (float)FadeTime); } } } if (FadeCounter <= 0) { if (!FadeIn) { foreach (GameDrawable d in drawable.Get("Foreground")) { if (d is DrawableSprite) { d.Visible = false; } } } return(BehaviorStatus.SUCCESS); } return(BehaviorStatus.WAIT); }
public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus result) { var status = context.GetValue(this); if (status.Running == 0) {// == 0 说明之前已经因为Success返回了 return(false, BehaviorStatus.None); } if (result == BehaviorStatus.Success) { context.SetValue(this, default); return(true, BehaviorStatus.Success); } status.Running -= 1; context.SetValue(this, status); return(status.Running <= 0 ? (true, BehaviorStatus.Failure) : (false, BehaviorStatus.Running)); }
public (bool, BehaviorStatus) Completed(ref Context context, int childIndex, BehaviorStatus result) { if (result == BehaviorStatus.Success) { return(true, BehaviorStatus.Success); } else if (result == BehaviorStatus.Failure) { context.Active(this); return(false, BehaviorStatus.None); } else { return(false, BehaviorStatus.None); //throw new System.Exception("Child node completion cannot be Running "); } }
private BehaviorStatus ExecuteItem(ref Context context, ref int itemIndex, BehaviorStatus result = BehaviorStatus.None) { var res = result; if (res == BehaviorStatus.Success) { return(BehaviorStatus.Success); } if (res == BehaviorStatus.Running) { context.SetValue(this, new BTSelectorData() { RunningIndex = itemIndex }); return(BehaviorStatus.Running); } // else res == BehaviorStatus.failure to Next return(ExecuteNext(ref context, itemIndex));; }
protected override void OnStatusChangedFrom(BehaviorStatus oldStatus) { base.OnStatusChangedFrom(oldStatus); switch (Status) { case BehaviorStatus.Running: // Enable child monitoring while this node is running MonitorChildScores = true; //superfluous, as it is done in OnStart break; case BehaviorStatus.Failed: case BehaviorStatus.Succeeded: MonitorChildScores = false; break; default: break; } }
protected override void OnChildStatusChanged(IBehavior child, BehaviorStatus oldStatus, BehaviorStatus childStatus) { switch (childStatus) { case BehaviorStatus.Initialized: break; case BehaviorStatus.Running: break; case BehaviorStatus.Failed: OnChildFailed(child); break; case BehaviorStatus.Succeeded: OnChildSucceeded(child); break; case BehaviorStatus.Disposed: break; default: break; } base.OnChildStatusChanged(child, oldStatus, childStatus); }
public override void Initialize() { mDummyEventArgs = new EventArgs(); mPlannedWorkPattern = BehaviorExecutePattern.Synchronization; Status = BehaviorStatus.Closed; mDependentBehaviors = new List<Behavior>(); //initialize the event state to allow thread to continue mManualEvent = new ManualResetEvent(true); mBehaviorEntities = new Dictionary<Component, BehaviorEntityType>(); mShouldPause = false; mShouldAbort = false; mIsWorkFinished=false; mDisposed = false; ProcessRate = 0; mProgressChangedEventArgs = new ProgressChangedEventArgs(mProcessRate); }
public override void Work() { OnBeforeStart(); while (!mIsWorkFinished) { if (mShouldPause) { OnPaused(); mManualEvent.WaitOne(); if (mStatus == BehaviorStatus.Paused) { //is resume from the pause state OnResumed(); } mShouldPause = false; } if (mShouldAbort) { //do other abort activity here OnAborted(); mShouldAbort = false; mIsWorkFinished = true; continue; } Status = BehaviorStatus.Working; DoWork(); } OnClose(); }
void OnBehaviorStatusChanged(IBehavior arg1, BehaviorStatus from, BehaviorStatus to) { switch (behavior.Status) { case BehaviorStatus.Disposed: OnDisposed(); break; case BehaviorStatus.Uninitialized: case BehaviorStatus.Initialized: case BehaviorStatus.Failed: case BehaviorStatus.Succeeded: StopCoroutine(); break; case BehaviorStatus.Running: if (from == BehaviorStatus.Suspended) { Resume(); } else { StartCoroutine(); } break; case BehaviorStatus.Suspended: Suspend(); break; default: break; } }
protected virtual void OnResumed() { Status = BehaviorStatus.Working; if (Resumed != null) { Resumed(this,mDummyEventArgs); } }
//public event Action<MultiComposite, IBehavior> SelectedChildChangedForFrom; protected abstract void OnSelectedStatusChangedForTo(IBehavior behavior, BehaviorStatus from, BehaviorStatus status);
protected sealed override void RaiseStatusChanged(BehaviorStatus oldStatus) { var ev = StatusChangedForFromTo; if (ev != null) ev(this, oldStatus, Status); }
void OnChildStatusChangedForFromTo(IBehavior child, BehaviorStatus from, BehaviorStatus newStatus) { switch (newStatus) { case BehaviorStatus.Uninitialized: break; case BehaviorStatus.Initialized: break; case BehaviorStatus.Running: break; case BehaviorStatus.Failed: OnChildFinished(); if (StopAfterFailuresRemaining > 0) { StopAfterFailuresRemaining--; if (StopAfterFailuresRemaining <= 0) { this.IsRunning = false; l.Error("Too many failures. "); // TODO: Make this Poller an activity? One that is isolated in its own tree? (Except for in TaskRunner) } } break; case BehaviorStatus.Succeeded: OnChildFinished(); if (StopAfterSuccessesRemaining > 0) { StopAfterSuccessesRemaining--; if (StopAfterSuccessesRemaining <= 0) { Succeed(); } } break; case BehaviorStatus.Disposed: break; default: break; } }
/// <summary> /// Rewrite to provide the behavior of customization /// </summary> protected virtual void OnPaused() { Status = BehaviorStatus.Paused; if (Paused != null) { Paused(this, mDummyEventArgs); } }
protected override void OnChildStatusChanged(IBehavior child, BehaviorStatus from, BehaviorStatus newStatus) { switch (newStatus) { case BehaviorStatus.Uninitialized: break; case BehaviorStatus.Initialized: break; case BehaviorStatus.Running: break; case BehaviorStatus.Failed: OnChildFinished(false); break; case BehaviorStatus.Succeeded: OnChildFinished(true); break; case BehaviorStatus.Disposed: break; default: break; } }
protected virtual void OnClose() { Status = BehaviorStatus.Closed; if(Close!=null) { Close(this, mDummyEventArgs); } }
protected virtual void OnChildStatusChanged(IBehavior child, BehaviorStatus from, BehaviorStatus newStatus) { }
/// <summary> /// Potential fof /// </summary> /// <param name="behavior"></param> /// <param name="oldStatus"></param> /// <param name="status"></param> /// <remarks> /// Potential alternative behavior in derived classes: /// - if one fails, try another until one succeeds /// - run all children in order (until one fails, or all succeed) /// - use max completions, max failures, max successes parameters /// </remarks> protected override void OnSelectedStatusChangedForTo(IBehavior behavior, BehaviorStatus oldStatus, BehaviorStatus status) { #if SanityChecks if (behavior != SelectedChild) return; #endif switch (status) { //case BehaviorStatus.Uninitialized: // break; case BehaviorStatus.Initialized: // Do nothing -- we just selected it break; case BehaviorStatus.Running: // Do nothing -- we just started it break; case BehaviorStatus.Failed: Fail(behavior.StatusMessage); break; case BehaviorStatus.Succeeded: Succeed(); break; //case BehaviorStatus.Disposed: // break; default: l.Trace("UNEXPECTED Status for Selector.SelectedChild: " + behavior.ToString()); break; } }