extend the docs and examples in skeleton.cpp

develop
myk002 2022-08-02 18:40:50 -07:00 committed by Myk
parent 2f9021a3a0
commit 0bbbacf161
1 changed files with 134 additions and 87 deletions

@ -1,65 +1,71 @@
// This is a generic plugin that does nothing useful apart from acting as an example... of a plugin that does nothing :D // This is an example plugin that just documents and implements all the plugin
// callbacks and features. You can compile it, load it, run it, and see the
// debug messages get printed to the console.
//
// See the other example plugins in this directory for plugins that are
// configured for specific use cases (but don't come with as many comments as
// this one does).
#include <string>
#include <vector>
#include "df/world.h"
// some headers required for a plugin. Nothing special, just the basics.
#include "Core.h" #include "Core.h"
#include <Console.h> #include "Debug.h"
#include <Export.h> #include "LuaTools.h"
#include <PluginManager.h> #include "PluginManager.h"
#include <modules/EventManager.h>
// If you need to save data per-world:
//#include "modules/Persistence.h"
// DF data structure definition headers #include "modules/Persistence.h"
#include "DataDefs.h" #include "modules/World.h"
//#include "df/world.h"
// our own, empty header. using std::string;
#include "skeleton.h" using std::vector;
using namespace DFHack; using namespace DFHack;
using namespace df::enums;
// Expose the plugin name to the DFHack core, as well as metadata like the DFHack version. // Expose the plugin name to the DFHack core, as well as metadata like the
// The name string provided must correspond to the filename - // DFHack version that this plugin was compiled with. This macro provides a
// variable for the plugin name as const char * plugin_name.
// The name provided must correspond to the filename --
// skeleton.plug.so, skeleton.plug.dylib, or skeleton.plug.dll in this case // skeleton.plug.so, skeleton.plug.dylib, or skeleton.plug.dll in this case
DFHACK_PLUGIN("skeleton"); DFHACK_PLUGIN("skeleton");
// The identifier declared with this macro (ie. enabled) can be specified by the user // The identifier declared with this macro (i.e. is_enabled) is used to track
// and subsequently used to manage the plugin's operations. // whether the plugin is in an "enabled" state. If you don't need enablement
// This will also be tracked by `plug`; when true the plugin will be shown as enabled. // for your plugin, you don't need this line. This variable will also be read
DFHACK_PLUGIN_IS_ENABLED(enabled); // by the `plug` builtin command; when true the plugin will be shown as enabled.
DFHACK_PLUGIN_IS_ENABLED(is_enabled);
// Any globals a plugin requires (e.g. world) should be listed here. // Any globals a plugin requires (e.g. world) should be listed here.
// For example, this line expands to "using df::global::world" and prevents the // For example, this line expands to "using df::global::world" and prevents the
// plugin from being loaded if df::global::world is null (i.e. missing from symbols.xml): // plugin from being loaded if df::global::world is null (i.e. missing from
// // symbols.xml).
REQUIRE_GLOBAL(world); REQUIRE_GLOBAL(world);
// You may want some compile time debugging options // logging levels can be dynamically controlled with the `debugfilter` command.
// one easy system just requires you to cache the color_ostream &out into a global debug variable namespace DFHack {
//#define P_DEBUG 1 // for configuration-related logging
//uint16_t maxTickFreq = 1200; //maybe you want to use some events DBG_DECLARE(skeleton, status, DebugCategory::LINFO);
// for logging during the periodic scan
DBG_DECLARE(skeleton, cycle, DebugCategory::LINFO);
}
command_result command_callback1(color_ostream &out, std::vector<std::string> &parameters); command_result command_callback1(color_ostream &out, vector<string> &parameters);
// run when the plugin is loaded
DFhackCExport command_result plugin_init(color_ostream &out, std::vector<PluginCommand> &commands) { DFhackCExport command_result plugin_init(color_ostream &out, std::vector<PluginCommand> &commands) {
commands.push_back(PluginCommand("skeleton", // For in-tree plugins, don't use the "usage" parameter of PluginCommand.
"~54 character description of plugin", //to use one line in the ``[DFHack]# ls`` output // Instead, add an .rst file with the same name as the plugin to the
command_callback1, // docs/plugins/ directory.
false, commands.push_back(PluginCommand(
"example usage" "skeleton",
" skeleton <option> <args>\n" "Short (~54 character) description of command.", // to use one line in the ``[DFHack]# ls`` output
" explanation of plugin/command\n" command_callback1));
"\n"
" skeleton\n"
" what happens when using the command\n"
"\n"
" skeleton option1\n"
" what happens when using the command with option1\n"
"\n"));
return CR_OK; return CR_OK;
} }
// run when the plugin is unloaded
DFhackCExport command_result plugin_shutdown(color_ostream &out) { DFhackCExport command_result plugin_shutdown(color_ostream &out) {
// You *MUST* kill all threads you created before this returns. // You *MUST* kill all threads you created before this returns.
// If everything fails, just return CR_FAILURE. Your plugin will be // If everything fails, just return CR_FAILURE. Your plugin will be
@ -68,28 +74,20 @@ DFhackCExport command_result plugin_shutdown(color_ostream &out) {
} }
// run when the `enable` or `disable` command is run with this plugin name as
// an argument
DFhackCExport command_result plugin_enable(color_ostream &out, bool enable) { DFhackCExport command_result plugin_enable(color_ostream &out, bool enable) {
namespace EM = EventManager; // you have to maintain the state of the is_enabled variable yourself. it
if (enable && !enabled) { // doesn't happen automatically.
//using namespace EM::EventType; is_enabled = enable;
//EM::EventHandler eventHandler(onNewEvent, maxTickFreq);
//EM::registerListener(EventType::JOB_COMPLETED, eventHandler, plugin_self);
//out.print("plugin enabled!\n");
} else if (!enable && enabled) {
EM::unregisterAll(plugin_self);
//out.print("plugin disabled!\n");
}
enabled = enable;
return CR_OK; return CR_OK;
} }
/* OPTIONAL *
// Called to notify the plugin about important state changes. // Called to notify the plugin about important state changes.
// Invoked with DF suspended, and always before the matching plugin_onupdate. // Invoked with DF suspended, and always before the matching plugin_onupdate.
// More event codes may be added in the future. // More event codes may be added in the future.
DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event) { DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event) {
if (enabled) { if (is_enabled) {
switch (event) { switch (event) {
case SC_UNKNOWN: case SC_UNKNOWN:
break; break;
@ -116,9 +114,8 @@ DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_chan
return CR_OK; return CR_OK;
} }
// Whatever you put here will be done in each game step. Don't abuse it. // Whatever you put here will be done in each game frame refresh. Don't abuse it.
DFhackCExport command_result plugin_onupdate ( color_ostream &out ) DFhackCExport command_result plugin_onupdate (color_ostream &out) {
{
// whetever. You don't need to suspend DF execution here. // whetever. You don't need to suspend DF execution here.
return CR_OK; return CR_OK;
} }
@ -128,44 +125,94 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out )
// and plugin_load_data is called whenever a new world is loaded. If the plugin // and plugin_load_data is called whenever a new world is loaded. If the plugin
// is loaded or unloaded while a world is active, plugin_save_data or // is loaded or unloaded while a world is active, plugin_save_data or
// plugin_load_data will be called immediately. // plugin_load_data will be called immediately.
DFhackCExport command_result plugin_save_data (color_ostream &out) DFhackCExport command_result plugin_save_data (color_ostream &out) {
{
// Call functions in the Persistence module here. // Call functions in the Persistence module here.
return CR_OK; return CR_OK;
} }
DFhackCExport command_result plugin_load_data (color_ostream &out) DFhackCExport command_result plugin_load_data (color_ostream &out) {
{
// Call functions in the Persistence module here. // Call functions in the Persistence module here.
return CR_OK; return CR_OK;
} }
* OPTIONAL */
// define the structure that will represent the possible commandline options
struct command_options {
// A command! It sits around and looks pretty. And it's nice and friendly. // whether to display help
command_result command_callback1(color_ostream &out, std::vector<std::string> &parameters) { bool help = false;
// It's nice to print a help message you get invalid options
// from the user instead of just acting strange. // whether to run a cycle right now
// This can be achieved by adding the extended help string to the bool now = false;
// PluginCommand registration as show above, and then returning
// CR_WRONG_USAGE from the function. The same string will also // how many ticks to wait between cycles when enabled, -1 means unset
// be used by 'help your-command'. int32_t ticks = -1;
if (!parameters.empty()) {
return CR_WRONG_USAGE; //or maybe you want it to do something else // example params of different types
df::coord start;
string format;
vector<string*> list; // note this must be a vector of pointers, not objects
static struct_identity _identity;
};
static const struct_field_info command_options_fields[] = {
{ struct_field_info::PRIMITIVE, "help", offsetof(command_options, help), &df::identity_traits<bool>::identity, 0, 0 },
{ struct_field_info::PRIMITIVE, "now", offsetof(command_options, now), &df::identity_traits<bool>::identity, 0, 0 },
{ struct_field_info::PRIMITIVE, "ticks", offsetof(command_options, ticks), &df::identity_traits<int32_t>::identity, 0, 0 },
{ struct_field_info::SUBSTRUCT, "start", offsetof(command_options, start), &df::coord::_identity, 0, 0 },
{ struct_field_info::PRIMITIVE, "format", offsetof(command_options, format), df::identity_traits<string>::get(), 0, 0 },
{ struct_field_info::STL_VECTOR_PTR, "list", offsetof(command_options, list), df::identity_traits<string>::get(), 0, 0 },
{ struct_field_info::END }
};
struct_identity command_options::_identity(sizeof(command_options), &df::allocator_fn<command_options>, NULL, "command_options", NULL, command_options_fields);
// load the lua module associated with the plugin and parse the commandline
// in lua (which has better facilities than C++ for string parsing). You should
// create a file named after your plugin in the plugins/lua directory. This
// example expects you to define a global function in that file named
// "parse_commandline" that takes the options struct defined above along with
// the commandline parameters. It should parse the parameters and set data in
// the options structure. See plugins/lua/skeleton.lua for an example.
static bool get_options(color_ostream &out,
command_options &opts,
const vector<string> &parameters)
{
auto L = Lua::Core::State;
Lua::StackUnwinder top(L);
if (!lua_checkstack(L, parameters.size() + 2) ||
!Lua::PushModulePublic(
out, L, ("plugins." + string(plugin_name)).c_str(),
"parse_commandline")) {
out.printerr("Failed to load %s Lua code\n", plugin_name);
return false;
} }
// Commands are called from threads other than the DF one.
// Suspend this thread until DF has time for us. Lua::Push(L, &opts);
// **If you use CoreSuspender** it'll automatically resume DF when for (const string &param : parameters)
// execution leaves the current scope. Lua::Push(L, param);
if (!Lua::SafeCall(out, L, parameters.size() + 1, 0))
return false;
return true;
}
// This is the callback we registered in plugin_init. Note that while plugin
// callbacks are called with the core suspended, command callbacks are called
// from a different thread and need to explicity suspend the core if they
// interact with Lua or DF game state (most commands do at least one of these).
static command_result command_callback1(color_ostream &out, vector<string> &parameters) {
// I'll say it again: always suspend the core in command callbacks unless
// all your data is local.
CoreSuspender suspend; CoreSuspender suspend;
// Actually do something here. Yay.
// process parameters // Return CR_WRONG_USAGE to print out your help text. The help text is
if (parameters.size() == 1 && parameters[0] == "option1") { // sourced from the associated rst file in docs/plugins/. The same help will
// stuff // also be returned by 'help your-command'.
} else { command_options opts;
return CR_FAILURE; if (!get_options(out, opts, parameters) || opts.help)
} return CR_WRONG_USAGE;
// Give control back to DF.
// TODO: do something according to the flags set in the options struct
return CR_OK; return CR_OK;
} }