behaviour-nodes-module/behaviour_tree.cpp

54 lines
1.4 KiB
C++

#include "behaviour_tree.h"
#include "behaviour_nodes/behaviour_composite.h"
#include "behaviour_nodes/behaviour_node.h"
#include "core/config/engine.h"
#include "core/variant/typed_array.h"
void BehaviourTree::_bind_methods() {}
void BehaviourTree::process() {
this->current->execute();
while (execute_next()) {
this->current->execute();
}
}
void BehaviourTree::_notification(int what) {
if (Engine::get_singleton()->is_editor_hint()) {
return;
}
switch (what) {
default:
return;
case NOTIFICATION_READY:
for (Variant var : get_children()) {
if ((this->current = cast_to<BehaviourNode>(var))) {
break;
}
}
ERR_FAIL_COND_EDMSG(this->current == nullptr, "No valid BehaviourNode in BehaviourTree");
set_process(true);
return;
case NOTIFICATION_PROCESS:
process();
return;
}
}
bool BehaviourTree::execute_next() {
BehaviourNode *next{ this->current->get_next() };
if (next == this->current) {
return false;
} else {
ERR_FAIL_COND_V_EDMSG(next == nullptr, false, vformat("%s::get_next returned a nullptr, repeating last node", this->current->get_class()));
if (this->current != next->get_parent()) {
this->current->exit();
}
if (this->current->get_parent() != next) {
next->enter();
next->execute();
}
this->current = next;
return cast_to<BehaviourComposite>(this->current) || this->current->get_status() == BehaviourNode::Fail;
}
}