Files
df7832aa43 Replaced our NPC AI with Behavior Trees. (#96628)
This PR replaces our current NPC AI with a [behavior tree
system](https://en.wikipedia.org/wiki/Behavior_tree_(artificial_intelligence,_robotics_and_control)).
Behavior trees are a common way of creating AI in which you place nodes
in a tree structure to define what actions an AI should take.

AI controllers defined a list of /datum/ai_planning_subtree types in
behavior_nodes. Each subtree was a self-contained unit that could call
queue_behavior() to fire off /datum/ai_behavior actions. The controller
iterated subtrees in order, each one deciding independently whether to
queue something and deciding whether the next subtree would run.

This has a few issues:
1. There's no real structure; you are just defining a list of things to
try in order.
2. There was a loooot of subtrees that were basically the same as
another but with some slight modification
3. It was hard to understand.

Controllers now define a single json file describing a tree of nodes.
The tree is composed of structural composites:

Sequence - do A, then B, then C (and so on)
Selector - try A, if it fails try B, then C (and so on)
Parallel - run A and B simultaneously, with configurable failure/success
policies and or looping behavior
Subplan - loop a child continiously

Along that we also have "Decorators". These are nodes that basically
check a condition (E.g.; do we have a combat target). These decorators
can be used to gate behavior and are re-useable across behavior trees.
They also have a concept known as "Observers". Which lets them cancel
lower priority behavior in case their condition changes (Which we check
whenever a signal fires that fits that specific decorator). This makes
the AI much more responsive to change in environment.

For behaviors, we still use the ai_behavior datums. These are the actual
behaviors such as "Move to X", "Attack X". The only major change is that
these can no longer sleep() since they now run in the ai_controller.

Lastly, we now also have subtrees, except now they are essentially
pieces of behavior tree that can be re-used, or even overriden at
runtime or as a variable. Allowing for making modular AI made out of
several smaller trees.

You can set variables on these nodes directly via the extension (see
below), which should reduce the need to make subtypes of behaviors by a
lot. All of these vars are saved on the JSON and will be applied at
runtime.

If you are using subtrees, you can also assign "bindings" to these
variables, which will allow instances of the subtree to override those
variables.

Since a tree structure with variables becomes hard to parse in a JSON,
I've made a VSCode extension to edit these JSONs:

https://marketplace.visualstudio.com/items?itemName=BehaviorTreeG.behaviortreeg
https://github.com/CabinetOnFire/BehaviorTreeG

<img width="1795" height="1268" alt="image"
src="https://github.com/user-attachments/assets/56aa2f0b-3cf9-449f-bca4-8281fca82db6"
/>

This extension allows you to edit the behavior tree JSONs, and browse
through all the behaviors/decorators/subtrees we have

If you'd like more info on how to build these AI check out the
learn_ai.md. I will also make a tutorial to go over more depth on what
the system offers because I kind of suck at doing technical write-ups.

Targetting has been changed to. I've made a new acquire_targets behavior
that takes a target_source (what am I targetting) and
targetting_strategy (what does the candidate need to fulfill to be
considered a target). This allows us to make composites targetting
combinations to reduce the amount of specific find_and_set esque
behaviors we had before. Not everything is ported to this system but
that would be a longer term goal.

I've added a new build_bt script that converts all the behavior tree
JSONs into compiled versions. Why is this needed? Because I wanted to
keep using defines in behavior trees, so we need a way to convert this
into literal values before we send it to DM. This script runs on compile
and should also run in CI (If I didn't fuck that up!). This saves to a
new build/ folder.

I've ported every single AI in the game to this system (except raptors,
Kobsa is working on those so should be in soon!), so I do expect some
bugs to come out of this. But I also fixed some issues that have
probably been in the game for a long time such as:
- Fixed penguins being unable to fish
- Fixed bileworms not being able to devour people
- Fixes goldgrubs not grubbing gold (they could not mine!)
- Lizards actually eat food they find

Either way, I'd reccomend a long TM on this.

1. (Hopefully) a better development experience for making AI
2. Less copy-paste for behaviors, we should be able to re-use more
pieces to make behavior
3. Behavior trees is a more common pattern in making AI, so it should be
easier to find resources to find out how to do things.

🆑 CabinetOnFire, Iamgoofball, SmartKar, Ben10omintrix
refactor: Replaces our AI system with behavior trees, porting all
datum/ai to it
/🆑

I will add this PR with more details down the line. I think I got the
big picture but its a big PR, so sorry if I missed something important.

---------

Co-authored-by: Iamgoofball <iamgoofball@gmail.com>
Co-authored-by: SmArtKar <44720187+SmArtKar@users.noreply.github.com>
Co-authored-by: Ghom <42542238+Ghommie@users.noreply.github.com>
Co-authored-by: Ben10Omintrix <138636438+Ben10Omintrix@users.noreply.github.com>
Co-authored-by: SyncIt21 <110812394+SyncIt21@users.noreply.github.com>
2026-08-15 10:33:57 -06:00

337 lines
13 KiB
Plaintext

#define PHASEREGEN_FILTER "healing_glow"
#define RUIN_QUEUE "the_thing_depleter"
/mob/living/basic/boss/thing
name = "\improper Thing"
icon = 'icons/mob/simple/icemoon/thething.dmi'
icon_state = "p1"
icon_dead = "dead"
gender = NEUTER
maxHealth = 1800 //nicely divisible by three
health = 1800
armour_penetration = 40
melee_damage_lower = 30
melee_damage_upper = 30
mob_biotypes = MOB_ORGANIC|MOB_SPECIAL|MOB_MINING
sharpness = SHARP_EDGED
melee_attack_cooldown = CLICK_CD_SLOW
attack_verb_continuous = "eviscerates"
attack_verb_simple = "eviscerate"
attack_sound = 'sound/items/weapons/bladeslice.ogg'
attack_vis_effect = ATTACK_EFFECT_SLASH
speed = 3.5 //dont make this any faster PLEASE
gps_name = "L-4 Biohazard Beacon"
ai_controller = /datum/ai_controller/basic_controller/thing_boss
crusher_loot = list(/obj/item/crusher_trophy/flesh_glob)
mouse_opacity = MOUSE_OPACITY_OPAQUE
achievements = list(
/datum/award/achievement/boss/boss_killer,
/datum/award/achievement/boss/thething_kill,
/datum/award/score/boss_score,
/datum/award/score/thething_score,
)
crusher_achievement_type = /datum/award/achievement/boss/thething_crusher
victor_memory_type = /datum/memory/megafauna_slayer
/// Current phase of the boss fight
var/phase = 1
/// Time the Thing will be invulnerable between phases
var/phase_invul_time = 10 SECONDS
/// timer of phase invulnerability between phases
var/phase_invulnerability_timer
// ruin logic
/// if true, this boss may only be killed proper in its ruin by the associated machines as part of the bossfight.
var/maploaded = TRUE
/// where we spawned. not set if not maploaded
var/turf/spawn_loc
/// return timer
var/return_timer
/mob/living/basic/boss/thing/Initialize(mapload)
. = ..()
AddElement(/datum/element/death_drops, /obj/item/keycard/thing_boss, FALSE)
var/static/list/innate_actions = list(
/datum/action/cooldown/mob_cooldown/the_thing/decimate = BB_THETHING_DECIMATE,
/datum/action/cooldown/mob_cooldown/charge/the_thing = BB_THETHING_CHARGE,
/datum/action/cooldown/mob_cooldown/the_thing/big_tendrils = BB_THETHING_BIGTENDRILS,
/datum/action/cooldown/mob_cooldown/the_thing/shriek = BB_THETHING_SHRIEK,
/datum/action/cooldown/mob_cooldown/the_thing/cardinal_tendrils = BB_THETHING_CARDTENDRILS,
/datum/action/cooldown/mob_cooldown/the_thing/acid_spit = BB_THETHING_ACIDSPIT,
)
grant_actions_by_list(innate_actions)
AddElement(/datum/element/relay_attackers) // used to immediately aggro if shot from outside aggro range
RegisterSignal(src, COMSIG_ATOM_WAS_ATTACKED, PROC_REF(immediate_aggro))
maploaded = mapload
if(!maploaded)
return
spawn_loc = loc
RegisterSignal(src, COMSIG_AI_BLACKBOARD_KEY_SET(BB_CURRENT_TARGET), PROC_REF(target_gained))
RegisterSignal(src, COMSIG_AI_BLACKBOARD_KEY_CLEARED(BB_CURRENT_TARGET), PROC_REF(target_lost))
SSqueuelinks.add_to_queue(src, RUIN_QUEUE, 0)
return INITIALIZE_HINT_LATELOAD
/mob/living/basic/boss/thing/LateInitialize()
SSqueuelinks.pop_link(RUIN_QUEUE)
/mob/living/basic/boss/thing/update_icon_state()
. = ..()
if(stat)
icon_state = "dead"
return
icon_state = "p[phase]"
icon_living = icon_state
/mob/living/basic/boss/thing/adjust_health(amount, updating_health = TRUE, forced = FALSE)
if(phase_invulnerability_timer || phase == 3 || stat || amount <= 0)
return ..()
var/potential_excess = bruteloss + amount - (maxHealth/3)*phase
if(potential_excess > 0)
amount -= potential_excess
. = ..()
if(bruteloss >= (maxHealth/3)*phase)
phase_health_depleted()
/mob/living/basic/boss/thing/proc/phase_health_depleted()
if(phase_invulnerability_timer)
return //wtf?
if(!maploaded || client)
phase_successfully_depleted()
return
if(!client && istype(get_area(src), /area/station)) //retreat to station if AI controlled
return_to_spawnloc()
return
add_traits(list(TRAIT_GODMODE, TRAIT_IMMOBILIZED), MEGAFAUNA_TRAIT)
balloon_alert_to_viewers("invulnerable! overload the machines!")
visible_message(span_danger("[src] drops to the ground staggered, unable to keep up with injuries!"))
phase_invulnerability_timer = addtimer(CALLBACK(src, PROC_REF(phase_too_slow)), phase_invul_time, TIMER_STOPPABLE|TIMER_UNIQUE)
add_filter(PHASEREGEN_FILTER, 2, list("type" = "outline", "color" = COLOR_PALE_GREEN, "alpha" = 0, "size" = 1))
var/filter = get_filter(PHASEREGEN_FILTER)
animate(filter, alpha = 200, time = 0.5 SECONDS, loop = -1)
animate(alpha = 0, time = 0.5 SECONDS)
SEND_SIGNAL(src, COMSIG_MEGAFAUNA_THETHING_PHASEUPDATED)
/// Delete our return timer when we gain a target if we started premapped
/mob/living/basic/boss/thing/proc/target_gained(datum/source)
SIGNAL_HANDLER
if(!return_timer)
return
deltimer(return_timer)
return_timer = null
/// If we started premapped, and we lost our target, start a 3 minute timer to return to spawn turf unless we gain aggro again
/mob/living/basic/boss/thing/proc/target_lost(datum/source)
SIGNAL_HANDLER
if(stat || client || loc == spawn_loc || return_timer)
return
return_timer = addtimer(CALLBACK(src, PROC_REF(return_to_spawn_check)), 3 MINUTES, TIMER_STOPPABLE | TIMER_DELETE_ME)
/// Return us to our spawn loc (ruin boss only) if we are alive and have an ai controller and our loc isnt the spawn loc
/mob/living/basic/boss/thing/proc/return_to_spawn_check()
if(isnull(ai_controller) || QDELETED(src) || loc == spawn_loc || stat || client)
return
return_to_spawnloc()
/mob/living/basic/boss/thing/proc/return_to_spawnloc()
if(isnull(spawn_loc))
CRASH("The Thing tried to return to spawn_loc but it was null! This shouldnt happen")
for(var/turf/open/target in RANGE_TURFS(1, loc))
new /obj/effect/temp_visual/mook_dust(target)
playsound(loc, 'sound/effects/meteorimpact.ogg', 40, TRUE)
visible_message(span_danger("[src] retreats through the ground back to where it came from!"))
forceMove(spawn_loc)
/// The Thing is successfully hit by incendiary fire while downed by damage (alternatively takes too much damage if not ruin spawned)
/mob/living/basic/boss/thing/proc/phase_successfully_depleted()
playsound(src, 'sound/effects/pop_expl.ogg', 65)
ai_controller?.set_blackboard_key(BB_THETHING_NOAOE, FALSE)
remove_traits(list(TRAIT_GODMODE, TRAIT_IMMOBILIZED), MEGAFAUNA_TRAIT)
deltimer(phase_invulnerability_timer)
phase_invulnerability_timer = null
if(phase < 3) //after phase 3 we literally just die
phase++
emote("scream")
update_appearance()
var/filter = get_filter(PHASEREGEN_FILTER)
if(!isnull(filter))
animate(filter)
remove_filter(PHASEREGEN_FILTER)
SEND_SIGNAL(src, COMSIG_MEGAFAUNA_THETHING_PHASEUPDATED)
new /obj/effect/gibspawner/human/bodypartless(loc)
/mob/living/basic/boss/thing/proc/phase_too_slow()
phase_invulnerability_timer = null
remove_traits(list(TRAIT_GODMODE, TRAIT_IMMOBILIZED), MEGAFAUNA_TRAIT)
balloon_alert_to_viewers("recovers!")
visible_message(span_danger("[src] recovers from the damage! Too slow!"))
adjust_health(-(maxHealth/3) * 0.5) //half of a phase (which is a third of maxhealth)
var/filter = get_filter(PHASEREGEN_FILTER)
if(!isnull(filter))
animate(filter)
remove_filter(PHASEREGEN_FILTER)
emote("roar")
SEND_SIGNAL(src, COMSIG_MEGAFAUNA_THETHING_PHASEUPDATED)
/// Immediately set out blackboard target key (if empty) to whoever attacks us; this is primarily because it has a lowered aggro range and a high sight range
/mob/living/basic/boss/thing/proc/immediate_aggro(datum/source, mob/attacker, flags)
SIGNAL_HANDLER
if(isnull(ai_controller) || stat || !istype(attacker) || ai_controller.blackboard_key_exists(BB_CURRENT_TARGET))
return
ai_controller?.set_blackboard_key(BB_CURRENT_TARGET, attacker)
/mob/living/basic/boss/thing/vv_edit_var(vname, vval)
. = ..()
if(vname == NAMEOF(src, phase))
ai_controller?.set_blackboard_key(BB_THETHING_NOAOE, phase > 1 ? FALSE : TRUE)
update_appearance()
/mob/living/basic/boss/thing/Destroy()
spawn_loc = null
return ..()
/mob/living/basic/boss/thing/with_ruin_loot/Initialize(mapload)
. = ..()
AddElement(/datum/element/death_drops, /obj/item/organ/brain/cybernetic/ai, FALSE)
// special stuff for our ruin to make a cooler bossfight
/obj/structure/thing_boss_phase_depleter
name = "Molecular Accelerator"
desc = "Weird-ass lab equipment."
icon_state = "thingdepleter"
anchored = TRUE
density = TRUE
move_resist = INFINITY
resistance_flags = INDESTRUCTIBLE | LAVA_PROOF | FIRE_PROOF | UNACIDABLE | ACID_PROOF
/// is this not broken yet
var/functional = TRUE
/// boss weakref
var/datum/weakref/boss_weakref
/obj/structure/thing_boss_phase_depleter/Initialize(mapload)
. = ..()
go_in_floor()
SSqueuelinks.add_to_queue(src, RUIN_QUEUE, 0)
/obj/structure/thing_boss_phase_depleter/MatchedLinks(id, list/partners)
if(id != RUIN_QUEUE)
return
var/mob/living/basic/boss/thing/thing = locate() in partners
if(isnull(thing))
qdel(src)
return
boss_weakref = WEAKREF(thing)
RegisterSignal(thing, COMSIG_MEGAFAUNA_THETHING_PHASEUPDATED, PROC_REF(thing_phaseupdated))
/obj/structure/thing_boss_phase_depleter/proc/thing_phaseupdated(mob/living/basic/boss/thing/source)
SIGNAL_HANDLER
if(!functional)
return
if(source.phase_invulnerability_timer)
go_out_floor()
else
go_in_floor()
/obj/structure/thing_boss_phase_depleter/examine(mob/user)
. = ..()
. += density ? span_boldnotice("It may be possible to overload this and destroy that things defenses...") : span_bolddanger("The machine is currently being restrained by tendrils.")
/obj/structure/thing_boss_phase_depleter/proc/set_circuit_floor(state)
for(var/turf/open/floor/circuit/circuit in RANGE_TURFS(1, loc))
circuit.on = state
circuit.update_appearance()
/obj/structure/thing_boss_phase_depleter/proc/go_in_floor()
if(!density)
return
density = FALSE
obj_flags &= ~CAN_BE_HIT
set_circuit_floor(FALSE)
name = "hatch"
icon_state = "thingdepleter_infloor"
/obj/structure/thing_boss_phase_depleter/proc/go_out_floor()
if(density)
return
density = TRUE
obj_flags |= CAN_BE_HIT
set_circuit_floor(TRUE)
name = initial(name)
icon_state = "thingdepleter"
new /obj/effect/temp_visual/mook_dust(loc)
/obj/structure/thing_boss_phase_depleter/interact(mob/user, list/modifiers)
var/mob/living/basic/boss/thing/the_thing = boss_weakref?.resolve()
if(!the_thing || !functional || !density)
return
if(!user.can_perform_action(src) || !user.can_interact_with(src))
return
balloon_alert_to_viewers("overloading...")
icon_state = "thingdepleter_overriding"
if(!do_after(user, 1 SECONDS, target = src))
if(density)
icon_state = "thingdepleter"
return
new /obj/effect/temp_visual/circle_wave/orange(loc)
playsound(src, 'sound/effects/explosion/explosion3.ogg', 100)
animate(src, transform = matrix()*1.5, time = 0.2 SECONDS)
animate(transform = matrix(), time = 0)
the_thing.phase_successfully_depleted()
functional = FALSE
go_in_floor()
icon_state = "thingdepleter_overriding"
addtimer(VARSET_CALLBACK(src, icon_state, "thingdepleter_broken"), 0.2 SECONDS)
/obj/effect/temp_visual/circle_wave/orange
color = COLOR_ORANGE
/obj/structure/aggro_gate
name = "biohazard gate"
desc = "A wall of solid light, only activating when a human is endangered by a biohazard, unfortunately that does little for safety as it locks you in with said biohazard. Virtually indestructible, you must evade (or kill) the threat."
icon = 'icons/effects/effects.dmi'
icon_state = "wave2"
resistance_flags = INDESTRUCTIBLE | FIRE_PROOF | ACID_PROOF | LAVA_PROOF
move_resist = MOVE_FORCE_OVERPOWERING
opacity = FALSE
density = FALSE
invisibility = INVISIBILITY_MAXIMUM
anchored = TRUE
/// queue id
var/queue_id = RUIN_QUEUE
/// blackboard key for target
var/target_bb_key = BB_CURRENT_TARGET
/obj/structure/aggro_gate/Initialize(mapload)
. = ..()
SSqueuelinks.add_to_queue(src, queue_id)
/obj/structure/aggro_gate/MatchedLinks(id, list/partners)
if(id != queue_id)
return
for(var/mob/living/partner in partners)
RegisterSignal(partner, COMSIG_AI_BLACKBOARD_KEY_SET(target_bb_key), PROC_REF(bar_the_gates))
RegisterSignals(partner, list(COMSIG_AI_BLACKBOARD_KEY_CLEARED(target_bb_key), COMSIG_LIVING_DEATH, COMSIG_MOB_LOGIN), PROC_REF(open_gates))
/obj/structure/aggro_gate/proc/bar_the_gates(mob/living/source)
SIGNAL_HANDLER
var/atom/target = source.ai_controller?.blackboard[target_bb_key]
if (QDELETED(target))
return
invisibility = INVISIBILITY_NONE
density = TRUE
playsound(src, SFX_SPARKS, 100, vary = TRUE, extrarange = SHORT_RANGE_SOUND_EXTRARANGE)
do_sparks(3, cardinal_only = FALSE, source = src)
/obj/structure/aggro_gate/proc/open_gates(mob/living/source)
playsound(src, SFX_SPARKS, 100, vary = TRUE, extrarange = SHORT_RANGE_SOUND_EXTRARANGE)
do_sparks(3, cardinal_only = FALSE, source = src)
density = FALSE
invisibility = INVISIBILITY_MAXIMUM
#undef PHASEREGEN_FILTER
#undef RUIN_QUEUE