To generate a plan, we instantiate a Planner and a Context, initialize the Context, and repeatedly call the planner's Tick method with the domain and context until the desired goal is achieved. In this example, the goal is to set the "Done" flag in the context to true. When the goal is achieved, we should see the console output "Get A", "Get B", "Get C", and "Done".
Partial planning
We can easily integrate the concept of partial planning into our domains. We call it a Pause Plan, and it must be set inside a sequence to be valid. It allows the planner to only plan up to a certain point, then continue from there once the partial plan has been completed.
.Sequence("A")
.Action("1")
//...
.End()
.PausePlan()
.Action("2")
//...
.End().End()
Sub-domains and domain splicing
We can define sub-domains and splice them together to form new domains, but they must share the same context type to be compatible. This can be quite handy for re-use of sub-domains and prevent a single domain definition from growing too large. Specially if we want to form recursive-style behavior this is needed.
var subDomain=new DomainBuilder("SubDomain")
.Select("B")
//...
.End()
.Build();
var myDomain=new DomainBuilder("MyDomain")
.Select("A")
//...
.End()
.Splice(subDomain)
.Select("C")
//...
.End().Build();
Sub-domains and slots
We can define slots in our domain definitions, and mark them with slot ids. This allow us to hook up sub-domains to these slots at run-time. This can be useful together with Smart Objects that extend the behavior of an agent when interacted with, for example.
var subDomain=new DomainBuilder("SubDomain")
.Select("B")
//...
.End()
.Build();
var myDomain=new DomainBuilder("MyDomain")
.Slot(1)
.Build();
myDomain.TrySetSlotDomain(1,subDomain);
//...
myDomain.ClearSlot(1);
Extending the Domain Builder
Fluid HTN makes it easy to extend the domain builder with specialized task types for a project's problem domain. Generic implementations of Condition, Operator and Effect are bundled with the library, allowing for lambda-styled domain definitions. Custom conditions, operators and effects can also be added to make domain definitions more readable and manageable.
var domain=new MyDomainBuilder("Trunk Thumper").Sequence("Attack enemy").IfEnemy().MoveTo(Location.Enemy, Speed.Sprint).SetLocation(Location.Enemy).SetIsTired().End().TrunkSlam().IfLocation(Location.Enemy).End().End().Sequence("Patrol next bridge").FindBridge().End().MoveTo(Location.Bridge, Speed.Walk).SetLocation(Location.Bridge).End().CheckBridge().IfLocation(Location.Bridge).SetBored().End().End().Build();
Let us look at how parts of this was made. First, we write our custom Domain Builder class. We instantiate a DefaultFactory into base, but we'll cover custom factory implementations later.
public class MyDomainBuilder : BaseDomainBuilder<MyDomainBuilder, MyContext>
{public MyDomainBuilder(string domainName):base(domainName,new DefaultFactory()){}}
Custom condition in domain builder
To add a custom condition, we need to override the ICondition interface.
public class IfEnemyCondition:ICondition{
public string Name{get;}="If Enemy";
public bool IsValid(IContext ctx){if(ctx is MyContext c){return c.HasState(WorldState.HasEnemy);}throw new Exception("Unexpected context type!");}}
Next, we can extend our MyDomainBuilder with a new function that expose this condition
public MyDomainBuilder IfEnemy(){var condition=new IfEnemyCondition();Pointer.AddCondition(condition);return this;}
Custom effect in domain builder
To add a custom effect, we need to override the IEffect interface.
public class SetLocationEffect:IEffect
{private Location _location;
public SetLocation(Location location)
{_location = location;}
public string Name{get;}="Set Location";
public EffectType Type{get;}=EffectType.PlanOnly;
public void Apply(IContext ctx){if (ctx is T c)c.SetState(WorldState.Location,_location);else throw new Exception("Unexpected context type!");}}
Next, we can extend our MyDomainBuilder with a new function that expose this effect
public MyDomainBuilder SetLocation(Location location)
{if(Pointer is IPrimitiveTask task)
{var effect = new SetLocationEffect(location);
task.AddEffect(effect);}
else throw new Exception("Tried to add an Effect, but the Pointer is not a Primitive Task!");return this;}
Custom operator in domain builder
To add a custom operator, we need to override the IOperator interface.
public class MoveToOperator:IOperator
{private Location _location;
private Speed _speed;
public MoveToOperator(Location location, Speed speed){_location = location;_speed = speed;}
public TaskStatus Update(IContext ctx)
{if(ctx is MyContext c){if(c.NavAgent.isStopped)return InitiateMovement(c);
return TickMovement(c);}
throw new Exception("Unexpected context type!");}
public void Stop(IContext ctx)
{if(ctx is MyContext c) {c.NavAgent.isStopped=true;return;}
throw new Exception("Unexpected context type!");}
private TaskStatus InitiateMovement(MyContext c)
{c.NavAgent.speed=_speed==Speed.Walk?WalkSpeed:RunSpeed;
switch(_location)
{case Location.Enemy:
if (ctx.NavAgent.SetDestination(ctx.BridgeLocation)){
ctx.NavAgent.isStopped = false;
return TaskStatus.Continue;}
else return TaskStatus.Failure;
case Location.Bridge:
//...}
return TaskStatus.Failure;}
private TaskStatus TickMovement(MyContext c)
{if(c.NavAgent.remainingDistance>c.NavAgent.stoppingDistance)
return TaskStatus.Continue;
c.NavAgent.isStopped=true;
return TaskStatus.Success;}}
Next, we can extend our MyDomainBuilder with a new function that expose this operator.
public MyDomainBuilder MoveTo(Location location,Speed speed)
{Action($"MoveTo({location},{speed})");
if(Pointer is IPrimitiveTask task)
{var op = new MoveToOperator(location, speed);
task.SetOperator(op);}
else throw new Exception("Tried to add an Operator, but the Pointer is not a Primitive Task!");
return this;}
Note that we both called Action(...), which sets the Pointer, and the SetOperator(...), but we didn't call End() to close the Pointer. This is so that we could be free to add Effects and Conditions to the action, but it means that the user must remember to call End() manually.
Custom selectors in domain builder
We're not limited to extend the domain builder with just conditions, effects and operators. We can also extend the capabilities of our selectors and sequences. Let's implement a Random Selector that will decompose into a random sub-task.
using FluidHTN.PrimitiveTasks;
namespace FluidHTN.Compounds
{public class RandomSelector : Selector{
protected Random _random = new Random();
DecompositionStatus OnDecompose(IContext ctx,int startIndex,out Queue result)
{Plan.Clear();
var taskIndex=_random.Next(startIndex, Subtasks.Count);
var task=Subtasks[taskIndex];
return OnDecomposeTask(ctx,task,taskIndex,null,out result);}}}
We can now extend our MyDomainBuilder with this new type of selector.
public DB RandomSelect(string name){return CompoundTask(name);}
Tips for domain builder usage
We can use the domain builder to create complex sub-domains with auto-indentation, in addition to simple tasks, conditions, and effects. However, we cannot add conditions and effects outside of the function. This approach is suitable for specialized sub-domains and improves the readability of the domain definition. For example, we can modify the domain definition as follows:
var domai =new MyDomainBuilder("Trunk Thumper").AttackEnemySequence().PatrolNextBridgeSequence().Build();
Let's extend out MyDomainBuild with these new sequences.
public DB AttackEnemySequence()
{Sequence("Attack enemy");{
IfEnemy();
MoveTo(Location.Enemy, Speed.Sprint);
{SetLocation(Location.Enemy);
SetIsTired();}
End();
TrunkSlam();
{IfLocation(Location.Enemy);}
End();}
End();
return this;}
public DB PatrolNextBridgeSequence()
{Sequence("Patrol next bridge");
{FindBridge();
{}
End();
MoveTo(Location.Bridge,Speed.Walk);
{SetLocation(Location.Bridge);}
End();
CheckBridge();
{IfLocation(Location.Bridge);
SetBored();}
End();
}End();return this;}
Custom factory
In implementing MyContext, we overrode Factory with DefaultFactory, which was also passed to BaseDomainBuilder when extending domain builders. You can create your own factory methods like PooledFactory and use it through the IFactory interface. DefaultFactory uses normal new operations and sets the collection reference to null when Free* API is called. The IFactory's Create* and Free* API supports pooling but it's up to the user to decide how they prefer to implement it.
Debugging the planner
To debug the planner, set the LogDecomposition flag to true in the context definition to store information about condition success and failure during decomposition. Use the DecompositionLog property to read out the logs, and apply context log calls to custom extensions. Set DebugMTR to true to track the method traversal record, and LastMTRDebug to track the previous traversal record when a plan was replaced. These debug properties are abstract in BaseContext to allow for flexibility in different environments.
Callback hooks in the planner
Planner callback hooks are available for additional insight and other purposes. These include OnNewPlan, OnReplacePlan, OnNewTask, OnNewTaskConditionFailed, OnStopCurrentTask, OnCurrentTaskCompletedSuccessfully, OnApplyEffect, and OnCurrentTaskFailed.
- NPCController
The NPCController class is the central point of control for NPC management. It is responsible for initializing and updating other subsystems such as FluidHTNController, QuestSystem, CombatSystem, InventorySystem, and DialogueSystem.
Responsibilities:
- Initialize the subsystems during NPC creation.
- Update the subsystems each frame to keep them in sync with the NPC state.
- Facilitate communication between subsystems as needed.
Interactions:
- FluidHTNController: Provides actions, decisions, and world state updates.
- QuestSystem: Offers functionality for creating, accepting, and completing quests.
- CombatSystem: Manages combat interactions, health, attack, and defense processes.
- InventorySystem: Handles inventory management, equipment, and item usage.
- DialogueSystem: Manages dialogue interactions with other NPCs and acquiring world information.
- FluidHTNController
The FluidHTNController class manages the HTN (Hierarchical Task Network) for NPC actions and decisions. It uses FluidHTN's DomainBuilder, Planner, and Context classes to define the NPC's behavior.
Responsibilities:
- Define NPC behavior through DomainBuilder.
- Generate and execute plans based on the world state and NPC context.
- Handle partial planning and domain splicing to create dynamic interactions.
Interactions:
- NPCController: Retrieves information about the NPC's world state and handles execution of tasks.
- DomainBuilder: Defines the NPC's behavior in a hierarchical structure.
- Planner: Generates and executes plans.
- QuestSystem
The QuestSystem class manages the NPC's ability to create, take, and complete quests. It offers functionality for quest creation, assignment, completion, and reward management.
Responsibilities:
- Create quests with objectives and rewards.
- Assign quests to NPCs.
- Track and manage quest progress.
- Handle quest completion and reward distribution.
Interactions:
- NPCController: Obtains quest-related information from the NPC.
- CombatSystem
The CombatSystem class manages the NPC's combat abilities and interactions with other NPCs. It handles attack, defense, and health management.
Responsibilities:
- Determine potential targets for combat.
- Execute attack and defense actions.
- Manage health and death events.
Interactions:
- NPCController: Gathers information about the NPC's state and communicates combat actions.
- InventorySystem
The InventorySystem class is responsible for managing the NPC's items, inventory, and equipment. It offers functionality for picking up items, managing inventory slots, equipping items, and trading them.
Responsibilities:
- Manage inventory slots and item storage.
- Handle picking up, dropping, and trading items.
- Equip items and manage equipped item slots.
Interactions:
- NPCController: Retrieves information about the NPC's world state and item interactions.
- DialogueSystem
The DialogueSystem class is responsible for managing the NPC's dialogue interactions with other NPCs and learning about the world through these interactions.
Responsibilities:
- Create and manage dialogue trees.
- Execute dialogue interactions with other NPCs.
- Learn world information and trigger events based on dialogue outcomes.
Interactions:
- NPCController: Gathers information about the NPC's world state and other NPCs for conversation management.
- Quest
The Quest class represents a single quest that can be created, taken, and completed by NPCs. It encapsulates information about objectives, rewards, and progress.
Responsibilities:
- Store quest objectives, descriptions, and rewards.
- Track quest progress and completion status.
- Provide methods for updating objectives and completion status.
Interactions:
- QuestSystem: Manages multiple Quest instances and their interactions with NPCs.
- Item
The Item class represents a single item that can be picked up, equipped, used, or traded by NPCs.
Responsibilities:
- Store item properties such as type, name, icon, and stats.
- Provide methods for item usage, triggering effects, or modifying NPC attributes.
Interactions:
- InventorySystem: Manages multiple Item instances and their interactions with NPCs and the world.
- DialogueNode
The DialogueNode class represents a single node in the dialogue tree, containing information about the speaker, dialogue text, and possible responses.
Responsibilities:
- Store information about the speaker, the dialogue text, and any responses or conditions.
- Provide methods for traversing and selecting responses in the dialogue tree.
Interactions:
- DialogueSystem: Manages multiple DialogueNode instances and their traversal during NPC conversations.
- ActionBar
The ActionBar class manages the NPC's abilities and skills, with functions for adding, removing, and executing these abilities.
Responsibilities:
- Store a collection of abilities and skills.
- Provide methods for adding, removing, and executing abilities.
Interactions:
- CombatSystem: Accesses the ActionBar to execute abilities during combat situations.
- NPCController: Keeps the ActionBar updated with the NPC's current abilities and skills.
- StatusEffect
The StatusEffect class represents a single status effect that can be applied to an NPC, such as buffs, debuffs, or crowd control effects.
Responsibilities:
- Store information about the effect, such as type, duration, and magnitude.
- Provide methods for applying, updating, and removing the effect on an NPC.
Interactions:
- CombatSystem: Applies and manages StatusEffect instances during combat encounters.
- Item: Items can apply StatusEffect instances to NPCs when used.
- NPCData
The NPCData class stores information about NPC properties, like appearance, stats, faction, and other attributes.
Responsibilities:
- Store NPC properties, such as appearance, stats, faction, and NPC type.
- Provide methods for modifying NPC properties and attributes.
Interactions:
- NPCController: Accesses NPCData to update the NPC's appearance, stats, and attributes during gameplay.
These additional classes improve the readability and modularity of the code by breaking down complex systems into smaller, more manageable components. They follow the SOLID principles, where each class is responsible for a single aspect of functionality, making it easier to maintain and understand the overall code structure.
- Ability
The Ability class represents a single ability that an NPC can perform, such as an attack, a heal, or a buff.
Responsibilities:
- Store information about the ability, including its name, description, and action type.
- Provide methods for executing the ability, including applying effects and triggering animations or particles.
Interactions:
- ActionBar: Manages multiple Ability instances and their execution.
- CombatSystem: Executes abilities during combat situations.
- NPCController: Accesses Ability instances to perform actions.
- Objective
The Objective class represents a single quest objective that an NPC must complete to progress in a quest.
Responsibilities:
- Store information about the quest objective, such as description, completion status, and requirements.
- Provide methods for updating the completion status and requirements.
Interactions:
- Quest: Manages multiple Objective instances within a quest.
- ItemDatabase
The ItemDatabase class serves as a central storage and repository of all item definitions in the game world.
Responsibilities:
- Store item definitions and their attributes.
- Provide methods for retrieving item definitions based on ID or name.
Interactions:
- InventorySystem: Retrieves item definitions from the ItemDatabase for item creation and management.
- NPCController: Accesses the ItemDatabase to spawn items in the world or add them to the NPC's inventory.
- DialogTree
The DialogTree class represents a collection of DialogueNodes organized in a tree structure for NPC dialogue interactions.
Responsibilities:
- Store DialogueNodes and maintain their tree structure.
- Provide methods for traversing the dialogue tree and accessing specific nodes.
Interactions:
- DialogueSystem: Manages multiple DialogTree instances and their interactions with NPCs.
- NPCManager
The NPCManager class serves as a central point for managing and controlling all existing NPCs in the game world.
Responsibilities:
- Store a collection of NPCs in the game world.
- Provide methods for creating, updating, and removing NPCs.
Interactions:
- NPCController: The NPCManager creates, updates, and removes instances of NPCController as necessary during gameplay.
- WorldState
The WorldState class represents the current state of the game world, including environment conditions, factions, and global events.
Responsibilities:
- Store information about the game world's state.
- Provide methods for updating and querying the world state.
Interactions:
- NPCController: Accesses the WorldState to make informed decisions based on the world's current conditions.
By incorporating these additional classes, the code structure becomes more modular, making it far more intuitive to understand and maintain. By assigning specific responsibilities to each class and ensuring intercommunication, the game logic remains well-organized, and overall system complexity is reduced. As a result, future updates, bug fixes, or extensions can be more easily implemented, adhering to the SOLID principles.