Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix BTForEach crash if elements are removed from the array during iteration #211

Merged
merged 1 commit into from
Sep 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions bt/tasks/decorators/bt_for_each.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,15 @@ void BTForEach::_enter() {
}

BT::Status BTForEach::_tick(double p_delta) {
ERR_FAIL_COND_V_MSG(get_child_count() == 0, FAILURE, "ForEach decorator has no child.");
ERR_FAIL_COND_V_MSG(save_var == StringName(), FAILURE, "ForEach save variable is not set.");
ERR_FAIL_COND_V_MSG(array_var == StringName(), FAILURE, "ForEach array variable is not set.");
ERR_FAIL_COND_V_MSG(get_child_count() == 0, FAILURE, "BTForEach: Decorator has no child.");
ERR_FAIL_COND_V_MSG(save_var == StringName(), FAILURE, "BTForEach: Save variable is not set.");
ERR_FAIL_COND_V_MSG(array_var == StringName(), FAILURE, "BTForEach: Array variable is not set.");

Array arr = get_blackboard()->get_var(array_var, Variant());
if (arr.size() == 0) {
if (current_idx >= arr.size()) {
if (current_idx != 0) {
WARN_PRINT("BTForEach: Array size changed during iteration.");
}
return SUCCESS;
}
Variant elem = arr[current_idx];
Expand Down
16 changes: 16 additions & 0 deletions tests/test_for_each.h
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,22 @@ TEST_CASE("[Modules][LimboAI] BTForEach") {
CHECK_ENTRIES_TICKS_EXITS(task, 3, 6, 3);
CHECK(blackboard->get_var("element", "wetgoop") == "mushroom");
}

SUBCASE("Shouldn't crash if elements are removed during iteration") {
CHECK(fe->execute(0.01666) == BTTask::RUNNING);
CHECK(task->get_status() == BTTask::SUCCESS);
CHECK_ENTRIES_TICKS_EXITS(task, 1, 1, 1);
CHECK(blackboard->get_var("element", "wetgoop") == "apple");

arr.clear();

ERR_PRINT_OFF;
CHECK(fe->execute(0.01666) == BTTask::SUCCESS); // Returns SUCCESS and prints a warning without executing child task.
ERR_PRINT_ON;
CHECK(task->get_status() == BTTask::SUCCESS); // Same status.
CHECK_ENTRIES_TICKS_EXITS(task, 1, 1, 1); // Task is not re-executed as there is not enough elements to continue iteration.
CHECK(blackboard->get_var("element", "wetgoop") == "apple"); // Not changed.
}
}

} //namespace TestForEach
Expand Down