Files
Bubberstation/code/datums/ai/_ai_controller.dm
T
JacquerelandGitHub eb6c0eb37c Dogs use the Pet Command system (#72045)
About The Pull Request

Chiefly this refactors dogs to use the newer component/datum system for "pet which follows instructions". It also refactors it a little bit because I had better ideas while working on this than I had last week. Specifically, instead of passing around keys we just stick a weakref to our currently active behaviour in the blackboard. Basically the same but skipping an unecessary step.

Additionally it adds a component for the previous "befriending a mob by clicking it repeatedly" behaviour which hopefully we won't use too much because it's not very exciting (I am planning on replacing it for dogs some time after Christmas).
The biggest effort in here was making the Fetch command more generic, which includes multiple behaviours (which might be used on their own?) and another component (for holding an item without hands).

Additionally I noticed that dogs would keep following my instructions after they died.
This seems unideal, and would be unideal for virtually any AI controller, so I added it as an AI_flag just in case there's some circumstance where you do want to process AI on a dead mob.

Finally this should replicate all behaviour Ian already had plus "follow" (from rats) and a new bonus easter egg reaction, however I noticed that the fetch command is supposed to have Ian eat any food that you try to get him to fetch.
This has been broken for some time and I will be away from my desk for a couple weeks pretty soon, so I wrote the behaviour for this but left it unused. I will come back to this in the future, once I figure out a way to implement it which does not require adding the "you can hit this" flag to every edible item.

Also I had to refit the recent addition of dogs barking at felinids to fit into this, with a side effect that now dogs won't get mad at a Felinid they are friends with. This... feels like intended behaviour anyway?
Why It's Good For The Game

It's good for these to work the same way instead of reimplementing the same behaviour in multiple files.
Being able to have Ian (or other dogs) follow you around the station is both fun and cute, and also makes him significantly more vulnerable to being murdered.
Changelog

cl
add: Ian has learned some new tricks, tell him what a good boy he is!
add: Ian will come on a walk with you, if you are his friend.
refactor: Ian's tricks work the same way as some other mobs' tricks and should be extendable to future mobs.
fix: Dogs no longer run at the maximum possible speed for a mob at all times.
add: When Ian gets old, he also slows down. Poor little guy.
add: Dogs will no longer dislike the presence of Felinids who have taken the time to befriend them.
/cl
2022-12-29 14:37:25 +13:00

336 lines
14 KiB
Plaintext

/*
AI controllers are a datumized form of AI that simulates the input a player would otherwise give to a atom. What this means is that these datums
have ways of interacting with a specific atom and control it. They posses a blackboard with the information the AI knows and has, and will plan behaviors it will try to execute through
multiple modular subtrees with behaviors
*/
/datum/ai_controller
///The atom this controller is controlling
var/atom/pawn
///Bitfield of traits for this AI to handle extra behavior
var/ai_traits = STOP_ACTING_WHILE_DEAD
///Current actions planned to be performed by the AI in the upcoming plan
var/list/planned_behaviors
///Current actions being performed by the AI.
var/list/current_behaviors
///Current actions and their respective last time ran as an assoc list.
var/list/behavior_cooldowns = list()
///Current status of AI (OFF/ON)
var/ai_status
///Current movement target of the AI, generally set by decision making.
var/atom/current_movement_target
///Identifier for what last touched our movement target, so it can be cleared conditionally
var/movement_target_source
///This is a list of variables the AI uses and can be mutated by actions. When an action is performed you pass this list and any relevant keys for the variables it can mutate.
var/list/blackboard = list()
///Stored arguments for behaviors given during their initial creation
var/list/behavior_args = list()
///Tracks recent pathing attempts, if we fail too many in a row we fail our current plans.
var/pathing_attempts
///Can the AI remain in control if there is a client?
var/continue_processing_when_client = FALSE
///distance to give up on target
var/max_target_distance = 14
///Cooldown for new plans, to prevent AI from going nuts if it can't think of new plans and looping on end
COOLDOWN_DECLARE(failed_planning_cooldown)
///All subtrees this AI has available, will run them in order, so make sure they're in the order you want them to run. On initialization of this type, it will start as a typepath(s) and get converted to references of ai_subtrees found in SSai_controllers when init_subtrees() is called
var/list/planning_subtrees
///The idle behavior this AI performs when it has no actions.
var/datum/idle_behavior/idle_behavior = null
// Movement related things here
///Reference to the movement datum we use. Is a type on initialize but becomes a ref afterwards.
var/datum/ai_movement/ai_movement = /datum/ai_movement/dumb
///Cooldown until next movement
COOLDOWN_DECLARE(movement_cooldown)
///Delay between movements. This is on the controller so we can keep the movement datum singleton
var/movement_delay = 0.1 SECONDS
// The variables below are fucking stupid and should be put into the blackboard at some point.
///AI paused time
var/paused_until = 0
/datum/ai_controller/New(atom/new_pawn)
change_ai_movement_type(ai_movement)
init_subtrees()
if(idle_behavior)
idle_behavior = new idle_behavior()
PossessPawn(new_pawn)
/datum/ai_controller/Destroy(force, ...)
set_ai_status(AI_STATUS_OFF)
UnpossessPawn(FALSE)
return ..()
///Sets the current movement target, with an optional param to override the movement behavior
/datum/ai_controller/proc/set_movement_target(source, atom/target, datum/ai_movement/new_movement)
movement_target_source = source
current_movement_target = target
if(new_movement)
change_ai_movement_type(new_movement)
///Overrides the current ai_movement of this controller with a new one
/datum/ai_controller/proc/change_ai_movement_type(datum/ai_movement/new_movement)
ai_movement = SSai_movement.movement_types[new_movement]
///Completely replaces the planning_subtrees with a new set based on argument provided, list provided must contain specifically typepaths
/datum/ai_controller/proc/replace_planning_subtrees(list/typepaths_of_new_subtrees)
planning_subtrees = typepaths_of_new_subtrees
init_subtrees()
///Loops over the subtrees in planning_subtrees and looks at the ai_controllers to grab a reference, ENSURE planning_subtrees ARE TYPEPATHS AND NOT INSTANCES/REFERENCES BEFORE EXECUTING THIS
/datum/ai_controller/proc/init_subtrees()
if(!LAZYLEN(planning_subtrees))
return
var/list/temp_subtree_list = list()
for(var/subtree in planning_subtrees)
var/subtree_instance = SSai_controllers.ai_subtrees[subtree]
temp_subtree_list += subtree_instance
planning_subtrees = temp_subtree_list
///Proc to move from one pawn to another, this will destroy the target's existing controller.
/datum/ai_controller/proc/PossessPawn(atom/new_pawn)
if(pawn) //Reset any old signals
UnpossessPawn(FALSE)
if(istype(new_pawn.ai_controller)) //Existing AI, kill it.
QDEL_NULL(new_pawn.ai_controller)
if(TryPossessPawn(new_pawn) & AI_CONTROLLER_INCOMPATIBLE)
qdel(src)
CRASH("[src] attached to [new_pawn] but these are not compatible!")
pawn = new_pawn
pawn.ai_controller = src
if (!ismob(new_pawn))
set_ai_status(AI_STATUS_ON)
else
set_ai_status(get_setup_mob_ai_status(new_pawn))
RegisterSignal(pawn, COMSIG_MOB_LOGIN, PROC_REF(on_sentience_gained))
/// Mobs have more complicated factors about whether their AI should be on or not
/datum/ai_controller/proc/get_setup_mob_ai_status(mob/mob_pawn)
var/final_status = AI_STATUS_ON
if(!continue_processing_when_client && mob_pawn.client)
final_status = AI_STATUS_OFF
if(ai_traits & STOP_ACTING_WHILE_DEAD)
RegisterSignal(pawn, COMSIG_MOB_STATCHANGE, PROC_REF(on_stat_changed))
if(mob_pawn.stat == DEAD)
final_status = AI_STATUS_OFF
return final_status
///Abstract proc for initializing the pawn to the new controller
/datum/ai_controller/proc/TryPossessPawn(atom/new_pawn)
return
///Proc for deinitializing the pawn to the old controller
/datum/ai_controller/proc/UnpossessPawn(destroy)
UnregisterSignal(pawn, list(COMSIG_MOB_LOGIN, COMSIG_MOB_LOGOUT, COMSIG_MOB_STATCHANGE))
if(ai_movement.moving_controllers[src])
ai_movement.stop_moving_towards(src)
pawn.ai_controller = null
pawn = null
if(destroy)
qdel(src)
return
///Returns TRUE if the ai controller can actually run at the moment.
/datum/ai_controller/proc/able_to_run()
if(HAS_TRAIT(pawn, TRAIT_AI_PAUSED))
return FALSE
if(world.time < paused_until)
return FALSE
return TRUE
///Runs any actions that are currently running
/datum/ai_controller/process(delta_time)
if(!able_to_run())
SSmove_manager.stop_looping(pawn) //stop moving
return //this should remove them from processing in the future through event-based stuff.
if(!LAZYLEN(current_behaviors) && idle_behavior)
idle_behavior.perform_idle_behavior(delta_time, src) //Do some stupid shit while we have nothing to do
return
if(current_movement_target)
if(!isatom(current_movement_target))
stack_trace("[pawn]'s current movement target is not an atom, rather a [current_movement_target.type]! Did you accidentally set it to a weakref?")
CancelActions()
return
if(get_dist(pawn, current_movement_target) > max_target_distance) //The distance is out of range
CancelActions()
return
for(var/datum/ai_behavior/current_behavior as anything in current_behaviors)
// Convert the current behaviour action cooldown to realtime seconds from deciseconds.current_behavior
// Then pick the max of this and the delta_time passed to ai_controller.process()
// Action cooldowns cannot happen faster than delta_time, so delta_time should be the value used in this scenario.
var/action_delta_time = max(current_behavior.action_cooldown * 0.1, delta_time)
if(current_behavior.behavior_flags & AI_BEHAVIOR_REQUIRE_MOVEMENT) //Might need to move closer
if(!current_movement_target)
stack_trace("[pawn] wants to perform action type [current_behavior.type] which requires movement, but has no current movement target!")
return //This can cause issues, so don't let these slide.
if(current_behavior.required_distance >= get_dist(pawn, current_movement_target)) ///Are we close enough to engage?
if(ai_movement.moving_controllers[src] == current_movement_target) //We are close enough, if we're moving stop.
ai_movement.stop_moving_towards(src)
if(behavior_cooldowns[current_behavior] > world.time) //Still on cooldown
continue
ProcessBehavior(action_delta_time, current_behavior)
return
else if(ai_movement.moving_controllers[src] != current_movement_target) //We're too far, if we're not already moving start doing it.
ai_movement.start_moving_towards(src, current_movement_target, current_behavior.required_distance) //Then start moving
if(current_behavior.behavior_flags & AI_BEHAVIOR_MOVE_AND_PERFORM) //If we can move and perform then do so.
if(behavior_cooldowns[current_behavior] > world.time) //Still on cooldown
continue
ProcessBehavior(action_delta_time, current_behavior)
return
else //No movement required
if(behavior_cooldowns[current_behavior] > world.time) //Still on cooldown
continue
ProcessBehavior(action_delta_time, current_behavior)
return
///Determines whether the AI can currently make a new plan
/datum/ai_controller/proc/able_to_plan()
. = TRUE
for(var/datum/ai_behavior/current_behavior as anything in current_behaviors)
if(!(current_behavior.behavior_flags & AI_BEHAVIOR_CAN_PLAN_DURING_EXECUTION)) //We have a behavior that blocks planning
. = FALSE
break
///This is where you decide what actions are taken by the AI.
/datum/ai_controller/proc/SelectBehaviors(delta_time)
SHOULD_NOT_SLEEP(TRUE) //Fuck you don't sleep in procs like this.
if(!COOLDOWN_FINISHED(src, failed_planning_cooldown))
return FALSE
LAZYINITLIST(current_behaviors)
LAZYCLEARLIST(planned_behaviors)
if(LAZYLEN(planning_subtrees))
for(var/datum/ai_planning_subtree/subtree as anything in planning_subtrees)
if(subtree.SelectBehaviors(src, delta_time) == SUBTREE_RETURN_FINISH_PLANNING)
break
for(var/datum/ai_behavior/current_behavior as anything in current_behaviors)
if(LAZYACCESS(planned_behaviors, current_behavior))
continue
var/list/arguments = list(src, FALSE)
var/list/stored_arguments = behavior_args[type]
if(stored_arguments)
arguments += stored_arguments
current_behavior.finish_action(arglist(arguments))
///This proc handles changing ai status, and starts/stops processing if required.
/datum/ai_controller/proc/set_ai_status(new_ai_status)
if(ai_status == new_ai_status)
return FALSE //no change
ai_status = new_ai_status
switch(ai_status)
if(AI_STATUS_ON)
SSai_controllers.active_ai_controllers += src
START_PROCESSING(SSai_behaviors, src)
if(AI_STATUS_OFF)
STOP_PROCESSING(SSai_behaviors, src)
SSai_controllers.active_ai_controllers -= src
CancelActions()
/datum/ai_controller/proc/PauseAi(time)
paused_until = world.time + time
///Call this to add a behavior to the stack.
/datum/ai_controller/proc/queue_behavior(behavior_type, ...)
var/datum/ai_behavior/behavior = GET_AI_BEHAVIOR(behavior_type)
if(!behavior)
CRASH("Behavior [behavior_type] not found.")
var/list/arguments = args.Copy()
arguments[1] = src
if(LAZYACCESS(current_behaviors, behavior)) ///It's still in the plan, don't add it again to current_behaviors but do keep it in the planned behavior list so its not cancelled
LAZYADDASSOC(planned_behaviors, behavior, TRUE)
return
if(!behavior.setup(arglist(arguments)))
return
LAZYADDASSOC(current_behaviors, behavior, TRUE)
LAZYADDASSOC(planned_behaviors, behavior, TRUE)
arguments.Cut(1, 2)
if(length(arguments))
behavior_args[behavior_type] = arguments
else
behavior_args -= behavior_type
/datum/ai_controller/proc/ProcessBehavior(delta_time, datum/ai_behavior/behavior)
var/list/arguments = list(delta_time, src)
var/list/stored_arguments = behavior_args[behavior.type]
if(stored_arguments)
arguments += stored_arguments
behavior.perform(arglist(arguments))
/datum/ai_controller/proc/CancelActions()
if(!LAZYLEN(current_behaviors))
return
for(var/i in current_behaviors)
var/datum/ai_behavior/current_behavior = i
var/list/arguments = list(src, FALSE)
var/list/stored_arguments = behavior_args[current_behavior.type]
if(stored_arguments)
arguments += stored_arguments
current_behavior.finish_action(arglist(arguments))
/// Turn the controller on or off based on if you're alive, we only register to this if the flag is present so don't need to check again
/datum/ai_controller/proc/on_stat_changed(mob/living/source, new_stat)
SIGNAL_HANDLER
var/new_ai_status = (new_stat == DEAD) ? AI_STATUS_OFF : AI_STATUS_ON
set_ai_status(new_ai_status)
/datum/ai_controller/proc/on_sentience_gained()
SIGNAL_HANDLER
UnregisterSignal(pawn, COMSIG_MOB_LOGIN)
if(!continue_processing_when_client)
set_ai_status(AI_STATUS_OFF) //Can't do anything while player is connected
RegisterSignal(pawn, COMSIG_MOB_LOGOUT, PROC_REF(on_sentience_lost))
/datum/ai_controller/proc/on_sentience_lost()
SIGNAL_HANDLER
UnregisterSignal(pawn, COMSIG_MOB_LOGOUT)
set_ai_status(AI_STATUS_ON) //Can't do anything while player is connected
RegisterSignal(pawn, COMSIG_MOB_LOGIN, PROC_REF(on_sentience_gained))
/// Use this proc to define how your controller defines what access the pawn has for the sake of pathfinding, likely pointing to whatever ID slot is relevant
/datum/ai_controller/proc/get_access()
return
///Returns the minimum required distance to preform one of our current behaviors. Honestly this should just be cached or something but fuck you
/datum/ai_controller/proc/get_minimum_distance()
var/minimum_distance = max_target_distance
// right now I'm just taking the shortest minimum distance of our current behaviors, at some point in the future
// we should let whatever sets the current_movement_target also set the min distance and max path length
// (or at least cache it on the controller)
for(var/datum/ai_behavior/iter_behavior as anything in current_behaviors)
if(iter_behavior.required_distance < minimum_distance)
minimum_distance = iter_behavior.required_distance
return minimum_distance
/// If this controller is applied to a human subtype, this proc will be called to generate examine text
/datum/ai_controller/proc/get_human_examine_text()
var/text = "[span_deadsay("[pawn.p_they(TRUE)] do[pawn.p_es()]n't appear to be [pawn.p_them()]self.")]"
return text