API: Difference between revisions

From Citizens Wiki

No edit summary
No edit summary
(23 intermediate revisions by 4 users not shown)
Line 10: Line 10:
<div class="padded" style="padding: 19px">
<div class="padded" style="padding: 19px">


'''Current Release Download:''' [http://ci.citizensnpcs.com/ Jenkins]
'''Current Release Download:''' [http://ci.citizensnpcs.co/ Jenkins]


'''Developmental Builds:''' [http://ci.citizensnpcs.com/job/CitizensAPI/ Jenkins]
'''Developmental Builds:''' [http://ci.citizensnpcs.co/job/CitizensAPI/ Jenkins]


'''Documentation:''' [http://jd.citizensnpcs.com/ JavaDocs]
'''Documentation:''' [http://jd.citizensnpcs.co/ JavaDocs]


'''Source:''' [https://github.com/CitizensDev/CitizensAPI Github]
'''Source:''' [https://github.com/CitizensDev/CitizensAPI Github]
Line 23: Line 23:
Citizens has an extensive API that can be used for making your plugins work with NPCs or even for adding a brand new character that can be attached to an NPC. Make sure you always are using an up-to-date build of the CitizensAPI to ensure that your plugin works with the latest release of Citizens.
Citizens has an extensive API that can be used for making your plugins work with NPCs or even for adding a brand new character that can be attached to an NPC. Make sure you always are using an up-to-date build of the CitizensAPI to ensure that your plugin works with the latest release of Citizens.


Javadocs can be found at http://jd.citizensnpcs.com
Javadocs can be found at http://jd.citizensnpcs.co
 
'''IF YOU HAVE TROUBLE USING THE API''' please speak to us on GitHub at https://github.com/CitizensDev/Citizens2/issues OR on Discord at https://discord.gg/Q6pZGSR
 
 
==Linking Properly In Java==
 
Citizens, like most Java projects, is built using Maven. Your plugin that links to Citizens should be using Maven as well.
 
In your <code>pom.xml</code> (Maven project) file, you can use this repository:
 
<pre>
    <repository>
        <id>everything</id>
        <url>http://repo.citizensnpcs.co/</url>
    </repository>
</pre>
 
and this dependency:
<pre>
    <dependency>
        <groupId>net.citizensnpcs</groupId>
        <artifactId>citizens</artifactId>
        <version>VERSION</version>
        <type>jar</type>
        <scope>provided</scope>
    </dependency>
</pre>
 
And replace <code>VERSION</code> with the current version of Citizens (check the filenames at http://ci.citizensnpcs.co/job/Citizens2/ for current version ID), formatted like <code>2.0.23-SNAPSHOT</code> (but with the version numbers changed to the relevant version).
 
Note that for most purposes, it's best to link <code>citizens</code> rather than the API project, as many useful classes and utilities are not in the API. The main Citizens project ''includes'' the API and adds more options.


==Hooking Into Citizens==
==Hooking Into Citizens==
Hooking into Citizens is as simple as creating a basic plugin and adding the line
Hooking into Citizens is as simple as creating a basic plugin and adding the line
depend: [Citizens] into your plugin.yml. From here, a common basic entry point is the CitizensAPI class. This gives you access to the NPCRegistry for NPC lookup, as well as the TraitFactory which allows trait registration.
depend: [Citizens] into your plugin.yml. From here, a common basic entry point is the CitizensAPI class. This gives you access to the NPCRegistry for NPC lookup, as well as the TraitFactory which allows trait registration. If Citizens is not loaded, all CitizensAPI.* methods will return null.
 
== Creating an NPC ==
The simplest way to create an NPC is to use an NPCRegistry, which manages the storage and creation of NPCs. The default registry is given by CitizensAPI.getNPCRegistry(), and you can create new ones with different storage methods by calling other CitizensAPI methods. A Player NPC with name "fullwall" could then be created like this:
NPC npc = CitizensAPI.getNPCRegistry().createNPC(EntityType.PLAYER, "fullwall");


== Checking if an entity is a Citizens NPC ==
== Checking if an entity is a Citizens NPC ==
Line 33: Line 68:
Eg.  
Eg.  
  boolean isCitizensNPC = entity.hasMetadata("NPC");
  boolean isCitizensNPC = entity.hasMetadata("NPC");
PLEASE NOTE: Players sharing names with NPCs will have the same metadata as the NPC as per https://bukkit.atlassian.net/browse/BUKKIT-2501. Working on a fix for this.


==Creating a Trait==
==Creating a Trait==
Traits are persistent, attachable objects that are linked to an NPC and provide specific functionality. This can be anything from a full-blown dynamic villager AI to a simple talking trait.
Traits are persistent, attachable objects that are linked to an NPC and provide specific functionality. This can be anything from a full-blown dynamic villager AI to a simple talking trait.
If using Maven, Citizens' Maven repo is available at http://repo.citizensnpcs.co


To register a trait, we use the '''TraitFactory''' class. This controls registration for your custom traits.
To register a trait, we use the '''TraitFactory''' class. This controls registration for your custom traits.
{{codebox|height=300px|width=100%|Example registration and simple trait|<syntaxhighlight lang="java5">
{{codebox|height=300px|width=100%|Example registration and simple trait|<pre>
//This is your trait that will be applied to a npc using the /trait mytraitname command. Each NPC gets its own instance of this class.
//This is your trait that will be applied to a npc using the /trait mytraitname command. Each NPC gets its own instance of this class.
//the Trait class has a reference to the attached NPC class through 'npc' or getNPC().
//the Trait class has a reference to the attached NPC class through the protected field 'npc' or getNPC().
//The Trait class also implements Listener so you can add EventHandlers directly to your trait.
//The Trait class also implements Listener so you can add EventHandlers directly to your trait.
@TraitName("mytraitname") // convenience annotation in recent CitizensAPI versions for specifying trait name
public class MyTrait extends Trait {
public class MyTrait extends Trait {
public MyTrait() {
public MyTrait() {
super("mytraitname");
super("mytraitname");
plugin = (MyPlugin) Bukkit.getServer().getPluginManager().getPlugin("MyPlugin");
plugin = JavaPlugin.getPlugin(MyPlugin.class);
}
}


Line 54: Line 89:


boolean SomeSetting = false;
boolean SomeSetting = false;
       
        // see the 'Persistence API' section
        @Persist("mysettingname") boolean automaticallyPersistedSetting = false;


//Here you should load up any values you have previously saved.  
// Here you should load up any values you have previously saved (optional).  
         //This does NOT get called when applying the trait for the first time, only loading onto an existing npc at server start.
         // This does NOT get called when applying the trait for the first time, only loading onto an existing npc at server start.
         //This is called AFTER onAttach so you can load defaults in onAttach and they will be overridden here.
         // This is called AFTER onAttach so you can load defaults in onAttach and they will be overridden here.
         //This is called BEFORE onSpawn so do not try to access npc.getBukkitEntity(). It will be null.
         // This is called BEFORE onSpawn, npc.getBukkitEntity() will return null.
public void load(DataKey key) {
public void load(DataKey key) {
SomeSetting = key.getBoolean("SomeSetting", false);
SomeSetting = key.getBoolean("SomeSetting", false);
}
}


//Save settings for this NPC. These values will be added to the citizens saves.yml under this NPC.
// Save settings for this NPC (optional). These values will be persisted to the Citizens saves file
public void save(DataKey key) {
public void save(DataKey key) {
key.setBoolean("SomeSetting",SomeSetting);
key.setBoolean("SomeSetting",SomeSetting);
}
}


        // An example event handler. All traits will be registered automatically as Bukkit Listeners.
@EventHandler
@EventHandler
public void click(net.citizensnpcs.api.event.NPCClickEvent event){
public void click(net.citizensnpcs.api.event.NPCClickEvent event){
Line 74: Line 113:
}
}
 
     
        // Called every tick
        @Override
        public void run() {
        }


//Run code when your trait is attached to a NPC.  
//Run code when your trait is attached to a NPC.  
         //This is called BEFORE onSpawn so do not try to access npc.getBukkitEntity(). It will be null.
         //This is called BEFORE onSpawn, so npc.getBukkitEntity() will return null
         //This would be a good place to load configurable defaults for new NPCs.
         //This would be a good place to load configurable defaults for new NPCs.
@Override
@Override
Line 117: Line 160:


//Register your trait with Citizens.         
//Register your trait with Citizens.         
net.citizensnpcs.api.CitizensAPI.getTraitFactory().registerTrait(net.citizensnpcs.api.trait.TraitInfo.create(MyTrait.class).withName("mytraitname"));
net.citizensnpcs.api.CitizensAPI.getTraitFactory().registerTrait(net.citizensnpcs.api.trait.TraitInfo.create(MyTrait.class));
}
}


Line 126: Line 169:
}
}


</syntaxhighlight>
</pre>
}}
}}
===Do's an Don't===
===Dos and Don'ts===
'''{{color|green|white|DO}}'''
'''{{color|green|white|DO}}'''
* Check npc.isSpawned() before using npc.getBukkitEntity()
* Check npc.isSpawned() before using npc.getBukkitEntity()
* Check npc.isSpawned() before using npc.getNavigator()
* Check npc.isSpawned() before using npc.getNavigator()
* Create a separate singleton Listener class if you expect there to be many instances of this trait running. This will help performance.
* Create a separate singleton Listener class if you expect there to be many instances of this trait running. This may help performance with frequently called events.
* Honor npc.data().get(NPC.DEFAULT_PROTECTED_METADATA) If this is true the NPC should be 'invulnerable' to normal damaging effects.
* Honor npc.data().get(NPC.DEFAULT_PROTECTED_METADATA) If this is true the NPC should be 'invulnerable' to normal damaging effects.
* use CitizensAPI.getNPCRegistry().isNPC() to check if an entity is a NPC. Real players and player-type NPCs will both return true for instanceof Player.
* use CitizensAPI.getNPCRegistry().isNPC() to check if an entity is a NPC. Real players and player-type NPCs will both return true for instanceof Player.
'''{{color|red|white|DON'T}}'''
* Attempt to access npc.getBukkitEntity() from within traits until onSpawn() has been called or npc.isSpawned() returns true.
* Change anything in npc.getNavigator.getDefaultParams() unless you're sure you want a global change. Use the localParams() instead ''after'' setting a navigation target.
* Assume a NPC is a player-type. Mob types have some important differences.
===Download an example===
===Download an example===
This is a link to a an example trait. It is similar to the code above, with some additional code for better handling commands, default configuration, and a plugin.yml
This is a link to a an example trait. It is similar to the code above, with some additional code for better handling commands, default configuration, and a plugin.yml
*[[https://github.com/downloads/jrbudda/Citizens2/Citizens%20MyTrait%20Example.zip Download it here]]
*[https://github.com/jrbudda/Citizens2/downloads Download it here]
You will also need to build against [[http://ci.citizensnpcs.com/job/CitizensAPI/ CitizensAPI.jar]] and [[http://dl.bukkit.org/downloads/bukkit/ Bukkit.jar]].
You will need to build against [http://ci.citizensnpcs.co/job/CitizensAPI/ CitizensAPI.jar],[http://ci.citizensnpcs.co/job/Citizens2/ Citizens.jar] (although this is not always required),  and [http://dl.bukkit.org/downloads/bukkit/ Bukkit.jar].
 
 
'''{{color|red|white|DON'T}}'''
* Change event data other than to cancel/uncancel it.
* Attempt to access npc.GetBukkitEntity() until onSpawn() has been called.
* Change anything in npc.getNavigator.getDefaultParams(). Use the localParams() instead after setting a navigation target.
* Assume a NPC is a player-type. Mob types have some important differences (like no inventory).


==NPC Events==
==NPC Events==
Line 151: Line 192:
Citizens currently provides the following:
Citizens currently provides the following:
*EntityTargetNPCEvent
*EntityTargetNPCEvent
*NPCChatEvent
*NPCClickEvent
*NPCClickEvent
*NPCCollisionEvent
*NPCCollisionEvent
Line 159: Line 201:
*NPCDamageByEntityEvent
*NPCDamageByEntityEvent
*NPCDamageEvent
*NPCDamageEvent
*NPCDeathEvent
*NPCDespawnEvent
*NPCDespawnEvent
*NPCEvent
*NPCEvent
Line 167: Line 210:
*NPCSelectEvent
*NPCSelectEvent
*NPCSpawnEvent
*NPCSpawnEvent
*PlayerCreateNPCEvent


See the [[http://jd.citizensnpcs.com/ Javadocs]] for details.
See the [[http://jd.citizensnpcs.co/ Javadocs]] for details.


==Using the AI API==
==Using the AI API==
Line 177: Line 221:
The GoalSelector allows a great deal of flexibility within goal implementations. It allows firstly the dynamic selection of sub-goals and the concurrent execution of many sub-goals, and can stop execution at any time.
The GoalSelector allows a great deal of flexibility within goal implementations. It allows firstly the dynamic selection of sub-goals and the concurrent execution of many sub-goals, and can stop execution at any time.


{{codebox|height=300px|width=100%|Example|<syntaxhighlight lang="java5">
In recent versions of CitizensAPI the "Behavior" class is introduced which allows a behavior tree-based AI approach that is backwards compatible with Goals and GoalControllers.
 
{{codebox|height=300px|width=100%|Example|<pre lang="java5">
  public class MyGoal implements Goal {
  public class MyGoal implements Goal {
     private Object state;
     private Object state;
Line 202: Line 248:
     }
     }
  }
  }
</syntaxhighlight>
</pre>
}}
}}


The second concept is the ''Navigator''. This controls the pathfinding aspects of the NPC. The Navigator can have one target at a time, and will call events to notify of completion/cancellation.
The second concept is the ''Navigator''. This controls the pathfinding aspects of the NPC. The Navigator can have one target at a time, and will call events to notify of completion/cancellation:


The pathfinding range of the Navigator is the maximum range it will search when attempting to find a path to the target. This is usually set by the server admin. The speed of the Navigator is the movement speed of the NPC while moving to the target. The default speed is around 0.3.
*NavigationBeginEvent
*NavigationCancelEvent
*NavigationCompleteEvent
*NavigationEvent
*NavigationReplaceEvent
 
The pathfinding range of the Navigator is the maximum range it will search when attempting to find a path to the target. This is usually set by the server admin. The speed modifier of the Navigator is the % modified movement speed of the NPC while moving to the target.
 
==Using the Persistence API==
Sometimes, traits can store a lot of simple variables such as primitives, Strings, Locations, and others. Saving/loading them via the trait API can be a little bit of overkill.
 
Citizens 2.0.4+ provides a simple Persistence API to automatically save and load these variables using DataKeys. The key to this API is the @Persist annotation. Sample code is provided below.
{{codebox|height=300px|width=100%|Example|<pre lang="java5">
public class MyTrait extends Trait {
    // logic omitted.
 
    @Persist boolean myVariable = false; // the default value of @Persist saves the value under the field name (in this case, 'myVariable').
   
    @Persist("newkey") int intVariable = 11; // this saves the value under 'newkey'. The default value of the variable has been set to 11 - this will be used when loading if the key doesn't exist.
 
    @Persist(value="newkey", required=true) String required; // if the value under 'newkey' doesn't exist, then the trait will fail to load.
}
</pre>}}
 
More advanced use of the API can be found in the @DelegatePersistence annotation. This allows complex types such as Locations to be saved and loaded with finer grained control. These types can be given default delegates by calling PersistenceLoader#registerPersistDelegate(Persister) - Location has a built in Persister for convenience.
 
{{codebox|height=300px|width=100%|Example|<pre lang="java5">
public class MyTrait extends Trait {
    // logic omitted.
 
    @Persist
    @DelegatePersistence(ExplicitComplexTypePersister.class) // explicit delegation
    ComplexType myComplexType;
 
    @Persist ComplexType implicitComplexType; // implicit delegation
    static {
        PersistenceLoader.registerPersistDelegate(ImplicitComplexTypePersister.class);
    }
}
public class ExplicitComplexTypePersister implements Persister {
    public Object create(DataKey root) {
        return new ComplexType(root.getInteger("complexstructures"));
    }
    public void save(Object instance, DataKey root) {
        ComplexType real = (ComplexType) instance; // guaranteed cast - will always succeed.
        root.setInteger("complexstructures", real.getComplexStructure());
    }
}
</pre>}}


==See Also==
==See Also==

Revision as of 13:51, 9 October 2018

Current Release Download: Jenkins

Developmental Builds: Jenkins

Documentation: JavaDocs

Source: Github

Citizens has an extensive API that can be used for making your plugins work with NPCs or even for adding a brand new character that can be attached to an NPC. Make sure you always are using an up-to-date build of the CitizensAPI to ensure that your plugin works with the latest release of Citizens.

Javadocs can be found at http://jd.citizensnpcs.co

IF YOU HAVE TROUBLE USING THE API please speak to us on GitHub at https://github.com/CitizensDev/Citizens2/issues OR on Discord at https://discord.gg/Q6pZGSR


Linking Properly In Java

Citizens, like most Java projects, is built using Maven. Your plugin that links to Citizens should be using Maven as well.

In your pom.xml (Maven project) file, you can use this repository:

    <repository>
        <id>everything</id>
        <url>http://repo.citizensnpcs.co/</url>
    </repository>

and this dependency:

    <dependency>
        <groupId>net.citizensnpcs</groupId>
        <artifactId>citizens</artifactId>
        <version>VERSION</version>
        <type>jar</type>
        <scope>provided</scope>
    </dependency>

And replace VERSION with the current version of Citizens (check the filenames at http://ci.citizensnpcs.co/job/Citizens2/ for current version ID), formatted like 2.0.23-SNAPSHOT (but with the version numbers changed to the relevant version).

Note that for most purposes, it's best to link citizens rather than the API project, as many useful classes and utilities are not in the API. The main Citizens project includes the API and adds more options.

Hooking Into Citizens

Hooking into Citizens is as simple as creating a basic plugin and adding the line depend: [Citizens] into your plugin.yml. From here, a common basic entry point is the CitizensAPI class. This gives you access to the NPCRegistry for NPC lookup, as well as the TraitFactory which allows trait registration. If Citizens is not loaded, all CitizensAPI.* methods will return null.

Creating an NPC

The simplest way to create an NPC is to use an NPCRegistry, which manages the storage and creation of NPCs. The default registry is given by CitizensAPI.getNPCRegistry(), and you can create new ones with different storage methods by calling other CitizensAPI methods. A Player NPC with name "fullwall" could then be created like this:

NPC npc = CitizensAPI.getNPCRegistry().createNPC(EntityType.PLAYER, "fullwall");

Checking if an entity is a Citizens NPC

Citizens NPCs will have the "NPC" metadata set to true. Eg.

boolean isCitizensNPC = entity.hasMetadata("NPC");

Creating a Trait

Traits are persistent, attachable objects that are linked to an NPC and provide specific functionality. This can be anything from a full-blown dynamic villager AI to a simple talking trait.

If using Maven, Citizens' Maven repo is available at http://repo.citizensnpcs.co

To register a trait, we use the TraitFactory class. This controls registration for your custom traits.

Code: Example registration and simple trait
//This is your trait that will be applied to a npc using the /trait mytraitname command. Each NPC gets its own instance of this class.
//the Trait class has a reference to the attached NPC class through the protected field 'npc' or getNPC().
//The Trait class also implements Listener so you can add EventHandlers directly to your trait.
@TraitName("mytraitname") // convenience annotation in recent CitizensAPI versions for specifying trait name
public class MyTrait extends Trait {
	public MyTrait() {
		super("mytraitname");
		plugin = JavaPlugin.getPlugin(MyPlugin.class);
	}

	MyPlugin plugin = null;

	boolean SomeSetting = false;
        
        // see the 'Persistence API' section
        @Persist("mysettingname") boolean automaticallyPersistedSetting = false;

	// Here you should load up any values you have previously saved (optional). 
        // This does NOT get called when applying the trait for the first time, only loading onto an existing npc at server start.
        // This is called AFTER onAttach so you can load defaults in onAttach and they will be overridden here.
        // This is called BEFORE onSpawn, npc.getBukkitEntity() will return null.
	public void load(DataKey key) {
		SomeSetting = key.getBoolean("SomeSetting", false);
	}

	// Save settings for this NPC (optional). These values will be persisted to the Citizens saves file
	public void save(DataKey key) {
		key.setBoolean("SomeSetting",SomeSetting);
	}

        // An example event handler. All traits will be registered automatically as Bukkit Listeners.
	@EventHandler
	public void click(net.citizensnpcs.api.event.NPCClickEvent event){
		//Handle a click on a NPC. The event has a getNPC() method. 
		//Be sure to check event.getNPC() == this.getNPC() so you only handle clicks on this NPC!
		
	}
      
        // Called every tick
        @Override
        public void run() {
        }

	//Run code when your trait is attached to a NPC. 
        //This is called BEFORE onSpawn, so npc.getBukkitEntity() will return null
        //This would be a good place to load configurable defaults for new NPCs.
	@Override
	public void onAttach() {
		plugin.getServer().getLogger().info(npc.getName() + "has been assigned MyTrait!");
	}

        // Run code when the NPC is despawned. This is called before the entity actually despawns so npc.getBukkitEntity() is still valid.
	@Override
	public void onDespawn() {
        }

	//Run code when the NPC is spawned. Note that npc.getBukkitEntity() will be null until this method is called.
        //This is called AFTER onAttach and AFTER Load when the server is started.
	@Override
	public void onSpawn() {

	}

        //run code when the NPC is removed. Use this to tear down any repeating tasks.
	@Override
	public void onRemove() {
        }

}

//This is your bukkit plugin class. Use it to hook your trait into Citizens and handle any commands.
public class MyPlugin extends org.bukkit.plugin.java.JavaPlugin {

	public void onEnable() {
	
	//check if Citizens is present and enabled.

		if(getServer().getPluginManager().getPlugin("Citizens") == null || getServer().getPluginManager().getPlugin("Citizens").isEnabled() == false) {
			getLogger().log(Level.SEVERE, "Citizens 2.0 not found or not enabled");
			getServer().getPluginManager().disablePlugin(this);	
			return;
		}	

		//Register your trait with Citizens.        
		net.citizensnpcs.api.CitizensAPI.getTraitFactory().registerTrait(net.citizensnpcs.api.trait.TraitInfo.create(MyTrait.class));	
	}

	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] inargs) {
		//handle commands for /myplugin 
	}
}

Dos and Don'ts

DO

  • Check npc.isSpawned() before using npc.getBukkitEntity()
  • Check npc.isSpawned() before using npc.getNavigator()
  • Create a separate singleton Listener class if you expect there to be many instances of this trait running. This may help performance with frequently called events.
  • Honor npc.data().get(NPC.DEFAULT_PROTECTED_METADATA) If this is true the NPC should be 'invulnerable' to normal damaging effects.
  • use CitizensAPI.getNPCRegistry().isNPC() to check if an entity is a NPC. Real players and player-type NPCs will both return true for instanceof Player.

DON'T

  • Attempt to access npc.getBukkitEntity() from within traits until onSpawn() has been called or npc.isSpawned() returns true.
  • Change anything in npc.getNavigator.getDefaultParams() unless you're sure you want a global change. Use the localParams() instead after setting a navigation target.
  • Assume a NPC is a player-type. Mob types have some important differences.

Download an example

This is a link to a an example trait. It is similar to the code above, with some additional code for better handling commands, default configuration, and a plugin.yml

You will need to build against CitizensAPI.jar,Citizens.jar (although this is not always required), and Bukkit.jar.

NPC Events

Citizens implements its own Listeners and will call new NPC-specific versions of many common events. This saves Trait developers the trouble of finding their npcs from the normal event entities. The event object these events provide are just like their Bukkit counterparts with the addition of the getNPC() method. Citizens currently provides the following:

  • EntityTargetNPCEvent
  • NPCChatEvent
  • NPCClickEvent
  • NPCCollisionEvent
  • NPCCombustByBlockEvent
  • NPCCombustByEntityEvent
  • NPCCombustEvent
  • NPCDamageByBlockEvent
  • NPCDamageByEntityEvent
  • NPCDamageEvent
  • NPCDeathEvent
  • NPCDespawnEvent
  • NPCEvent
  • NPCLeftClickEvent
  • NPCPushEvent
  • NPCRemoveEvent
  • NPCRightClickEvent
  • NPCSelectEvent
  • NPCSpawnEvent
  • PlayerCreateNPCEvent

See the [Javadocs] for details.

Using the AI API

The AI API of Citizens can be broken down into two parts - GoalController and Navigator.

A Goal is a repeatable, abstract unit of work that can be performed by an NPC. It can be registered with a GoalController with a priority (higher is more important). The highest priority goal which can be executed will be prioritised. NPC contains getDefaultGoalController() for this purpose.

The GoalSelector allows a great deal of flexibility within goal implementations. It allows firstly the dynamic selection of sub-goals and the concurrent execution of many sub-goals, and can stop execution at any time.

In recent versions of CitizensAPI the "Behavior" class is introduced which allows a behavior tree-based AI approach that is backwards compatible with Goals and GoalControllers.


Code: Example
 public class MyGoal implements Goal {
     private Object state;
     private GoalSelector selector; // the current selector
     public void reset() {
         state = null;
         // this method can be called at any time - tear down any state
     }
     public void run() {
         if(!npcIsCool()) {
             selector.finish(); // stops execution
         } else if (npcIsAwesome()){
             selector.select(new AwesomeGoal()); // this switches execution to AwesomeGoal and stops execution of this goal.
         } else if (npcNeedsCool()) {
             selector.selectAdditional(new AccumulateCoolGoal()); // AccumulateCoolGoal executes concurrently to this goal.
         }
     }
     public boolean shouldExecute(GoalSelector selector) {
         if (npcIsCool()) {
             this.selector = selector;
             return true;
         }
         return false;
     }
 }

The second concept is the Navigator. This controls the pathfinding aspects of the NPC. The Navigator can have one target at a time, and will call events to notify of completion/cancellation:

  • NavigationBeginEvent
  • NavigationCancelEvent
  • NavigationCompleteEvent
  • NavigationEvent
  • NavigationReplaceEvent

The pathfinding range of the Navigator is the maximum range it will search when attempting to find a path to the target. This is usually set by the server admin. The speed modifier of the Navigator is the % modified movement speed of the NPC while moving to the target.

Using the Persistence API

Sometimes, traits can store a lot of simple variables such as primitives, Strings, Locations, and others. Saving/loading them via the trait API can be a little bit of overkill.

Citizens 2.0.4+ provides a simple Persistence API to automatically save and load these variables using DataKeys. The key to this API is the @Persist annotation. Sample code is provided below.

Code: Example
 public class MyTrait extends Trait {
     // logic omitted.

    @Persist boolean myVariable = false; // the default value of @Persist saves the value under the field name (in this case, 'myVariable').
    
    @Persist("newkey") int intVariable = 11; // this saves the value under 'newkey'. The default value of the variable has been set to 11 - this will be used when loading if the key doesn't exist.

    @Persist(value="newkey", required=true) String required; // if the value under 'newkey' doesn't exist, then the trait will fail to load.
 }

More advanced use of the API can be found in the @DelegatePersistence annotation. This allows complex types such as Locations to be saved and loaded with finer grained control. These types can be given default delegates by calling PersistenceLoader#registerPersistDelegate(Persister) - Location has a built in Persister for convenience.


Code: Example
 public class MyTrait extends Trait {
     // logic omitted.

    @Persist 
    @DelegatePersistence(ExplicitComplexTypePersister.class) // explicit delegation
    ComplexType myComplexType;

    @Persist ComplexType implicitComplexType; // implicit delegation
    static {
        PersistenceLoader.registerPersistDelegate(ImplicitComplexTypePersister.class);
    }
 }
 
 public class ExplicitComplexTypePersister implements Persister {
     public Object create(DataKey root) {
         return new ComplexType(root.getInteger("complexstructures"));
     }
     public void save(Object instance, DataKey root) {
         ComplexType real = (ComplexType) instance; // guaranteed cast - will always succeed.
         root.setInteger("complexstructures", real.getComplexStructure());
     }
 }

See Also

Characters