diff --git a/Compile.html b/Compile.html deleted file mode 100644 index d3559f4dd..000000000 --- a/Compile.html +++ /dev/null @@ -1,655 +0,0 @@ - - - - - - -Building DFHACK - - - -
-

Building DFHACK

- -
-

Contents

- -
-
-

Linux

-

On Linux, DFHack acts as a library that shadows parts of the SDL API using LD_PRELOAD.

-
-

How to get the code

-

DFHack doesn't have any kind of system of code snapshots in place, so you will have to get code from the github repository using git. -Having a 'git' package installed is the minimal requirement, but some sort of git gui or git integration for your favorite text editor/IDE will certainly help.

-

The code resides here: https://github.com/DFHack/dfhack

-

If you just want to compile DFHack or work on it by contributing patches, it's quite enough to clone from the read-only address:

-
-git clone git://github.com/DFHack/dfhack.git
-cd dfhack
-git submodule init
-git submodule update
-
-

If you want to get really involved with the development, create an account on github, make a clone there and then use that as your remote repository instead. Detailed instructions are beyond the scope of this document. If you need help, join us on IRC (#dfhack channel on freenode).

-
-
-

Dependencies

-

DFHack is meant to be installed into an existing DF folder, so get one ready.

-

For building, you need a 32-bit version of GCC. For example, to build DFHack on -a 64-bit distribution like Arch, you'll need the multilib development tools and libraries. -Alternatively, you might be able to use lxc to -create a virtual 32-bit environment.

-

Before you can build anything, you'll also need cmake. It is advisable to also get -ccmake on distributions that split the cmake package into multiple parts.

-

You also need perl and the XML::LibXML and XML::LibXSLT perl packages (for the code generation parts). -You should be able to find them in your distro repositories (on Arch linux 'perl-xml-libxml' and 'perl-xml-libxslt') or through cpan.

-

To build Stonesense, you'll also need OpenGL headers.

-
-
-

Build

-

Building is fairly straightforward. Enter the build folder and start the build like this:

-
-cd build
-cmake .. -DCMAKE_BUILD_TYPE:string=Release -DCMAKE_INSTALL_PREFIX=/home/user/DF
-make install
-
-

Obviously, replace the install path with path to your DF. This will build the library -along with the normal set of plugins and install them into your DF folder.

-

Alternatively, you can use ccmake instead of cmake:

-
-cd build
-ccmake ..
-make install
-
-

This will show a curses-based interface that lets you set all of the -extra options.

-

You can also use a cmake-friendly IDE like KDevelop 4 or the cmake-gui -program.

-
-
-

Fixing the libstdc++ version bug

-

When compiling dfhack yourself, it builds against your system libc. -When Dwarf Fortress runs, it uses a libstdc++ shipped with the binary, which -is usually way older, and incompatible with your dfhack. This manifests with -the error message:

-
-./libs/Dwarf_Fortress: /pathToDF/libs/libstdc++.so.6: version
-    `GLIBCXX_3.4.15' not found (required by ./hack/libdfhack.so)
-
-

To fix this, simply remove the libstdc++ shipped with DF, it will fall back -to your system lib and everything will work fine:

-
-cd /path/to/DF/
-rm libs/libstdc++.so.6
-
-
-
-
-

Mac OS X

-

If you are building on 10.6, please read the subsection below titled "Snow Leopard Changes" FIRST.

-
    -
  1. Download and unpack a copy of the latest DF

    -
  2. -
  3. Install Xcode from Mac App Store

    -
  4. -
  5. Open Xcode, go to Preferences > Downloads, and install the Command Line Tools.

    -
  6. -
  7. Install dependencies

    -
    -

    Option 1: Using MacPorts:

    -
    -
      -
    • Install MacPorts
    • -
    • Run sudo port install gcc45 +universal cmake +universal git-core +universal -This will take some time—maybe hours, depending on your machine.
    • -
    -

    At some point during this process, it may ask you to install a Java environment; let it do so.

    -
    -

    Option 2: Using Homebrew:

    -
    -
      -
    • Install Homebrew and run:
    • -
    • brew tap homebrew/versions
    • -
    • brew install git
    • -
    • brew install cmake
    • -
    • brew install gcc45 --enable-multilib
    • -
    -
    -
    -
  8. -
  9. Install perl dependencies

    -
    -
      -
    1. sudo cpan

      -

      If this is the first time you've run cpan, you will need to go through the setup -process. Just stick with the defaults for everything and you'll be fine.

      -
    2. -
    3. install XML::LibXML

      -
    4. -
    5. install XML::LibXSLT

      -
    6. -
    -
    -
  10. -
  11. Get the dfhack source:

    -
    -git clone git://github.com/DFHack/dfhack.git
    -cd dfhack
    -git submodule init
    -git submodule update
    -
    -
  12. -
  13. Set environment variables:

    -
  14. -
-
-

Macports:

-
-export CC=/opt/local/bin/gcc-mp-4.5
-export CXX=/opt/local/bin/g++-mp-4.5
-
-

Homebrew:

-
-export CC=/usr/local/bin/gcc-4.5
-export CXX=/usr/local/bin/g++-4.5
-
-
-
    -
  1. Build dfhack:

    -
    -mkdir build-osx
    -cd build-osx
    -cmake .. -DCMAKE_BUILD_TYPE:string=Release -DCMAKE_INSTALL_PREFIX=/path/to/DF/directory
    -make
    -make install
    -
    -
  2. -
-
-

Snow Leopard Changes

-
    -
  1. -
    Add a step 6.2a (before Install XML::LibXSLT)::
    -

    In a separate Terminal window or tab, run: -sudo ln -s /usr/include/libxml2/libxml /usr/include/libxml

    -
    -
    -
  2. -
  3. -
    Add a step 7a (before building)::
    -
    -
    In <dfhack directory>/library/LuaTypes.cpp, change line 467 to
    -

    int len = strlen((char*)ptr);

    -
    -
    -
    -
    -
  4. -
-
-
-

Yosemite Changes

-

If you have issues building on OS X Yosemite (or above), try definining the following environment variable:

-
-export MACOSX_DEPLOYMENT_TARGET=10.9
-
-
-
-

Windows

-

On Windows, DFHack replaces the SDL library distributed with DF.

-
-

How to get the code

-

DFHack doesn't have any kind of system of code snapshots in place, so you will have to get code from the github repository using git. -You will need some sort of Windows port of git, or a GUI. Some examples:

-
- -
-

The code resides here: https://github.com/DFHack/dfhack

-

If you just want to compile DFHack or work on it by contributing patches, it's quite enough to clone from the read-only address:

-
-git clone git://github.com/DFHack/dfhack.git
-cd dfhack
-git submodule init
-git submodule update
-
-

The tortoisegit GUI should have the equivalent options included.

-

If you want to get really involved with the development, create an account on github, make a clone there and then use that as your remote repository instead. Detailed instructions are beyond the scope of this document. If you need help, join us on IRC (#dfhack channel on freenode).

-
-
-

Dependencies

-

First, you need cmake. Get the win32 installer version from the official -site: http://www.cmake.org/cmake/resources/software.html

-

It has the usual installer wizard. Make sure you let it add its binary folder -to your binary search PATH so the tool can be later run from anywhere.

-

You'll need a copy of Microsoft Visual C++ 2010. The Express version is sufficient. -Grab it from Microsoft's site.

-

You'll also need the Visual Studio 2010 SP1 update.

-

For the code generation parts, you'll need perl with XML::LibXML and XML::LibXSLT. Strawberry Perl works nicely for this: http://strawberryperl.com/

-

If you already have a different version of perl (for example the one from cygwin), you can run into some trouble. Either remove the other perl install from PATH, or install libxml and libxslt for it instead. Strawberry perl works though and has all the required packages.

-
-
-

Build

-

There are several different batch files in the build folder along with a script that's used for picking the DF path.

-

First, run set_df_path.vbs and point the dialog that pops up at your DF folder that you want to use for development. -Next, run one of the scripts with generate prefix. These create the MSVC solution file(s):

-
    -
  • all will create a solution with everything enabled (and the kitchen sink).
  • -
  • gui will pop up the cmake gui and let you pick and choose what to build. This is probably what you want most of the time. Set the options you are interested in, then hit configure, then generate. More options can appear after the configure step.
  • -
  • minimal will create a minimal solution with just the bare necessities - the main library and standard plugins.
  • -
-

Then you can either open the solution with MSVC or use one of the msbuild scripts:

-
    -
  • Scripts with build prefix will only build.
  • -
  • Scripts with install prefix will build DFHack and install it to the previously selected DF path.
  • -
  • Scripts with package prefix will build and create a .zip package of DFHack.
  • -
-

When you open the solution in MSVC, make sure you never use the Debug builds. Those aren't -binary-compatible with DF. If you try to use a debug build with DF, you'll only get crashes. -So pick either Release or RelWithDebInfo build and build the INSTALL target.

-

The debug scripts actually do RelWithDebInfo builds.

-
-
-
-

Build types

-

cmake allows you to pick a build type by changing this -variable: CMAKE_BUILD_TYPE

-
-cmake .. -DCMAKE_BUILD_TYPE:string=BUILD_TYPE
-
-

Without specifying a build type or 'None', cmake uses the -CMAKE_CXX_FLAGS variable for building.

-

Valid and useful build types include 'Release', 'Debug' and -'RelWithDebInfo'. 'Debug' is not available on Windows.

-
-
-

Using the library as a developer

-

Currently, the most direct way to use the library is to write a plugin that can be loaded by it. -All the plugins can be found in the 'plugins' folder. There's no in-depth documentation -on how to write one yet, but it should be easy enough to copy one and just follow the pattern.

-

Other than through plugins, it is possible to use DFHack via remote access interface, or by writing Lua scripts.

-

The most important parts of DFHack are the Core, Console, Modules and Plugins.

- -

Rudimentary API documentation can be built using doxygen (see build options with ccmake or cmake-gui).

-

DFHack consists of variously licensed code, but invariably weak copyleft. -The main license is zlib/libpng, some bits are MIT licensed, and some are BSD licensed.

-

Feel free to add your own extensions and plugins. Contributing back to -the dfhack repository is welcome and the right thing to do :)

-
-

DF data structure definitions

-

DFHack uses information about the game data structures, represented via xml files in the library/xml/ submodule.

-

Data structure layouts are described in files following the df.*.xml name pattern. This information is transformed by a perl script into C++ headers describing the structures, and associated metadata for the Lua wrapper. These headers and data are then compiled into the DFHack libraries, thus necessitating a compatibility break every time layouts change; in return it significantly boosts the efficiency and capabilities of DFHack code.

-

Global object addresses are stored in symbols.xml, which is copied to the dfhack release package and loaded as data at runtime.

-
-
-

Remote access interface

-

DFHack supports remote access by exchanging Google protobuf messages via a TCP socket. Both the core and plugins can define remotely accessible methods. The dfhack-run command uses this interface to invoke ordinary console commands.

-

Currently the supported set of requests is limited, because the developers don't know what exactly is most useful.

-

Protocol client implementations exist for Java and C#.

-
-
-
- - diff --git a/Contributing.html b/Contributing.html deleted file mode 100644 index 3aad05fd9..000000000 --- a/Contributing.html +++ /dev/null @@ -1,410 +0,0 @@ - - - - - - -Contributing to DFHACK - - - -
-

Contributing to DFHACK

- -
-

Contents

- -
-
-

Contributing to DFHack

-

Several things should be kept in mind when contributing to DFHack.

-
-

Code Format

-
    -
  • Four space indents for C++. Never use tabs for indentation in any language.
  • -
  • LF (Unix style) line terminators
  • -
  • Avoid trailing whitespace
  • -
  • UTF-8 encoding
  • -
  • For C++:
      -
    • Opening and closing braces on their own lines or opening brace at the end of the previous line
    • -
    • Braces placed at original indent level if on their own lines
    • -
    • #includes should be sorted. C++ libraries first, then dfhack modules, then df structures, then local includes. Within each category they should be sorted alphabetically. This policy is currently broken by most C++ files but try to follow it if you can.
    • -
    -
  • -
-
-
-

How to get new code into DFHack

-
    -
  • Submit pull requests to the develop branch, not the master branch. The master branch always points at the most recent release.
  • -
  • Use new branches for each feature/fix so that your changes can be merged independently.
  • -
  • If possible, compile on multiple platforms
  • -
  • Do update NEWS/Contributors.rst
  • -
  • Do NOT run fix-texts.sh or update .html files (except to locally test changes to .rst files)
  • -
  • Create a Github Pull Request once finished
  • -
  • Work done against issues that are tagged "bug report" gets priority
      -
    • Submit ideas and bug reports as issues on github. Posts in the forum thread are also acceptable but can get missed or forgotten more easily.
    • -
    -
  • -
-
-
-

Memory research

-

If you want to do memory research, you'll need some tools and some knowledge. -In general, you'll need a good memory viewer and optionally something -to look at machine code without getting crazy :)

-

Good windows tools include:

-
    -
  • Cheat Engine
  • -
  • IDA Pro 5.0 (freely available for non-commercial use)
  • -
-

Good linux tools:

-
    -
  • angavrilov's df-structures gui (visit us on IRC for details).
  • -
  • edb (Evan's Debugger)
  • -
  • IDA Pro 5.0 running under Wine
  • -
  • Some of the tools residing in the legacy dfhack branch.
  • -
-

Using publicly known information and analyzing the game's data is preferred.

-
-
-
- - diff --git a/Contributors.html b/Contributors.html deleted file mode 100644 index 970da8a8d..000000000 --- a/Contributors.html +++ /dev/null @@ -1,703 +0,0 @@ - - - - - - -Contributors - - - -
-

Contributors

- -

If you belong here and are missing, please add yourself and send me (peterix) a pull request :-)

-

The following is a list of people who have contributed to DFHack.

- ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameGithubEmail
Petr Mrázekpeterixpeterix@gmail.com
Alexander Gavrilovangavrilovangavrilov@gmail.com
doomchilddoomchildlee.crabtree@gmail.com
Quietustquietustquietust@gmail.com
jjjjygjohn-git@ofjj.net
Warmistwarmistwarmist@gmail.com
Robert Heinrichrh73robertheinrich73@googlemail.com
simon simon@banquise.net
Kelly Martinab9rfkelly.lynn.martin@gmail.com
mizipzormizipzormizipzor@gmail.com
Simon Jacksonsizeaksizeak@hotmail.com
belaljimhesterjimbelal@gmail.com
RusAnonRusAnonrusanon@dollchan.ru
Raoul XQraoulxqraoulxq@gmail.com
Matthew Cline zelgadis@sourceforge.net
Mike Stewartthewonderidiotthewonderidiot@gmail.com
Timothy Collettdanaristcollett+github@topazgryphon.org
RossM Ross@Gnome
Tom Prince tom.prince@ualberta.net
Jared Adams jaxad0127@gmail.com
expwnentexpwnent 
Erik YoungrenArtanisartanis.00@gmail.com
Espen Wiborg espen.wiborg@telio.no
Tim Walbergtwalbergtwalberg@comcast.net
Mikko JuolaNoedamikko.juola@kolumbus.fi
rampaging-poet yrudoingthis@hotmail.com
U-glouglou\simon simon@glouglou
Clayton Hughes clayton.hughes@gmail.com
zilpinzilpinziLpin@gmail.com
Will Rogerswjrogerswjrogers@gmail.com
NMLittlenmlittlenmlittle@gmail.com
root  
reverb  
ZhentarZhentarZhentar@gmail.com
Valentin OchsCat-Iona@0au.de
Priit Laesplaesplaes@plaes.org
kmartin  
Neil Little  
rout rout.mail+github@gmail.com
rofl0rrofl0rretnyg@gmx.net
harlanplayfordplayfordhharlanplayford@gmail.com
John Shadegsvsltogsvslto@gmail.com
sami  
potato  
feng1st nf_xp@hotmail.com
comestiblenickrartnickolas.g.russell@gmail.com
RumrusherrumrusherAnuleakage@yahoo.com
RininRininRininS@Gmail.com
Raoul van Putten  
John Beisleyhuingreatred@gmail.com
Feng nf_xp@hotmail.com
Donald Ruegseggerhashaashdruegsegger@gmail.com
Caldfircaldfircaldfir@hotmail.com
Antaliatamarakorrtamarakorr@gmail.com
Angus Mezickamezickamezick@gmail.com
JapaJapaMalajapa.mala.illo@gmail.com
PutnamPutnam3145 
Lethosorlethosor 
PeridexisErrantPeridexisErrantPeridexisErrant@gmail.com
Eswaldeswald 
RamblurrRamblurr 
MithrilTuxedoMithrilTuxedo 
AndreasPKAndreasPK 
Chris Dombroskicdombroski 
Ben LubarBenLubar 
miffedmapmiffedmap 
scamtankscamtank 
Mason11987Mason11987 
James Logsdonjlogsdon 
melkor217melkor217 
-

And these are the cool people who made Stonesense.

- ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameGithubEmail
Kris Parkerkaypy 
JapaJapaMalajapa.mala.illo@gmail.com
Jonas Ask jonask84@gmail.com
Petr Mrázekpeterixpeterix@gmail.com>
Caldfircaldfiraitken.tim@gmail.com
8Z8Zgit8z@ya.ru
Alexander Gavrilovangavrilovangavrilov@gmail.com
Timothy Collettdanaristcollett+github@topazgryphon.org
Lethosorlethosor 
Eswaldeswald 
PeridexisErrantPeridexisErrantPeridexisErrant@gmail.com
-
- - diff --git a/Lua API.html b/Lua API.html deleted file mode 100644 index 0060723b7..000000000 --- a/Lua API.html +++ /dev/null @@ -1,3498 +0,0 @@ - - - - - - -DFHack Lua API - - - -
-

DFHack Lua API

- -
-

Contents

- -
-

The current version of DFHack has extensive support for -the Lua scripting language, providing access to:

-
    -
  1. Raw data structures used by the game.
  2. -
  3. Many C++ functions for high-level access to these -structures, and interaction with dfhack itself.
  4. -
  5. Some functions exported by C++ plugins.
  6. -
-

Lua code can be used both for writing scripts, which -are treated by DFHack command line prompt almost as -native C++ commands, and invoked by plugins written in c++.

-

This document describes native API available to Lua in detail. -It does not describe all of the utility functions -implemented by Lua files located in hack/lua/...

-
-

DF data structure wrapper

-

Data structures of the game are defined in XML files located in library/xml -(and online at http://github.com/DFHack/df-structures), and automatically exported -to lua code as a tree of objects and functions under the df global, which -also broadly maps to the df namespace in the headers generated for C++.

-

WARNING: The wrapper provides almost raw access to the memory -of the game, so mistakes in manipulating objects are as likely to -crash the game as equivalent plain C++ code would be. E.g. NULL -pointer access is safely detected, but dangling pointers aren't.

-

Objects managed by the wrapper can be broadly classified into the following groups:

-
    -
  1. Typed object pointers (references).

    -

    References represent objects in DF memory with a known type.

    -

    In addition to fields and methods defined by the wrapped type, -every reference has some built-in properties and methods.

    -
  2. -
  3. Untyped pointers

    -

    Represented as lightuserdata.

    -

    In assignment to a pointer NULL can be represented either as -nil, or a NULL lightuserdata; reading a NULL pointer field -returns nil.

    -
  4. -
  5. Named types

    -

    Objects in the df tree that represent identity of struct, class, -enum and bitfield types. They host nested named types, static -methods, builtin properties & methods, and, for enums and bitfields, -the bi-directional mapping between key names and values.

    -
  6. -
  7. The global object

    -

    df.global corresponds to the df::global namespace, and -behaves as a mix between a named type and a reference, containing -both nested types and fields corresponding to global symbols.

    -
  8. -
-

In addition to the global object and top-level types the df -global also contains a few global builtin utility functions.

-
-

Typed object references

-

The underlying primitive lua object is userdata with a metatable. -Every structured field access produces a new userdata instance.

-

All typed objects have the following built-in features:

-
    -
  • ref1 == ref2, tostring(ref)

    -

    References implement equality by type & pointer value, and string conversion.

    -
  • -
  • pairs(ref)

    -

    Returns an iterator for the sequence of actual C++ field names -and values. Fields are enumerated in memory order. Methods and -lua wrapper properties are not included in the iteration.

    -

    WARNING: a few of the data structures (like ui_look_list) -contain unions with pointers to different types with vtables. -Using pairs on such structs is an almost sure way to crash with -an access violation.

    -
  • -
  • ref._kind

    -

    Returns one of: primitive, struct, container, -or bitfield, as appropriate for the referenced object.

    -
  • -
  • ref._type

    -

    Returns the named type object or a string that represents -the referenced object type.

    -
  • -
  • ref:sizeof()

    -

    Returns size, address

    -
  • -
  • ref:new()

    -

    Allocates a new instance of the same type, and copies data -from the current object.

    -
  • -
  • ref:delete()

    -

    Destroys the object with the C++ delete operator. -If destructor is not available, returns false.

    -

    WARNING: the lua reference object remains as a dangling -pointer, like a raw C++ pointer would.

    -
  • -
  • ref:assign(object)

    -

    Assigns data from object to ref. Object must either be another -ref of a compatible type, or a lua table; in the latter case -special recursive assignment rules are applied.

    -
  • -
  • ref:_displace(index[,step])

    -

    Returns a new reference with the pointer adjusted by index*step. -Step defaults to the natural object size.

    -
  • -
-
-

Primitive references

-

References of the _kind 'primitive' are used for objects -that don't fit any of the other reference types. Such -references can only appear as a value of a pointer field, -or as a result of calling the _field() method.

-

They behave as structs with one field value of the right type.

-

To make working with numeric buffers easier, they also allow -numeric indices. Note that other than excluding negative values -no bound checking is performed, since buffer length is not available. -Index 0 is equivalent to the value field.

-
-
-

Struct references

-

Struct references are used for class and struct objects.

-

They implement the following features:

-
    -
  • ref.field, ref.field = value

    -

    Valid fields of the structure may be accessed by subscript.

    -

    Primitive typed fields, i.e. numbers & strings, are converted -to/from matching lua values. The value of a pointer is a reference -to the target, or nil/NULL. Complex types are represented by -a reference to the field within the structure; unless recursive -lua table assignment is used, such fields can only be read.

    -

    NOTE: In case of inheritance, superclass fields have precedence -over the subclass, but fields shadowed in this way can still -be accessed as ref['subclasstype.field']. -This shadowing order is necessary because vtable-based classes -are automatically exposed in their exact type, and the reverse -rule would make access to superclass fields unreliable.

    -
  • -
  • ref._field(field)

    -

    Returns a reference to a valid field. That is, unlike regular -subscript, it returns a reference to the field within the structure -even for primitive typed fields and pointers.

    -
  • -
  • ref:vmethod(args...)

    -

    Named virtual methods are also exposed, subject to the same -shadowing rules.

    -
  • -
  • pairs(ref)

    -

    Enumerates all real fields (but not methods) in memory -(= declaration) order.

    -
  • -
-
-
-

Container references

-

Containers represent vectors and arrays, possibly resizable.

-

A container field can associate an enum to the container -reference, which allows accessing elements using string keys -instead of numerical indices.

-

Implemented features:

-
    -
  • ref._enum

    -

    If the container has an associated enum, returns the matching -named type object.

    -
  • -
  • #ref

    -

    Returns the length of the container.

    -
  • -
  • ref[index]

    -

    Accesses the container element, using either a 0-based numerical -index, or, if an enum is associated, a valid enum key string.

    -

    Accessing an invalid index is an error, but some container types -may return a default value, or auto-resize instead for convenience. -Currently this relaxed mode is implemented by df-flagarray aka BitArray.

    -
  • -
  • ref._field(index)

    -

    Like with structs, returns a pointer to the array element, if possible. -Flag and bit arrays cannot return such pointer, so it fails with an error.

    -
  • -
  • pairs(ref), ipairs(ref)

    -

    If the container has no associated enum, both behave identically, -iterating over numerical indices in order. Otherwise, ipairs still -uses numbers, while pairs tries to substitute enum keys whenever -possible.

    -
  • -
  • ref:resize(new_size)

    -

    Resizes the container if supported, or fails with an error.

    -
  • -
  • ref:insert(index,item)

    -

    Inserts a new item at the specified index. To add at the end, -use #ref, or just '#' as index.

    -
  • -
  • ref:erase(index)

    -

    Removes the element at the given valid index.

    -
  • -
-
-
-

Bitfield references

-

Bitfields behave like special fixed-size containers. -Consider them to be something in between structs and -fixed-size vectors.

-

The _enum property points to the bitfield type. -Numerical indices correspond to the shift value, -and if a subfield occupies multiple bits, the -ipairs order would have a gap.

-

Since currently there is no API to allocate a bitfield -object fully in GC-managed lua heap, consider using the -lua table assignment feature outlined below in order to -pass bitfield values to dfhack API functions that need -them, e.g. matinfo:matches{metal=true}.

-
-
-
-

Named types

-

Named types are exposed in the df tree with names identical -to the C++ version, except for the :: vs . difference.

-

All types and the global object have the following features:

-
    -
  • type._kind

    -

    Evaluates to one of struct-type, class-type, enum-type, -bitfield-type or global.

    -
  • -
  • type._identity

    -

    Contains a lightuserdata pointing to the underlying -DFHack::type_instance object.

    -
  • -
-

Types excluding the global object also support:

-
    -
  • type:sizeof()

    -

    Returns the size of an object of the type.

    -
  • -
  • type:new()

    -

    Creates a new instance of an object of the type.

    -
  • -
  • type:is_instance(object)

    -

    Returns true if object is same or subclass type, or a reference -to an object of same or subclass type. It is permissible to pass -nil, NULL or non-wrapper value as object; in this case the -method returns nil.

    -
  • -
-

In addition to this, enum and bitfield types contain a -bi-directional mapping between key strings and values, and -also map _first_item and _last_item to the min and -max values.

-

Struct and class types with instance-vector attribute in the -xml have a type.find(key) function that wraps the find -method provided in C++.

-
-
-

Global functions

-

The df table itself contains the following functions and values:

-
    -
  • NULL, df.NULL

    -

    Contains the NULL lightuserdata.

    -
  • -
  • df.isnull(obj)

    -

    Evaluates to true if obj is nil or NULL; false otherwise.

    -
  • -
  • df.isvalid(obj[,allow_null])

    -

    For supported objects returns one of type, voidptr, ref.

    -

    If allow_null is true, and obj is nil or NULL, returns null.

    -

    Otherwise returns nil.

    -
  • -
  • df.sizeof(obj)

    -

    For types and refs identical to obj:sizeof(). -For lightuserdata returns nil, address

    -
  • -
  • df.new(obj), df.delete(obj), df.assign(obj, obj2)

    -

    Equivalent to using the matching methods of obj.

    -
  • -
  • df._displace(obj,index[,step])

    -

    For refs equivalent to the method, but also works with -lightuserdata (step is mandatory then).

    -
  • -
  • df.is_instance(type,obj)

    -

    Equivalent to the method, but also allows a reference as proxy for its type.

    -
  • -
  • df.new(ptype[,count])

    -

    Allocate a new instance, or an array of built-in types. -The ptype argument is a string from the following list: -string, int8_t, uint8_t, int16_t, uint16_t, -int32_t, uint32_t, int64_t, uint64_t, bool, -float, double. All of these except string can be -used with the count argument to allocate an array.

    -
  • -
  • df.reinterpret_cast(type,ptr)

    -

    Converts ptr to a ref of specified type. The type may be anything -acceptable to df.is_instance. Ptr may be nil, a ref, -a lightuserdata, or a number.

    -

    Returns nil if NULL, or a ref.

    -
  • -
-
-
-

Recursive table assignment

-

Recursive assignment is invoked when a lua table is assigned -to a C++ object or field, i.e. one of:

-
    -
  • ref:assign{...}
  • -
  • ref.field = {...}
  • -
-

The general mode of operation is that all fields of the table -are assigned to the fields of the target structure, roughly -emulating the following code:

-
-function rec_assign(ref,table)
-    for key,value in pairs(table) do
-        ref[key] = value
-    end
-end
-
-

Since assigning a table to a field using = invokes the same -process, it is recursive.

-

There are however some variations to this process depending -on the type of the field being assigned to:

-
    -
  1. If the table contains an assign field, it is -applied first, using the ref:assign(value) method. -It is never assigned as a usual field.

    -
  2. -
  3. When a table is assigned to a non-NULL pointer field -using the ref.field = {...} syntax, it is applied -to the target of the pointer instead.

    -

    If the pointer is NULL, the table is checked for a new field:

    -
      -
    1. If it is nil or false, assignment fails with an error.
    2. -
    3. If it is true, the pointer is initialized with a newly -allocated object of the declared target type of the pointer.
    4. -
    5. Otherwise, table.new must be a named type, or an -object of a type compatible with the pointer. The pointer -is initialized with the result of calling table.new:new().
    6. -
    -

    After this auto-vivification process, assignment proceeds -as if the pointer wasn't NULL.

    -

    Obviously, the new field inside the table is always skipped -during the actual per-field assignment processing.

    -
  4. -
  5. If the target of the assignment is a container, a separate -rule set is used:

    -
      -
    1. If the table contains neither assign nor resize -fields, it is interpreted as an ordinary 1-based lua -array. The container is resized to the #-size of the -table, and elements are assigned in numeric order:

      -
      -ref:resize(#table);
      -for i=1,#table do ref[i-1] = table[i] end
      -
      -
    2. -
    3. Otherwise, resize must be true, false, or -an explicit number. If it is not false, the container -is resized. After that the usual struct-like 'pairs' -assignment is performed.

      -

      In case resize is true, the size is computed -by scanning the table for the largest numeric key.

      -
    4. -
    -

    This means that in order to reassign only one element of -a container using this system, it is necessary to use:

    -
    -{ resize=false, [idx]=value }
    -
    -
  6. -
-

Since nil inside a table is indistinguishable from missing key, -it is necessary to use df.NULL as a null pointer value.

-

This system is intended as a way to define a nested object -tree using pure lua data structures, and then materialize it in -C++ memory in one go. Note that if pointer auto-vivification -is used, an error in the middle of the recursive walk would -not destroy any objects allocated in this way, so the user -should be prepared to catch the error and do the necessary -cleanup.

-
-
-
-

DFHack API

-

DFHack utility functions are placed in the dfhack global tree.

-
-

Native utilities

-
-

Input & Output

-
    -
  • dfhack.print(args...)

    -

    Output tab-separated args as standard lua print would do, -but without a newline.

    -
  • -
  • print(args...), dfhack.println(args...)

    -

    A replacement of the standard library print function that -works with DFHack output infrastructure.

    -
  • -
  • dfhack.printerr(args...)

    -

    Same as println; intended for errors. Uses red color and logs to stderr.log.

    -
  • -
  • dfhack.color([color])

    -

    Sets the current output color. If color is nil or -1, resets to default. -Returns the previous color value.

    -
  • -
  • dfhack.is_interactive()

    -

    Checks if the thread can access the interactive console and returns true or false.

    -
  • -
  • dfhack.lineedit([prompt[,history_filename]])

    -

    If the thread owns the interactive console, shows a prompt -and returns the entered string. Otherwise returns nil, error.

    -

    Depending on the context, this function may actually yield the -running coroutine and let the C++ code release the core suspend -lock. Using an explicit dfhack.with_suspend will prevent -this, forcing the function to block on input with lock held.

    -
  • -
  • dfhack.interpreter([prompt[,history_filename[,env]]])

    -

    Starts an interactive lua interpreter, using the specified prompt -string, global environment and command-line history file.

    -

    If the interactive console is not accessible, returns nil, error.

    -
  • -
-
-
-

Exception handling

-
    -
  • dfhack.error(msg[,level[,verbose]])

    -

    Throws a dfhack exception object with location and stack trace. -The verbose parameter controls whether the trace is printed by default.

    -
  • -
  • qerror(msg[,level])

    -

    Calls dfhack.error() with verbose being false. Intended to -be used for user-caused errors in scripts, where stack traces are not -desirable.

    -
  • -
  • dfhack.pcall(f[,args...])

    -

    Invokes f via xpcall, using an error function that attaches -a stack trace to the error. The same function is used by SafeCall -in C++, and dfhack.safecall.

    -
  • -
  • safecall(f[,args...]), dfhack.safecall(f[,args...])

    -

    Just like pcall, but also prints the error using printerr before -returning. Intended as a convenience function.

    -
  • -
  • dfhack.saferesume(coroutine[,args...])

    -

    Compares to coroutine.resume like dfhack.safecall vs pcall.

    -
  • -
  • dfhack.exception

    -

    Metatable of error objects used by dfhack. The objects have the -following properties:

    -
    -
    err.where
    -

    The location prefix string, or nil.

    -
    -
    err.message
    -

    The base message string.

    -
    -
    err.stacktrace
    -

    The stack trace string, or nil.

    -
    -
    err.cause
    -

    A different exception object, or nil.

    -
    -
    err.thread
    -

    The coroutine that has thrown the exception.

    -
    -
    err.verbose
    -

    Boolean, or nil; specifies if where and stacktrace should be printed.

    -
    -
    tostring(err), or err:tostring([verbose])
    -

    Converts the exception to string.

    -
    -
    -
  • -
  • dfhack.exception.verbose

    -

    The default value of the verbose argument of err:tostring().

    -
  • -
-
-
-

Miscellaneous

-
    -
  • dfhack.VERSION

    -

    DFHack version string constant.

    -
  • -
  • dfhack.curry(func,args...), or curry(func,args...)

    -

    Returns a closure that invokes the function with args combined -both from the curry call and the closure call itself. I.e. -curry(func,a,b)(c,d) equals func(a,b,c,d).

    -
  • -
-
-
-

Locking and finalization

-
    -
  • dfhack.with_suspend(f[,args...])

    -

    Calls f with arguments after grabbing the DF core suspend lock. -Suspending is necessary for accessing a consistent state of DF memory.

    -

    Returned values and errors are propagated through after releasing -the lock. It is safe to nest suspends.

    -

    Every thread is allowed only one suspend per DF frame, so it is best -to group operations together in one big critical section. A plugin -can choose to run all lua code inside a C++-side suspend lock.

    -
  • -
  • dfhack.call_with_finalizer(num_cleanup_args,always,cleanup_fn[,cleanup_args...],fn[,args...])

    -

    Invokes fn with args, and after it returns or throws an -error calls cleanup_fn with cleanup_args. Any return values from -fn are propagated, and errors are re-thrown.

    -

    The num_cleanup_args integer specifies the number of cleanup_args, -and the always boolean specifies if cleanup should be called in any case, -or only in case of an error.

    -
  • -
  • dfhack.with_finalize(cleanup_fn,fn[,args...])

    -

    Calls fn with arguments, then finalizes with cleanup_fn. -Implemented using call_with_finalizer(0,true,...).

    -
  • -
  • dfhack.with_onerror(cleanup_fn,fn[,args...])

    -

    Calls fn with arguments, then finalizes with cleanup_fn on any thrown error. -Implemented using call_with_finalizer(0,false,...).

    -
  • -
  • dfhack.with_temp_object(obj,fn[,args...])

    -

    Calls fn(obj,args...), then finalizes with obj:delete().

    -
  • -
-
-
-

Persistent configuration storage

-

This api is intended for storing configuration options in the world itself. -It probably should be restricted to data that is world-dependent.

-

Entries are identified by a string key, but it is also possible to manage -multiple entries with the same key; their identity is determined by entry_id. -Every entry has a mutable string value, and an array of 7 mutable ints.

-
    -
  • dfhack.persistent.get(key), entry:get()

    -

    Retrieves a persistent config record with the given string key, -or refreshes an already retrieved entry. If there are multiple -entries with the same key, it is undefined which one is retrieved -by the first version of the call.

    -

    Returns entry, or nil if not found.

    -
  • -
  • dfhack.persistent.delete(key), entry:delete()

    -

    Removes an existing entry. Returns true if succeeded.

    -
  • -
  • dfhack.persistent.get_all(key[,match_prefix])

    -

    Retrieves all entries with the same key, or starting with key..'/'. -Calling get_all('',true) will match all entries.

    -

    If none found, returns nil; otherwise returns an array of entries.

    -
  • -
  • dfhack.persistent.save({key=str1, ...}[,new]), entry:save([new])

    -

    Saves changes in an entry, or creates a new one. Passing true as -new forces creation of a new entry even if one already exists; -otherwise the existing one is simply updated. -Returns entry, did_create_new

    -
  • -
-

Since the data is hidden in data structures owned by the DF world, -and automatically stored in the save game, these save and retrieval -functions can just copy values in memory without doing any actual I/O. -However, currently every entry has a 180+-byte dead-weight overhead.

-

It is also possible to associate one bit per map tile with an entry, -using these two methods:

-
    -
  • entry:getTilemask(block[, create])

    -

    Retrieves the tile bitmask associated with this entry in the given map -block. If create is true, an empty mask is created if none exists; -otherwise the function returns nil, which must be assumed to be the same -as an all-zero mask.

    -
  • -
  • entry:deleteTilemask(block)

    -

    Deletes the associated tile mask from the given map block.

    -
  • -
-

Note that these masks are only saved in fortress mode, and also that deleting -the persistent entry will NOT delete the associated masks.

-
-
-

Material info lookup

-

A material info record has fields:

-
    -
  • type, index, material

    -

    DF material code pair, and a reference to the material object.

    -
  • -
  • mode

    -

    One of 'builtin', 'inorganic', 'plant', 'creature'.

    -
  • -
  • inorganic, plant, creature

    -

    If the material is of the matching type, contains a reference to the raw object.

    -
  • -
  • figure

    -

    For a specific creature material contains a ref to the historical figure.

    -
  • -
-

Functions:

-
    -
  • dfhack.matinfo.decode(type,index)

    -

    Looks up material info for the given number pair; if not found, returs nil.

    -
  • -
  • ....decode(matinfo), ....decode(item), ....decode(obj)

    -

    Uses matinfo.type/matinfo.index, item getter vmethods, -or obj.mat_type/obj.mat_index to get the code pair.

    -
  • -
  • dfhack.matinfo.find(token[,token...])

    -

    Looks up material by a token string, or a pre-split string token sequence.

    -
  • -
  • dfhack.matinfo.getToken(...), info:getToken()

    -

    Applies decode and constructs a string token.

    -
  • -
  • info:toString([temperature[,named]])

    -

    Returns the human-readable name at the given temperature.

    -
  • -
  • info:getCraftClass()

    -

    Returns the classification used for craft skills.

    -
  • -
  • info:matches(obj)

    -

    Checks if the material matches job_material_category or job_item. -Accept dfhack_material_category auto-assign table.

    -
  • -
-
-
-

Random number generation

-
    -
  • dfhack.random.new([seed[,perturb_count]])

    -

    Creates a new random number generator object. Without any -arguments, the object is initialized using current time. -Otherwise, the seed must be either a non-negative integer, -or a list of such integers. The second argument may specify -the number of additional randomization steps performed to -improve the initial state.

    -
  • -
  • rng:init([seed[,perturb_count]])

    -

    Re-initializes an already existing random number generator object.

    -
  • -
  • rng:random([limit])

    -

    Returns a random integer. If limit is specified, the value -is in the range [0, limit); otherwise it uses the whole 32-bit -unsigned integer range.

    -
  • -
  • rng:drandom()

    -

    Returns a random floating-point number in the range [0,1).

    -
  • -
  • rng:drandom0()

    -

    Returns a random floating-point number in the range (0,1).

    -
  • -
  • rng:drandom1()

    -

    Returns a random floating-point number in the range [0,1].

    -
  • -
  • rng:unitrandom()

    -

    Returns a random floating-point number in the range [-1,1].

    -
  • -
  • rng:unitvector([size])

    -

    Returns multiple values that form a random vector of length 1, -uniformly distributed over the corresponding sphere surface. -The default size is 3.

    -
  • -
  • fn = rng:perlin([dim]); fn(x[,y[,z]])

    -

    Returns a closure that computes a classical Perlin noise function -of dimension dim, initialized from this random generator. -Dimension may be 1, 2 or 3 (default).

    -
  • -
-
-
-
-

C++ function wrappers

-

Thin wrappers around C++ functions, similar to the ones for virtual methods. -One notable difference is that these explicit wrappers allow argument count -adjustment according to the usual lua rules, so trailing false/nil arguments -can be omitted.

-
    -
  • dfhack.getOSType()

    -

    Returns the OS type string from symbols.xml.

    -
  • -
  • dfhack.getDFVersion()

    -

    Returns the DF version string from symbols.xml.

    -
  • -
  • dfhack.getDFPath()

    -

    Returns the DF directory path.

    -
  • -
  • dfhack.getHackPath()

    -

    Returns the dfhack directory path, i.e. ".../df/hack/".

    -
  • -
  • dfhack.getSavePath()

    -

    Returns the path to the current save directory, or nil if no save loaded.

    -
  • -
  • dfhack.getTickCount()

    -

    Returns the tick count in ms, exactly as DF ui uses.

    -
  • -
  • dfhack.isWorldLoaded()

    -

    Checks if the world is loaded.

    -
  • -
  • dfhack.isMapLoaded()

    -

    Checks if the world and map are loaded.

    -
  • -
  • dfhack.TranslateName(name[,in_english,only_last_name])

    -

    Convert a language_name or only the last name part to string.

    -
  • -
  • dfhack.df2utf(string)

    -

    Convert a string from DF's CP437 encoding to UTF-8.

    -
  • -
  • dfhack.utf2df(string)

    -

    Convert a string from UTF-8 to DF's CP437 encoding.

    -
  • -
-
-

Gui module

-
    -
  • dfhack.gui.getCurViewscreen([skip_dismissed])

    -

    Returns the topmost viewscreen. If skip_dismissed is true, -ignores screens already marked to be removed.

    -
  • -
  • dfhack.gui.getFocusString(viewscreen)

    -

    Returns a string representation of the current focus position -in the ui. The string has a "screen/foo/bar/baz..." format.

    -
  • -
  • dfhack.gui.getCurFocus([skip_dismissed])

    -

    Returns the focus string of the current viewscreen.

    -
  • -
  • dfhack.gui.getSelectedWorkshopJob([silent])

    -

    When a job is selected in 'q' mode, returns the job, else -prints error unless silent and returns nil.

    -
  • -
  • dfhack.gui.getSelectedJob([silent])

    -

    Returns the job selected in a workshop or unit/jobs screen.

    -
  • -
  • dfhack.gui.getSelectedUnit([silent])

    -

    Returns the unit selected via 'v', 'k', unit/jobs, or -a full-screen item view of a cage or suchlike.

    -
  • -
  • dfhack.gui.getSelectedItem([silent])

    -

    Returns the item selected via 'v' ->inventory, 'k', 't', or -a full-screen item view of a container. Note that in the -last case, the highlighted contained item is returned, not -the container itself.

    -
  • -
  • dfhack.gui.getSelectedBuilding([silent])

    -

    Returns the building selected via 'q', 't', 'k' or 'i'.

    -
  • -
  • dfhack.gui.writeToGamelog(text)

    -

    Writes a string to gamelog.txt without doing an announcement.

    -
  • -
  • dfhack.gui.makeAnnouncement(type,flags,pos,text,color[,is_bright])

    -

    Adds an announcement with given announcement_type, text, color, and brightness. -The is_bright boolean actually seems to invert the brightness.

    -

    The announcement is written to gamelog.txt. The announcement_flags -argument provides a custom set of announcements.txt options, -which specify if the message should actually be displayed in the -announcement list, and whether to recenter or show a popup.

    -

    Returns the index of the new announcement in df.global.world.status.reports, or -1.

    -
  • -
  • dfhack.gui.addCombatReport(unit,slot,report_index)

    -

    Adds the report with the given index (returned by makeAnnouncement) -to the specified group of the given unit. Returns true on success.

    -
  • -
  • dfhack.gui.addCombatReportAuto(unit,flags,report_index)

    -

    Adds the report with the given index to the appropriate group(s) -of the given unit, as requested by the flags.

    -
  • -
  • dfhack.gui.showAnnouncement(text,color[,is_bright])

    -

    Adds a regular announcement with given text, color, and brightness. -The is_bright boolean actually seems to invert the brightness.

    -
  • -
  • dfhack.gui.showZoomAnnouncement(type,pos,text,color[,is_bright])

    -

    Like above, but also specifies a position you can zoom to from the announcement menu.

    -
  • -
  • dfhack.gui.showPopupAnnouncement(text,color[,is_bright])

    -

    Pops up a titan-style modal announcement window.

    -
  • -
  • dfhack.gui.showAutoAnnouncement(type,pos,text,color[,is_bright,unit1,unit2])

    -

    Uses the type to look up options from announcements.txt, and calls the above -operations accordingly. The units are used to call addCombatReportAuto.

    -
  • -
-
-
-

Job module

-
    -
  • dfhack.job.cloneJobStruct(job)

    -

    Creates a deep copy of the given job.

    -
  • -
  • dfhack.job.printJobDetails(job)

    -

    Prints info about the job.

    -
  • -
  • dfhack.job.printItemDetails(jobitem,idx)

    -

    Prints info about the job item.

    -
  • -
  • dfhack.job.getGeneralRef(job, type)

    -

    Searches for a general_ref with the given type.

    -
  • -
  • dfhack.job.getSpecificRef(job, type)

    -

    Searches for a specific_ref with the given type.

    -
  • -
  • dfhack.job.getHolder(job)

    -

    Returns the building holding the job.

    -
  • -
  • dfhack.job.getWorker(job)

    -

    Returns the unit performing the job.

    -
  • -
  • dfhack.job.setJobCooldown(building,worker,timeout)

    -

    Prevent the worker from taking jobs at the specified workshop for the specified time. -This doesn't decrease the timeout in any circumstances.

    -
  • -
  • dfhack.job.removeWorker(job,timeout)

    -

    Removes the worker from the specified workshop job, and sets the cooldown. -Returns true on success.

    -
  • -
  • dfhack.job.checkBuildingsNow()

    -

    Instructs the game to check buildings for jobs next frame and assign workers.

    -
  • -
  • dfhack.job.checkDesignationsNow()

    -

    Instructs the game to check designations for jobs next frame and assign workers.

    -
  • -
  • dfhack.job.is_equal(job1,job2)

    -

    Compares important fields in the job and nested item structures.

    -
  • -
  • dfhack.job.is_item_equal(job_item1,job_item2)

    -

    Compares important fields in the job item structures.

    -
  • -
  • dfhack.job.linkIntoWorld(job,new_id)

    -

    Adds job into df.global.job_list, and if new_id -is true, then also sets it's id and increases -df.global.job_next_id

    -
  • -
  • dfhack.job.listNewlyCreated(first_id)

    -

    Returns the current value of df.global.job_next_id, and -if there are any jobs with first_id <= id < job_next_id, -a lua list containing them.

    -
  • -
  • dfhack.job.isSuitableItem(job_item, item_type, item_subtype)

    -

    Does basic sanity checks to verify if the suggested item type matches -the flags in the job item.

    -
  • -
  • dfhack.job.isSuitableMaterial(job_item, mat_type, mat_index)

    -

    Likewise, if replacing material.

    -
  • -
  • dfhack.job.getName(job)

    -

    Returns the job's description, as seen in the Units and Jobs screens.

    -
  • -
-
-
-

Units module

-
    -
  • dfhack.units.getPosition(unit)

    -

    Returns true x,y,z of the unit, or nil if invalid; may be not equal to unit.pos if caged.

    -
  • -
  • dfhack.units.getGeneralRef(unit, type)

    -

    Searches for a general_ref with the given type.

    -
  • -
  • dfhack.units.getSpecificRef(unit, type)

    -

    Searches for a specific_ref with the given type.

    -
  • -
  • dfhack.units.getContainer(unit)

    -

    Returns the container (cage) item or nil.

    -
  • -
  • dfhack.units.setNickname(unit,nick)

    -

    Sets the unit's nickname properly.

    -
  • -
  • dfhack.units.getVisibleName(unit)

    -

    Returns the language_name object visible in game, accounting for false identities.

    -
  • -
  • dfhack.units.getIdentity(unit)

    -

    Returns the false identity of the unit if it has one, or nil.

    -
  • -
  • dfhack.units.getNemesis(unit)

    -

    Returns the nemesis record of the unit if it has one, or nil.

    -
  • -
  • dfhack.units.isHidingCurse(unit)

    -

    Checks if the unit hides improved attributes from its curse.

    -
  • -
  • dfhack.units.getPhysicalAttrValue(unit, attr_type)

    -
  • -
  • dfhack.units.getMentalAttrValue(unit, attr_type)

    -

    Computes the effective attribute value, including curse effect.

    -
  • -
  • dfhack.units.isCrazed(unit)

    -
  • -
  • dfhack.units.isOpposedToLife(unit)

    -
  • -
  • dfhack.units.hasExtravision(unit)

    -
  • -
  • dfhack.units.isBloodsucker(unit)

    -

    Simple checks of caste attributes that can be modified by curses.

    -
  • -
  • dfhack.units.getMiscTrait(unit, type[, create])

    -

    Finds (or creates if requested) a misc trait object with the given id.

    -
  • -
  • dfhack.units.isDead(unit)

    -

    The unit is completely dead and passive, or a ghost.

    -
  • -
  • dfhack.units.isAlive(unit)

    -

    The unit isn't dead or undead.

    -
  • -
  • dfhack.units.isSane(unit)

    -

    The unit is capable of rational action, i.e. not dead, insane, zombie, or active werewolf.

    -
  • -
  • dfhack.units.isDwarf(unit)

    -

    The unit is of the correct race of the fortress.

    -
  • -
  • dfhack.units.isCitizen(unit)

    -

    The unit is an alive sane citizen of the fortress; wraps the -same checks the game uses to decide game-over by extinction.

    -
  • -
  • dfhack.units.getAge(unit[,true_age])

    -

    Returns the age of the unit in years as a floating-point value. -If true_age is true, ignores false identities.

    -
  • -
  • dfhack.units.getNominalSkill(unit, skill[, use_rust])

    -

    Retrieves the nominal skill level for the given unit. If use_rust -is true, subtracts the rust penalty.

    -
  • -
  • dfhack.units.getEffectiveSkill(unit, skill)

    -

    Computes the effective rating for the given skill, taking into account exhaustion, pain etc.

    -
  • -
  • dfhack.units.getExperience(unit, skill[, total])

    -

    Returns the experience value for the given skill. If total is true, adds experience implied by the current rating.

    -
  • -
  • dfhack.units.computeMovementSpeed(unit)

    -

    Computes number of frames * 100 it takes the unit to move in its current state of mind and body.

    -
  • -
  • dfhack.units.computeSlowdownFactor(unit)

    -

    Meandering and floundering in liquid introduces additional slowdown. It is -random, but the function computes and returns the expected mean factor as a float.

    -
  • -
  • dfhack.units.getNoblePositions(unit)

    -

    Returns a list of tables describing noble position assignments, or nil. -Every table has fields entity, assignment and position.

    -
  • -
  • dfhack.units.getProfessionName(unit[,ignore_noble,plural])

    -

    Retrieves the profession name using custom profession, noble assignments -or raws. The ignore_noble boolean disables the use of noble positions.

    -
  • -
  • dfhack.units.getCasteProfessionName(race,caste,prof_id[,plural])

    -

    Retrieves the profession name for the given race/caste using raws.

    -
  • -
  • dfhack.units.getProfessionColor(unit[,ignore_noble])

    -

    Retrieves the color associated with the profession, using noble assignments -or raws. The ignore_noble boolean disables the use of noble positions.

    -
  • -
  • dfhack.units.getCasteProfessionColor(race,caste,prof_id)

    -

    Retrieves the profession color for the given race/caste using raws.

    -
  • -
-
-
-

Items module

-
    -
  • dfhack.items.getPosition(item)

    -

    Returns true x,y,z of the item, or nil if invalid; may be not equal to item.pos if in inventory.

    -
  • -
  • dfhack.items.getDescription(item, type[, decorate])

    -

    Returns the string description of the item, as produced by the getItemDescription -method. If decorate is true, also adds markings for quality and improvements.

    -
  • -
  • dfhack.items.getGeneralRef(item, type)

    -

    Searches for a general_ref with the given type.

    -
  • -
  • dfhack.items.getSpecificRef(item, type)

    -

    Searches for a specific_ref with the given type.

    -
  • -
  • dfhack.items.getOwner(item)

    -

    Returns the owner unit or nil.

    -
  • -
  • dfhack.items.setOwner(item,unit)

    -

    Replaces the owner of the item. If unit is nil, removes ownership. -Returns false in case of error.

    -
  • -
  • dfhack.items.getContainer(item)

    -

    Returns the container item or nil.

    -
  • -
  • dfhack.items.getContainedItems(item)

    -

    Returns a list of items contained in this one.

    -
  • -
  • dfhack.items.getHolderBuilding(item)

    -

    Returns the holder building or nil.

    -
  • -
  • dfhack.items.getHolderUnit(item)

    -

    Returns the holder unit or nil.

    -
  • -
  • dfhack.items.moveToGround(item,pos)

    -

    Move the item to the ground at position. Returns false if impossible.

    -
  • -
  • dfhack.items.moveToContainer(item,container)

    -

    Move the item to the container. Returns false if impossible.

    -
  • -
  • dfhack.items.moveToBuilding(item,building,use_mode)

    -

    Move the item to the building. Returns false if impossible.

    -
  • -
  • dfhack.items.moveToInventory(item,unit,use_mode,body_part)

    -

    Move the item to the unit inventory. Returns false if impossible.

    -
  • -
  • dfhack.items.remove(item[, no_uncat])

    -

    Removes the item, and marks it for garbage collection unless no_uncat is true.

    -
  • -
  • dfhack.items.makeProjectile(item)

    -

    Turns the item into a projectile, and returns the new object, or nil if impossible.

    -
  • -
  • dfhack.items.isCasteMaterial(item_type)

    -

    Returns true if this item type uses a creature/caste pair as its material.

    -
  • -
  • dfhack.items.getSubtypeCount(item_type)

    -

    Returns the number of raw-defined subtypes of the given item type, or -1 if not applicable.

    -
  • -
  • dfhack.items.getSubtypeDef(item_type, subtype)

    -

    Returns the raw definition for the given item type and subtype, or nil if invalid.

    -
  • -
  • dfhack.items.getItemBaseValue(item_type, subtype, material, mat_index)

    -

    Calculates the base value for an item of the specified type and material.

    -
  • -
  • dfhack.items.getValue(item)

    -

    Calculates the Basic Value of an item, as seen in the View Item screen.

    -
  • -
-
-
-

Maps module

-
    -
  • dfhack.maps.getSize()

    -

    Returns map size in blocks: x, y, z

    -
  • -
  • dfhack.maps.getTileSize()

    -

    Returns map size in tiles: x, y, z

    -
  • -
  • dfhack.maps.getBlock(x,y,z)

    -

    Returns a map block object for given x,y,z in local block coordinates.

    -
  • -
  • dfhack.maps.isValidTilePos(coords), or isValidTilePos(x,y,z)

    -

    Checks if the given df::coord or x,y,z in local tile coordinates are valid.

    -
  • -
  • dfhack.maps.getTileBlock(coords), or getTileBlock(x,y,z)

    -

    Returns a map block object for given df::coord or x,y,z in local tile coordinates.

    -
  • -
  • dfhack.maps.ensureTileBlock(coords), or ensureTileBlock(x,y,z)

    -

    Like getTileBlock, but if the block is not allocated, try creating it.

    -
  • -
  • dfhack.maps.getTileType(coords), or getTileType(x,y,z)

    -

    Returns the tile type at the given coordinates, or nil if invalid.

    -
  • -
  • dfhack.maps.getTileFlags(coords), or getTileFlags(x,y,z)

    -

    Returns designation and occupancy references for the given coordinates, or nil, nil if invalid.

    -
  • -
  • dfhack.maps.getRegionBiome(region_coord2d), or getRegionBiome(x,y)

    -

    Returns the biome info struct for the given global map region.

    -
  • -
  • dfhack.maps.enableBlockUpdates(block[,flow,temperature])

    -

    Enables updates for liquid flow or temperature, unless already active.

    -
  • -
  • dfhack.maps.spawnFlow(pos,type,mat_type,mat_index,dimension)

    -

    Spawns a new flow (i.e. steam/mist/dust/etc) at the given pos, and with -the given parameters. Returns it, or nil if unsuccessful.

    -
  • -
  • dfhack.maps.getGlobalInitFeature(index)

    -

    Returns the global feature object with the given index.

    -
  • -
  • dfhack.maps.getLocalInitFeature(region_coord2d,index)

    -

    Returns the local feature object with the given region coords and index.

    -
  • -
  • dfhack.maps.getTileBiomeRgn(coords), or getTileBiomeRgn(x,y,z)

    -

    Returns x, y for use with getRegionBiome.

    -
  • -
  • dfhack.maps.canWalkBetween(pos1, pos2)

    -

    Checks if a dwarf may be able to walk between the two tiles, -using a pathfinding cache maintained by the game. Note that -this cache is only updated when the game is unpaused, and thus -can get out of date if doors are forbidden or unforbidden, or -tools like liquids or tiletypes are used. It also cannot possibly -take into account anything that depends on the actual units, like -burrows, or the presence of invaders.

    -
  • -
  • dfhack.maps.hasTileAssignment(tilemask)

    -

    Checks if the tile_bitmask object is not nil and contains any set bits; returns true or false.

    -
  • -
  • dfhack.maps.getTileAssignment(tilemask,x,y)

    -

    Checks if the tile_bitmask object is not nil and has the relevant bit set; returns true or false.

    -
  • -
  • dfhack.maps.setTileAssignment(tilemask,x,y,enable)

    -

    Sets the relevant bit in the tile_bitmask object to the enable argument.

    -
  • -
  • dfhack.maps.resetTileAssignment(tilemask[,enable])

    -

    Sets all bits in the mask to the enable argument.

    -
  • -
-
-
-

Burrows module

-
    -
  • dfhack.burrows.findByName(name)

    -

    Returns the burrow pointer or nil.

    -
  • -
  • dfhack.burrows.clearUnits(burrow)

    -

    Removes all units from the burrow.

    -
  • -
  • dfhack.burrows.isAssignedUnit(burrow,unit)

    -

    Checks if the unit is in the burrow.

    -
  • -
  • dfhack.burrows.setAssignedUnit(burrow,unit,enable)

    -

    Adds or removes the unit from the burrow.

    -
  • -
  • dfhack.burrows.clearTiles(burrow)

    -

    Removes all tiles from the burrow.

    -
  • -
  • dfhack.burrows.listBlocks(burrow)

    -

    Returns a table of map block pointers.

    -
  • -
  • dfhack.burrows.isAssignedTile(burrow,tile_coord)

    -

    Checks if the tile is in burrow.

    -
  • -
  • dfhack.burrows.setAssignedTile(burrow,tile_coord,enable)

    -

    Adds or removes the tile from the burrow. Returns false if invalid coords.

    -
  • -
  • dfhack.burrows.isAssignedBlockTile(burrow,block,x,y)

    -

    Checks if the tile within the block is in burrow.

    -
  • -
  • dfhack.burrows.setAssignedBlockTile(burrow,block,x,y,enable)

    -

    Adds or removes the tile from the burrow. Returns false if invalid coords.

    -
  • -
-
-
-

Buildings module

-
    -
  • dfhack.buildings.getGeneralRef(building, type)

    -

    Searches for a general_ref with the given type.

    -
  • -
  • dfhack.buildings.getSpecificRef(building, type)

    -

    Searches for a specific_ref with the given type.

    -
  • -
  • dfhack.buildings.setOwner(item,unit)

    -

    Replaces the owner of the building. If unit is nil, removes ownership. -Returns false in case of error.

    -
  • -
  • dfhack.buildings.getSize(building)

    -

    Returns width, height, centerx, centery.

    -
  • -
  • dfhack.buildings.findAtTile(pos), or findAtTile(x,y,z)

    -

    Scans the buildings for the one located at the given tile. -Does not work on civzones. Warning: linear scan if the map -tile indicates there are buildings at it.

    -
  • -
  • dfhack.buildings.findCivzonesAt(pos), or findCivzonesAt(x,y,z)

    -

    Scans civzones, and returns a lua sequence of those that touch -the given tile, or nil if none.

    -
  • -
  • dfhack.buildings.getCorrectSize(width, height, type, subtype, custom, direction)

    -

    Computes correct dimensions for the specified building type and orientation, -using width and height for flexible dimensions. -Returns is_flexible, width, height, center_x, center_y.

    -
  • -
  • dfhack.buildings.checkFreeTiles(pos,size[,extents,change_extents,allow_occupied])

    -

    Checks if the rectangle defined by pos and size, and possibly extents, -can be used for placing a building. If change_extents is true, bad tiles -are removed from extents. If allow_occupied, the occupancy test is skipped.

    -
  • -
  • dfhack.buildings.countExtentTiles(extents,defval)

    -

    Returns the number of tiles included by extents, or defval.

    -
  • -
  • dfhack.buildings.containsTile(building, x, y[, room])

    -

    Checks if the building contains the specified tile, either directly, or as room.

    -
  • -
  • dfhack.buildings.hasSupport(pos,size)

    -

    Checks if a bridge constructed at specified position would have -support from terrain, and thus won't collapse if retracted.

    -
  • -
  • dfhack.buildings.getStockpileContents(stockpile)

    -

    Returns a list of items stored on the given stockpile. -Ignores empty bins, barrels, and wheelbarrows assigned as storage and transport for that stockpile.

    -
  • -
-

Low-level building creation functions;

-
    -
  • dfhack.buildings.allocInstance(pos, type, subtype, custom)

    -

    Creates a new building instance of given type, subtype and custom type, -at specified position. Returns the object, or nil in case of an error.

    -
  • -
  • dfhack.buildings.setSize(building, width, height, direction)

    -

    Configures an object returned by allocInstance, using specified -parameters wherever appropriate. If the building has fixed size along -any dimension, the corresponding input parameter will be ignored. -Returns false if the building cannot be placed, or true, width, -height, rect_area, true_area. Returned width and height are the -final values used by the building; true_area is less than rect_area -if any tiles were removed from designation.

    -
  • -
  • dfhack.buildings.constructAbstract(building)

    -

    Links a fully configured object created by allocInstance into the -world. The object must be an abstract building, i.e. a stockpile or civzone. -Returns true, or false if impossible.

    -
  • -
  • dfhack.buildings.constructWithItems(building, items)

    -

    Links a fully configured object created by allocInstance into the -world for construction, using a list of specific items as material. -Returns true, or false if impossible.

    -
  • -
  • dfhack.buildings.constructWithFilters(building, job_items)

    -

    Links a fully configured object created by allocInstance into the -world for construction, using a list of job_item filters as inputs. -Returns true, or false if impossible. Filter objects are claimed -and possibly destroyed in any case. -Use a negative quantity field value to auto-compute the amount -from the size of the building.

    -
  • -
  • dfhack.buildings.deconstruct(building)

    -

    Destroys the building, or queues a deconstruction job. -Returns true if the building was destroyed and deallocated immediately.

    -
  • -
-

More high-level functions are implemented in lua and can be loaded by -require('dfhack.buildings'). See hack/lua/dfhack/buildings.lua.

-

Among them are:

-
    -
  • dfhack.buildings.getFiltersByType(argtable,type,subtype,custom)

    -

    Returns a sequence of lua structures, describing input item filters -suitable for the specified building type, or nil if unknown or invalid. -The returned sequence is suitable for use as the job_items argument -of constructWithFilters. -Uses tables defined in buildings.lua.

    -

    Argtable members material (the default name), bucket, barrel, -chain, mechanism, screw, pipe, anvil, weapon are used to -augment the basic attributes with more detailed information if the -building has input items with the matching name (see the tables for naming details). -Note that it is impossible to override any properties this way, only supply those that -are not mentioned otherwise; one exception is that flags2.non_economic -is automatically cleared if an explicit material is specified.

    -
  • -
  • dfhack.buildings.constructBuilding{...}

    -

    Creates a building in one call, using options contained -in the argument table. Returns the building, or nil, error.

    -

    NOTE: Despite the name, unless the building is abstract, -the function creates it in an 'unconstructed' stage, with -a queued in-game job that will actually construct it. I.e. -the function replicates programmatically what can be done -through the construct building menu in the game ui, except -that it does less environment constraint checking.

    -

    The following options can be used:

    -
      -
    • pos = coordinates, or x = ..., y = ..., z = ...

      -

      Mandatory. Specifies the left upper corner of the building.

      -
    • -
    • type = df.building_type.FOO, subtype = ..., custom = ...

      -

      Mandatory. Specifies the type of the building. Obviously, subtype -and custom are only expected if the type requires them.

      -
    • -
    • fields = { ... }

      -

      Initializes fields of the building object after creation with df.assign.

      -
    • -
    • width = ..., height = ..., direction = ...

      -

      Sets size and orientation of the building. If it is -fixed-size, specified dimensions are ignored.

      -
    • -
    • full_rectangle = true

      -

      For buildings like stockpiles or farm plots that can normally -accomodate individual tile exclusion, forces an error if any -tiles within the specified width*height are obstructed.

      -
    • -
    • items = { item, item ... }, or filters = { {...}, {...}... }

      -

      Specifies explicit items or item filters to use in construction. -It is the job of the user to ensure they are correct for the building type.

      -
    • -
    • abstract = true

      -

      Specifies that the building is abstract and does not require construction. -Required for stockpiles and civzones; an error otherwise.

      -
    • -
    • material = {...}, mechanism = {...}, ...

      -

      If none of items, filter, or abstract is used, -the function uses getFiltersByType to compute the input -item filters, and passes the argument table through. If no filters -can be determined this way, constructBuilding throws an error.

      -
    • -
    -
  • -
-
-
-

Constructions module

-
    -
  • dfhack.constructions.designateNew(pos,type,item_type,mat_index)

    -

    Designates a new construction at given position. If there already is -a planned but not completed construction there, changes its type. -Returns true, or false if obstructed. -Note that designated constructions are technically buildings.

    -
  • -
  • dfhack.constructions.designateRemove(pos), or designateRemove(x,y,z)

    -

    If there is a construction or a planned construction at the specified -coordinates, designates it for removal, or instantly cancels the planned one. -Returns true, was_only_planned if removed; or false if none found.

    -
  • -
-
-
-

Screen API

-

The screen module implements support for drawing to the tiled screen of the game. -Note that drawing only has any effect when done from callbacks, so it can only -be feasibly used in the core context.

-

Basic painting functions:

-
    -
  • dfhack.screen.getWindowSize()

    -

    Returns width, height of the screen.

    -
  • -
  • dfhack.screen.getMousePos()

    -

    Returns x,y of the tile the mouse is over.

    -
  • -
  • dfhack.screen.inGraphicsMode()

    -

    Checks if [GRAPHICS:YES] was specified in init.

    -
  • -
  • dfhack.screen.paintTile(pen,x,y[,char,tile])

    -

    Paints a tile using given parameters. See below for a description of pen.

    -

    Returns false if coordinates out of bounds, or other error.

    -
  • -
  • dfhack.screen.readTile(x,y)

    -

    Retrieves the contents of the specified tile from the screen buffers. -Returns a pen object, or nil if invalid or TrueType.

    -
  • -
  • dfhack.screen.paintString(pen,x,y,text)

    -

    Paints the string starting at x,y. Uses the string characters -in sequence to override the ch field of pen.

    -

    Returns true if painting at least one character succeeded.

    -
  • -
  • dfhack.screen.fillRect(pen,x1,y1,x2,y2)

    -

    Fills the rectangle specified by the coordinates with the given pen. -Returns true if painting at least one character succeeded.

    -
  • -
  • dfhack.screen.findGraphicsTile(pagename,x,y)

    -

    Finds a tile from a graphics set (i.e. the raws used for creatures), -if in graphics mode and loaded.

    -

    Returns: tile, tile_grayscale, or nil if not found. -The values can then be used for the tile field of pen structures.

    -
  • -
  • dfhack.screen.clear()

    -

    Fills the screen with blank background.

    -
  • -
  • dfhack.screen.invalidate()

    -

    Requests repaint of the screen by setting a flag. Unlike other -functions in this section, this may be used at any time.

    -
  • -
  • dfhack.screen.getKeyDisplay(key)

    -

    Returns the string that should be used to represent the given -logical keybinding on the screen in texts like "press Key to ...".

    -
  • -
  • dfhack.screen.keyToChar(key)

    -

    Returns the integer character code of the string input -character represented by the given logical keybinding, -or nil if not a string input key.

    -
  • -
  • dfhack.screen.charToKey(charcode)

    -

    Returns the keybinding representing the given string input -character, or nil if impossible.

    -
  • -
-

The "pen" argument used by functions above may be represented by -a table with the following possible fields:

-
-
-
ch
-
Provides the ordinary tile character, as either a 1-character string or a number. -Can be overridden with the char function parameter.
-
fg
-
Foreground color for the ordinary tile. Defaults to COLOR_GREY (7).
-
bg
-
Background color for the ordinary tile. Defaults to COLOR_BLACK (0).
-
bold
-
Bright/bold text flag. If nil, computed based on (fg & 8); fg is masked to 3 bits. -Otherwise should be true/false.
-
tile
-
Graphical tile id. Ignored unless [GRAPHICS:YES] was in init.txt.
-
tile_color = true
-
Specifies that the tile should be shaded with fg/bg.
-
tile_fg, tile_bg
-
If specified, overrides tile_color and supplies shading colors directly.
-
-
-

Alternatively, it may be a pre-parsed native object with the following API:

-
    -
  • dfhack.pen.make(base[,pen_or_fg,bg,bold])

    -

    Creates a new pre-parsed pen by combining its arguments according to the -following rules:

    -
      -
    1. The base argument may be a pen object, a pen table as specified above, -or a single color value. In the single value case, it is split into -fg and bold properties, and others are initialized to 0. -This argument will be converted to a pre-parsed object and returned -if there are no other arguments.
    2. -
    3. If the pen_or_fg argument is specified as a table or object, it -completely replaces the base, and is returned instead of it.
    4. -
    5. Otherwise, the non-nil subset of the optional arguments is used -to update the fg, bg and bold properties of the base. -If the bold flag is nil, but pen_or_fg is a number, bold -is deduced from it like in the simple base case.
    6. -
    -

    This function always returns a new pre-parsed pen, or nil.

    -
  • -
  • dfhack.pen.parse(base[,pen_or_fg,bg,bold])

    -

    Exactly like the above function, but returns base or pen_or_fg -directly if they are already a pre-parsed native object.

    -
  • -
  • pen.property, pen.property = value, pairs(pen)

    -

    Pre-parsed pens support reading and setting their properties, -but don't behave exactly like a simple table would; for instance, -assigning to pen.tile_color also resets pen.tile_fg and -pen.tile_bg to nil.

    -
  • -
-

In order to actually be able to paint to the screen, it is necessary -to create and register a viewscreen (basically a modal dialog) with -the game.

-

NOTE: As a matter of policy, in order to avoid user confusion, all -interface screens added by dfhack should bear the "DFHack" signature.

-

Screens are managed with the following functions:

-
    -
  • dfhack.screen.show(screen[,below])

    -

    Displays the given screen, possibly placing it below a different one. -The screen must not be already shown. Returns true if success.

    -
  • -
  • dfhack.screen.dismiss(screen[,to_first])

    -

    Marks the screen to be removed when the game enters its event loop. -If to_first is true, all screens up to the first one will be deleted.

    -
  • -
  • dfhack.screen.isDismissed(screen)

    -

    Checks if the screen is already marked for removal.

    -
  • -
-

Apart from a native viewscreen object, these functions accept a table -as a screen. In this case, show creates a new native viewscreen -that delegates all processing to methods stored in that table.

-

NOTE: Lua-implemented screens are only supported in the core context.

-

Supported callbacks and fields are:

-
    -
  • screen._native

    -

    Initialized by show with a reference to the backing viewscreen -object, and removed again when the object is deleted.

    -
  • -
  • function screen:onShow()

    -

    Called by dfhack.screen.show if successful.

    -
  • -
  • function screen:onDismiss()

    -

    Called by dfhack.screen.dismiss if successful.

    -
  • -
  • function screen:onDestroy()

    -

    Called from the destructor when the viewscreen is deleted.

    -
  • -
  • function screen:onResize(w, h)

    -

    Called before onRender or onIdle when the window size has changed.

    -
  • -
  • function screen:onRender()

    -

    Called when the viewscreen should paint itself. This is the only context -where the above painting functions work correctly.

    -

    If omitted, the screen is cleared; otherwise it should do that itself. -In order to make a see-through dialog, call self._native.parent:render().

    -
  • -
  • function screen:onIdle()

    -

    Called every frame when the screen is on top of the stack.

    -
  • -
  • function screen:onHelp()

    -

    Called when the help keybinding is activated (usually '?').

    -
  • -
  • function screen:onInput(keys)

    -

    Called when keyboard or mouse events are available. -If any keys are pressed, the keys argument is a table mapping them to true. -Note that this refers to logical keybingings computed from real keys via -options; if multiple interpretations exist, the table will contain multiple keys.

    -

    The table also may contain special keys:

    -
    -
    _STRING
    -

    Maps to an integer in range 0-255. Duplicates a separate "STRING_A???" code for convenience.

    -
    -
    _MOUSE_L, _MOUSE_R
    -

    If the left or right mouse button is being pressed.

    -
    -
    _MOUSE_L_DOWN, _MOUSE_R_DOWN
    -

    If the left or right mouse button was just pressed.

    -
    -
    -

    If this method is omitted, the screen is dismissed on receival of the LEAVESCREEN key.

    -
  • -
  • function screen:onGetSelectedUnit()

    -
  • -
  • function screen:onGetSelectedItem()

    -
  • -
  • function screen:onGetSelectedJob()

    -
  • -
  • function screen:onGetSelectedBuilding()

    -

    Implement these to provide a return value for the matching -dfhack.gui.getSelected... function.

    -
  • -
-
-
-

Filesystem module

-

Most of these functions return true on success and false on failure, -unless otherwise noted.

-
    -
  • dfhack.filesystem.exists(path)

    -

    Returns true if path exists.

    -
  • -
  • dfhack.filesystem.isfile(path)

    -

    Returns true if path exists and is a file.

    -
  • -
  • dfhack.filesystem.isdir(path)

    -

    Returns true if path exists and is a directory.

    -
  • -
  • dfhack.filesystem.getcwd()

    -

    Returns the current working directory. To retrieve the DF path, use dfhack.getDFPath() instead.

    -
  • -
  • dfhack.filesystem.chdir(path)

    -

    Changes the current directory to path. Use with caution.

    -
  • -
  • dfhack.filesystem.mkdir(path)

    -

    Creates a new directory. Returns false if unsuccessful, including if path already exists.

    -
  • -
  • dfhack.filesystem.rmdir(path)

    -

    Removes a directory. Only works if the directory is already empty.

    -
  • -
  • dfhack.filesystem.mtime(path)

    -

    Returns the modification time (in seconds) of the file or directory specified by path, -or -1 if path does not exist. This depends on the system clock and should only be used locally.

    -
  • -
  • dfhack.filesystem.atime(path)

    -
  • -
  • dfhack.filesystem.ctime(path)

    -

    Return values vary across operating systems - return the st_atime and st_ctime -fields of a C++ stat struct, respectively.

    -
  • -
  • dfhack.filesystem.listdir(path)

    -

    Lists files/directories in a directory. Returns {} if path does not exist.

    -
  • -
  • dfhack.filesystem.listdir_recursive(path [, depth = 10])

    -

    Lists all files/directories in a directory and its subdirectories. All directories -are listed before their contents. Returns a table with subtables of the format:

    -
    -{path: 'path to file', isdir: true|false}
    -
    -

    Note that listdir() returns only the base name of each directory entry, while -listdir_recursive() returns the initial path and all components following it -for each entry.

    -
  • -
-
-
-

Internal API

-

These functions are intended for the use by dfhack developers, -and are only documented here for completeness:

-
    -
  • dfhack.internal.scripts

    -

    The table used by dfhack.run_script() to give every script its own -global environment, persistent between calls to the script.

    -
  • -
  • dfhack.internal.getAddress(name)

    -

    Returns the global address name, or nil.

    -
  • -
  • dfhack.internal.setAddress(name, value)

    -

    Sets the global address name. Returns the value of getAddress before the change.

    -
  • -
  • dfhack.internal.getVTable(name)

    -

    Returns the pre-extracted vtable address name, or nil.

    -
  • -
  • dfhack.internal.getImageBase()

    -

    Returns the mmap base of the executable.

    -
  • -
  • dfhack.internal.getRebaseDelta()

    -

    Returns the ASLR rebase offset of the DF executable.

    -
  • -
  • dfhack.internal.adjustOffset(offset[,to_file])

    -

    Returns the re-aligned offset, or nil if invalid. -If to_file is true, the offset is adjusted from memory to file. -This function returns the original value everywhere except windows.

    -
  • -
  • dfhack.internal.getMemRanges()

    -

    Returns a sequence of tables describing virtual memory ranges of the process.

    -
  • -
  • dfhack.internal.patchMemory(dest,src,count)

    -

    Like memmove below, but works even if dest is read-only memory, e.g. code. -If destination overlaps a completely invalid memory region, or another error -occurs, returns false.

    -
  • -
  • dfhack.internal.patchBytes(write_table[, verify_table])

    -

    The first argument must be a lua table, which is interpreted as a mapping from -memory addresses to byte values that should be stored there. The second argument -may be a similar table of values that need to be checked before writing anything.

    -

    The function takes care to either apply all of write_table, or none of it. -An empty write_table with a nonempty verify_table can be used to reasonably -safely check if the memory contains certain values.

    -

    Returns true if successful, or nil, error_msg, address if not.

    -
  • -
  • dfhack.internal.memmove(dest,src,count)

    -

    Wraps the standard memmove function. Accepts both numbers and refs as pointers.

    -
  • -
  • dfhack.internal.memcmp(ptr1,ptr2,count)

    -

    Wraps the standard memcmp function.

    -
  • -
  • dfhack.internal.memscan(haystack,count,step,needle,nsize)

    -

    Searches for needle of nsize bytes in haystack, -using count steps of step bytes. -Returns: step_idx, sum_idx, found_ptr, or nil if not found.

    -
  • -
  • dfhack.internal.diffscan(old_data, new_data, start_idx, end_idx, eltsize[, oldval, newval, delta])

    -

    Searches for differences between buffers at ptr1 and ptr2, as integers of size eltsize. -The oldval, newval or delta arguments may be used to specify additional constraints. -Returns: found_index, or nil if end reached.

    -
  • -
  • dfhack.internal.getDir(path)

    -

    Lists files/directories in a directory. -Returns: file_names or empty table if not found. Identical to dfhack.filesystem.listdir(path).

    -
  • -
  • dfhack.internal.strerror(errno)

    -

    Wraps strerror() - returns a string describing a platform-specific error code

    -
  • -
-
-
-
-

Core interpreter context

-

While plugins can create any number of interpreter instances, -there is one special context managed by dfhack core. It is the -only context that can receive events from DF and plugins.

-

Core context specific functions:

-
    -
  • dfhack.is_core_context

    -

    Boolean value; true in the core context.

    -
  • -
  • dfhack.timeout(time,mode,callback)

    -

    Arranges for the callback to be called once the specified -period of time passes. The mode argument specifies the -unit of time used, and may be one of 'frames' (raw FPS), -'ticks' (unpaused FPS), 'days', 'months', -'years' (in-game time). All timers other than -'frames' are cancelled when the world is unloaded, -and cannot be queued until it is loaded again. -Returns the timer id, or nil if unsuccessful due to -world being unloaded.

    -
  • -
  • dfhack.timeout_active(id[,new_callback])

    -

    Returns the active callback with the given id, or nil -if inactive or nil id. If called with 2 arguments, replaces -the current callback with the given value, if still active. -Using timeout_active(id,nil) cancels the timer.

    -
  • -
  • dfhack.onStateChange.foo = function(code)

    -

    Event. Receives the same codes as plugin_onstatechange in C++.

    -
  • -
-
-

Event type

-

An event is a native object transparently wrapping a lua table, -and implementing a __call metamethod. When it is invoked, it loops -through the table with next and calls all contained values. -This is intended as an extensible way to add listeners.

-

This type itself is available in any context, but only the -core context has the actual events defined by C++ code.

-

Features:

-
    -
  • dfhack.event.new()

    -

    Creates a new instance of an event.

    -
  • -
  • event[key] = function

    -

    Sets the function as one of the listeners. Assign nil to remove it.

    -

    NOTE: The df.NULL key is reserved for the use by -the C++ owner of the event; it is an error to try setting it.

    -
  • -
  • #event

    -

    Returns the number of non-nil listeners.

    -
  • -
  • pairs(event)

    -

    Iterates over all listeners in the table.

    -
  • -
  • event(args...)

    -

    Invokes all listeners contained in the event in an arbitrary -order using dfhack.safecall.

    -
  • -
-
-
-
-
-

Lua Modules

-

DFHack sets up the lua interpreter so that the built-in require -function can be used to load shared lua code from hack/lua/. -The dfhack namespace reference itself may be obtained via -require('dfhack'), although it is initially created as a -global by C++ bootstrap code.

-

The following module management functions are provided:

- -
-

Global environment

-

A number of variables and functions are provided in the base global -environment by the mandatory init file dfhack.lua:

-
    -
  • Color constants

    -

    These are applicable both for dfhack.color() and color fields -in DF functions or structures:

    -

    COLOR_RESET, COLOR_BLACK, COLOR_BLUE, COLOR_GREEN, COLOR_CYAN, -COLOR_RED, COLOR_MAGENTA, COLOR_BROWN, COLOR_GREY, COLOR_DARKGREY, -COLOR_LIGHTBLUE, COLOR_LIGHTGREEN, COLOR_LIGHTCYAN, COLOR_LIGHTRED, -COLOR_LIGHTMAGENTA, COLOR_YELLOW, COLOR_WHITE

    -
  • -
  • dfhack.onStateChange event codes

    -

    Available only in the core context, as is the event itself:

    -

    SC_WORLD_LOADED, SC_WORLD_UNLOADED, SC_MAP_LOADED, -SC_MAP_UNLOADED, SC_VIEWSCREEN_CHANGED, SC_CORE_INITIALIZED

    -
  • -
  • Functions already described above

    -

    safecall, qerror, mkmodule, reload

    -
  • -
  • Miscellaneous constants

    - --- - - - - - - -
    NEWLINE, COMMA, PERIOD:
     evaluate to the relevant character strings.
    DEFAULT_NIL:is an unspecified unique token used by the class module below.
    -
  • -
  • printall(obj)

    -

    If the argument is a lua table or DF object reference, prints all fields.

    -
  • -
  • copyall(obj)

    -

    Returns a shallow copy of the table or reference as a lua table.

    -
  • -
  • pos2xyz(obj)

    -

    The object must have fields x, y and z. Returns them as 3 values. -If obj is nil, or x is -30000 (the usual marker for undefined -coordinates), returns nil.

    -
  • -
  • xyz2pos(x,y,z)

    -

    Returns a table with x, y and z as fields.

    -
  • -
  • same_xyz(a,b)

    -

    Checks if a and b have the same x, y and z fields.

    -
  • -
  • get_path_xyz(path,i)

    -

    Returns path.x[i], path.y[i], path.z[i].

    -
  • -
  • pos2xy(obj), xy2pos(x,y), same_xy(a,b), get_path_xy(a,b)

    -

    Same as above, but for 2D coordinates.

    -
  • -
  • safe_index(obj,index...)

    -

    Walks a sequence of dereferences, which may be represented by numbers or strings. -Returns nil if any of obj or indices is nil, or a numeric index is out of array bounds.

    -
  • -
-
-
-

utils

-
    -
  • utils.compare(a,b)

    -

    Comparator function; returns -1 if a<b, 1 if a>b, 0 otherwise.

    -
  • -
  • utils.compare_name(a,b)

    -

    Comparator for names; compares empty string last.

    -
  • -
  • utils.is_container(obj)

    -

    Checks if obj is a container ref.

    -
  • -
  • utils.make_index_sequence(start,end)

    -

    Returns a lua sequence of numbers in start..end.

    -
  • -
  • utils.make_sort_order(data, ordering)

    -

    Computes a sorted permutation of objects in data, as a table of integer -indices into the data sequence. Uses data.n as input length -if present.

    -

    The ordering argument is a sequence of ordering specs, represented -as lua tables with following possible fields:

    -
    -
    ord.key = function(value)
    -

    Computes comparison key from input data value. Not called on nil. -If omitted, the comparison key is the value itself.

    -
    -
    ord.key_table = function(data)
    -

    Computes a key table from the data table in one go.

    -
    -
    ord.compare = function(a,b)
    -

    Comparison function. Defaults to utils.compare above. -Called on non-nil keys; nil sorts last.

    -
    -
    ord.nil_first = true/false
    -

    If true, nil keys are sorted first instead of last.

    -
    -
    ord.reverse = true/false
    -

    If true, sort non-nil keys in descending order.

    -
    -
    -

    For every comparison during sorting the specs are applied in -order until an unambiguous decision is reached. Sorting is stable.

    -

    Example of sorting a sequence by field foo:

    -
    -local spec = { key = function(v) return v.foo end }
    -local order = utils.make_sort_order(data, { spec })
    -local output = {}
    -for i = 1,#order do output[i] = data[order[i]] end
    -
    -

    Separating the actual reordering of the sequence in this -way enables applying the same permutation to multiple arrays. -This function is used by the sort plugin.

    -
  • -
  • for link,item in utils.listpairs(list)

    -

    Iterates a df-list structure, for example df.global.world.job_list.

    -
  • -
  • utils.assign(tgt, src)

    -

    Does a recursive assignment of src into tgt. -Uses df.assign if tgt is a native object ref; otherwise -recurses into lua tables.

    -
  • -
  • utils.clone(obj, deep)

    -

    Performs a shallow, or semi-deep copy of the object as a lua table tree. -The deep mode recurses into lua tables and subobjects, except pointers -to other heap objects. -Null pointers are represented as df.NULL. Zero-based native containers -are converted to 1-based lua sequences.

    -
  • -
  • utils.clone_with_default(obj, default, force)

    -

    Copies the object, using the default lua table tree -as a guide to which values should be skipped as uninteresting. -The force argument makes it always return a non-nil value.

    -
  • -
  • utils.parse_bitfield_int(value, type_ref)

    -

    Given an int value, and a bitfield type in the df tree, -it returns a lua table mapping the enabled bit keys to true, -unless value is 0, in which case it returns nil.

    -
  • -
  • utils.list_bitfield_flags(bitfield[, list])

    -

    Adds all enabled bitfield keys to list or a newly-allocated -empty sequence, and returns it. The bitfield argument may -be nil.

    -
  • -
  • utils.sort_vector(vector,field,cmpfun)

    -

    Sorts a native vector or lua sequence using the comparator function. -If field is not nil, applies the comparator to the field instead -of the whole object.

    -
  • -
  • utils.linear_index(vector,key[,field])

    -

    Searches for key in the vector, and returns index, found_value, -or nil if none found.

    -
  • -
  • utils.binsearch(vector,key,field,cmpfun,min,max)

    -

    Does a binary search in a native vector or lua sequence for -key, using cmpfun and field like sort_vector. -If min and max are specified, they are used as the -search subrange bounds.

    -

    If found, returns item, true, idx. Otherwise returns -nil, false, insert_idx, where insert_idx is the correct -insertion point.

    -
  • -
  • utils.insert_sorted(vector,item,field,cmpfun)

    -

    Does a binary search, and inserts item if not found. -Returns did_insert, vector[idx], idx.

    -
  • -
  • utils.insert_or_update(vector,item,field,cmpfun)

    -

    Like insert_sorted, but also assigns the item into -the vector cell if insertion didn't happen.

    -

    As an example, you can use this to set skill values:

    -
    -utils.insert_or_update(soul.skills, {new=true, id=..., rating=...}, 'id')
    -
    -

    (For an explanation of new=true, see table assignment in the wrapper section)

    -
  • -
  • utils.erase_sorted_key(vector,key,field,cmpfun)

    -

    Removes the item with the given key from the list. Returns: did_erase, vector[idx], idx.

    -
  • -
  • utils.erase_sorted(vector,item,field,cmpfun)

    -

    Exactly like erase_sorted_key, but if field is specified, takes the key from item[field].

    -
  • -
  • utils.call_with_string(obj,methodname,...)

    -

    Allocates a temporary string object, calls obj:method(tmp,...), and -returns the value written into the temporary after deleting it.

    -
  • -
  • utils.getBuildingName(building)

    -

    Returns the string description of the given building.

    -
  • -
  • utils.getBuildingCenter(building)

    -

    Returns an x/y/z table pointing at the building center.

    -
  • -
  • utils.split_string(string, delimiter)

    -

    Splits the string by the given delimiter, and returns a sequence of results.

    -
  • -
  • utils.prompt_yes_no(prompt, default)

    -

    Presents a yes/no prompt to the user. If default is not nil, -allows just pressing Enter to submit the default choice. -If the user enters 'abort', throws an error.

    -
  • -
  • utils.prompt_input(prompt, checkfun, quit_str)

    -

    Presents a prompt to input data, until a valid string is entered. -Once checkfun(input) returns true, ..., passes the values -through. If the user enters the quit_str (defaults to '~~~'), -throws an error.

    -
  • -
  • utils.check_number(text)

    -

    A prompt_input checkfun that verifies a number input.

    -
  • -
-
-
-

dumper

-

A third-party lua table dumper module from -http://lua-users.org/wiki/DataDumper. Defines one -function:

-
    -
  • dumper.DataDumper(value, varname, fastmode, ident, indent_step)

    -

    Returns value converted to a string. The indent_step -argument specifies the indentation step size in spaces. For -the other arguments see the original documentation link above.

    -
  • -
-
-
-

class

-

Implements a trivial single-inheritance class system.

-
    -
  • Foo = defclass(Foo[, ParentClass])

    -

    Defines or updates class Foo. The Foo = defclass(Foo) syntax -is needed so that when the module or script is reloaded, the -class identity will be preserved through the preservation of -global variable values.

    -

    The defclass function is defined as a stub in the global -namespace, and using it will auto-load the class module.

    -
  • -
  • Class.super

    -

    This class field is set by defclass to the parent class, and -allows a readable Class.super.method(self, ...) syntax for -calling superclass methods.

    -
  • -
  • Class.ATTRS { foo = xxx, bar = yyy }

    -

    Declares certain instance fields to be attributes, i.e. auto-initialized -from fields in the table used as the constructor argument. If omitted, -they are initialized with the default values specified in this declaration.

    -

    If the default value should be nil, use ATTRS { foo = DEFAULT_NIL }.

    -

    Declaring an attribute is mostly the same as defining your init method like this:

    -
    -function Class.init(args)
    -    self.attr1 = args.attr1 or default1
    -    self.attr2 = args.attr2 or default2
    -    ...
    -end
    -
    -

    The main difference is that attributes are processed as a separate -initialization step, before any init methods are called. They -also make the directy relation between instance fields and constructor -arguments more explicit.

    -
  • -
  • new_obj = Class{ foo = arg, bar = arg, ... }

    -

    Calling the class as a function creates and initializes a new instance. -Initialization happens in this order:

    -
      -
    1. An empty instance table is created, and its metatable set.
    2. -
    3. The preinit methods are called via invoke_before (see below) -with the table used as argument to the class. These methods are intended -for validating and tweaking that argument table.
    4. -
    5. Declared ATTRS are initialized from the argument table or their default values.
    6. -
    7. The init methods are called via invoke_after with the argument table. -This is the main constructor method.
    8. -
    9. The postinit methods are called via invoke_after with the argument table. -Place code that should be called after the object is fully constructed here.
    10. -
    -
  • -
-

Predefined instance methods:

-
    -
  • instance:assign{ foo = xxx }

    -

    Assigns all values in the input table to the matching instance fields.

    -
  • -
  • instance:callback(method_name, [args...])

    -

    Returns a closure that invokes the specified method of the class, -properly passing in self, and optionally a number of initial arguments too. -The arguments given to the closure are appended to these.

    -
  • -
  • instance:cb_getfield(field_name)

    -

    Returns a closure that returns the specified field of the object when called.

    -
  • -
  • instance:cb_setfield(field_name)

    -

    Returns a closure that sets the specified field to its argument when called.

    -
  • -
  • instance:invoke_before(method_name, args...)

    -

    Navigates the inheritance chain of the instance starting from the most specific -class, and invokes the specified method with the arguments if it is defined in -that specific class. Equivalent to the following definition in every class:

    -
    -function Class:invoke_before(method, ...)
    -  if rawget(Class, method) then
    -    rawget(Class, method)(self, ...)
    -  end
    -  Class.super.invoke_before(method, ...)
    -end
    -
    -
  • -
  • instance:invoke_after(method_name, args...)

    -

    Like invoke_before, only the method is called after the recursive call to super, -i.e. invocations happen in the parent to child order.

    -

    These two methods are inspired by the Common Lisp before and after methods, and -are intended for implementing similar protocols for certain things. The class -library itself uses them for constructors.

    -
  • -
-

To avoid confusion, these methods cannot be redefined.

-
-
-
-

In-game UI Library

-

A number of lua modules with names starting with gui are dedicated -to wrapping the natives of the dfhack.screen module in a way that -is easy to use. This allows relatively easily and naturally creating -dialogs that integrate in the main game UI window.

-

These modules make extensive use of the class module, and define -things ranging from the basic Painter, View and Screen -classes, to fully functional predefined dialogs.

-
-

gui

-

This module defines the most important classes and functions for -implementing interfaces. This documents those of them that are -considered stable.

-
-

Misc

-
    -
  • USE_GRAPHICS

    -

    Contains the value of dfhack.screen.inGraphicsMode(), which cannot be -changed without restarting the game and thus is constant during the session.

    -
  • -
  • CLEAR_PEN

    -

    The black pen used to clear the screen.

    -
  • -
  • simulateInput(screen, keys...)

    -

    This function wraps an undocumented native function that passes a set of -keycodes to a screen, and is the official way to do that.

    -

    Every argument after the initial screen may be nil, a numeric keycode, -a string keycode, a sequence of numeric or string keycodes, or a mapping -of keycodes to true or false. For instance, it is possible to use the -table passed as argument to onInput.

    -
  • -
  • mkdims_xy(x1,y1,x2,y2)

    -

    Returns a table containing the arguments as fields, and also width and -height that contains the rectangle dimensions.

    -
  • -
  • mkdims_wh(x1,y1,width,height)

    -

    Returns the same kind of table as mkdims_xy, only this time it computes -x2 and y2.

    -
  • -
  • is_in_rect(rect,x,y)

    -

    Checks if the given point is within a rectangle, represented by a table produced -by one of the mkdims functions.

    -
  • -
  • blink_visible(delay)

    -

    Returns true or false, with the value switching to the opposite every delay -msec. This is intended for rendering blinking interface objects.

    -
  • -
  • getKeyDisplay(keycode)

    -

    Wraps dfhack.screen.getKeyDisplay in order to allow using strings for the keycode argument.

    -
  • -
-
-
-

ViewRect class

-

This class represents an on-screen rectangle with an associated independent -clip area rectangle. It is the base of the Painter class, and is used by -Views to track their client area.

-
    -
  • ViewRect{ rect = ..., clip_rect = ..., view_rect = ..., clip_view = ... }

    -

    The constructor has the following arguments:

    - --- - - - - - - - - - -
    rect:The mkdims rectangle in screen coordinates of the logical viewport. -Defaults to the whole screen.
    clip_rect:The clip rectangle in screen coordinates. Defaults to rect.
    view_rect:A ViewRect object to copy from; overrides both rect and clip_rect.
    clip_view:A ViewRect object to intersect the specified clip area with.
    -
  • -
  • rect:isDefunct()

    -

    Returns true if the clip area is empty, i.e. no painting is possible.

    -
  • -
  • rect:inClipGlobalXY(x,y)

    -

    Checks if these global coordinates are within the clip rectangle.

    -
  • -
  • rect:inClipLocalXY(x,y)

    -

    Checks if these coordinates (specified relative to x1,y1) are within the clip rectangle.

    -
  • -
  • rect:localXY(x,y)

    -

    Converts a pair of global coordinates to local; returns x_local,y_local.

    -
  • -
  • rect:globalXY(x,y)

    -

    Converts a pair of local coordinates to global; returns x_global,y_global.

    -
  • -
  • rect:viewport(x,y,w,h) or rect:viewport(subrect)

    -

    Returns a ViewRect representing a sub-rectangle of the current one. -The arguments are specified in local coordinates; the subrect -argument must be a mkdims table. The returned object consists of -the exact specified rectangle, and a clip area produced by intersecting -it with the clip area of the original object.

    -
  • -
-
-
-

Painter class

-

The painting natives in dfhack.screen apply to the whole screen, are -completely stateless and don't implement clipping.

-

The Painter class inherits from ViewRect to provide clipping and local -coordinates, and tracks current cursor position and current pen.

-
    -
  • Painter{ ..., pen = ..., key_pen = ... }

    -

    In addition to ViewRect arguments, Painter accepts a suggestion of -the initial value for the main pen, and the keybinding pen. They -default to COLOR_GREY and COLOR_LIGHTGREEN otherwise.

    -

    There are also some convenience functions that wrap this constructor:

    -
      -
    • Painter.new(rect,pen)
    • -
    • Painter.new_view(view_rect,pen)
    • -
    • Painter.new_xy(x1,y1,x2,y2,pen)
    • -
    • Painter.new_wh(x1,y1,width,height,pen)
    • -
    -
  • -
  • painter:isValidPos()

    -

    Checks if the current cursor position is within the clip area.

    -
  • -
  • painter:viewport(x,y,w,h)

    -

    Like the superclass method, but returns a Painter object.

    -
  • -
  • painter:cursor()

    -

    Returns the current cursor x,y in local coordinates.

    -
  • -
  • painter:seek(x,y)

    -

    Sets the current cursor position, and returns self. -Either of the arguments may be nil to keep the current value.

    -
  • -
  • painter:advance(dx,dy)

    -

    Adds the given offsets to the cursor position, and returns self. -Either of the arguments may be nil to keep the current value.

    -
  • -
  • painter:newline([dx])

    -

    Advances the cursor to the start of the next line plus the given x offset, and returns self.

    -
  • -
  • painter:pen(...)

    -

    Sets the current pen to dfhack.pen.parse(old_pen,...), and returns self.

    -
  • -
  • painter:key_pen(...)

    -

    Sets the current keybinding pen to dfhack.pen.parse(old_pen,...), and returns self.

    -
  • -
  • painter:clear()

    -

    Fills the whole clip rectangle with CLEAR_PEN, and returns self.

    -
  • -
  • painter:fill(x1,y1,x2,y2[,...]) or painter:fill(rect[,...])

    -

    Fills the specified local coordinate rectangle with dfhack.pen.parse(cur_pen,...), -and returns self.

    -
  • -
  • painter:char([char[, ...]])

    -

    Paints one character using char and dfhack.pen.parse(cur_pen,...); returns self. -The char argument, if not nil, is used to override the ch property of the pen.

    -
  • -
  • painter:tile([char, tile[, ...]])

    -

    Like above, but also allows overriding the tile property on ad-hoc basis.

    -
  • -
  • painter:string(text[, ...])

    -

    Paints the string with dfhack.pen.parse(cur_pen,...); returns self.

    -
  • -
  • painter:key(keycode[, ...])

    -

    Paints the description of the keycode using dfhack.pen.parse(cur_key_pen,...); returns self.

    -
  • -
-

As noted above, all painting methods return self, in order to allow chaining them like this:

-
-painter:pen(foo):seek(x,y):char(1):advance(1):string('bar')...
-
-
-
-

View class

-

This class is the common abstract base of both the stand-alone screens -and common widgets to be used inside them. It defines the basic layout, -rendering and event handling framework.

-

The class defines the following attributes:

- --- - - - - - - - -
visible:Specifies that the view should be painted.
active:Specifies that the view should receive events, if also visible.
view_id:Specifies an identifier to easily identify the view among subviews. -This is reserved for implementation of top-level views, and should -not be used by widgets for their internal subviews.
-

It also always has the following fields:

- --- - - - -
subviews:Contains a table of all subviews. The sequence part of the -table is used for iteration. In addition, subviews are also -indexed under their view_id, if any; see addviews() below.
-

These fields are computed by the layout process:

- --- - - - - - - - - -
frame_parent_rect:
 The ViewRect represeting the client area of the parent view.
frame_rect:The mkdims rect of the outer frame in parent-local coordinates.
frame_body:The ViewRect representing the body part of the View's own frame.
-

The class has the following methods:

-
    -
  • view:addviews(list)

    -

    Adds the views in the list to the subviews sequence. If any of the views -in the list have view_id attributes that don't conflict with existing keys -in subviews, also stores them under the string keys. Finally, copies any -non-conflicting string keys from the subviews tables of the listed views.

    -

    Thus, doing something like this:

    -
    -self:addviews{
    -    Panel{
    -        view_id = 'panel',
    -        subviews = {
    -            Label{ view_id = 'label' }
    -        }
    -    }
    -}
    -
    -

    Would make the label accessible as both self.subviews.label and -self.subviews.panel.subviews.label.

    -
  • -
  • view:getWindowSize()

    -

    Returns the dimensions of the frame_body rectangle.

    -
  • -
  • view:getMousePos()

    -

    Returns the mouse x,y in coordinates local to the frame_body -rectangle if it is within its clip area, or nothing otherwise.

    -
  • -
  • view:updateLayout([parent_rect])

    -

    Recomputes layout of the view and its subviews. If no argument is -given, re-uses the previous parent rect. The process goes as follows:

    -
      -
    1. Calls preUpdateLayout(parent_rect) via invoke_before.
    2. -
    3. Uses computeFrame(parent_rect) to compute the desired frame.
    4. -
    5. Calls postComputeFrame(frame_body) via invoke_after.
    6. -
    7. Calls updateSubviewLayout(frame_body) to update children.
    8. -
    9. Calls postUpdateLayout(frame_body) via invoke_after.
    10. -
    -
  • -
  • view:computeFrame(parent_rect) (for overriding)

    -

    Called by updateLayout in order to compute the frame rectangle(s). -Should return the mkdims rectangle for the outer frame, and optionally -also for the body frame. If only one rectangle is returned, it is used -for both frames, and the margin becomes zero.

    -
  • -
  • view:updateSubviewLayout(frame_body)

    -

    Calls updateLayout on all children.

    -
  • -
  • view:render(painter)

    -

    Given the parent's painter, renders the view via the following process:

    -
      -
    1. Calls onRenderFrame(painter, frame_rect) to paint the outer frame.
    2. -
    3. Creates a new painter using the frame_body rect.
    4. -
    5. Calls onRenderBody(new_painter) to paint the client area.
    6. -
    7. Calls renderSubviews(new_painter) to paint visible children.
    8. -
    -
  • -
  • view:renderSubviews(painter)

    -

    Calls render on all visible subviews in the order they -appear in the subviews sequence.

    -
  • -
  • view:onRenderFrame(painter, rect) (for overriding)

    -

    Called by render to paint the outer frame; by default does nothing.

    -
  • -
  • view:onRenderBody(painter) (for overriding)

    -

    Called by render to paint the client area; by default does nothing.

    -
  • -
  • view:onInput(keys) (for overriding)

    -

    Override this to handle events. By default directly calls inputToSubviews. -Return a true value from this method to signal that the event has been handled -and should not be passed on to more views.

    -
  • -
  • view:inputToSubviews(keys)

    -

    Calls onInput on all visible active subviews, iterating the subviews -sequence in reverse order, so that topmost subviews get events first. -Returns true if any of the subviews handled the event.

    -
  • -
-
-
-

Screen class

-

This is a View subclass intended for use as a stand-alone dialog or screen. -It adds the following methods:

-
    -
  • screen:isShown()

    -

    Returns true if the screen is currently in the game engine's display stack.

    -
  • -
  • screen:isDismissed()

    -

    Returns true if the screen is dismissed.

    -
  • -
  • screen:isActive()

    -

    Returns true if the screen is shown and not dismissed.

    -
  • -
  • screen:invalidate()

    -

    Requests a repaint. Note that currently using it is not necessary, because -repaints are constantly requested automatically, due to issues with native -screens happening otherwise.

    -
  • -
  • screen:renderParent()

    -

    Asks the parent native screen to render itself, or clears the screen if impossible.

    -
  • -
  • screen:sendInputToParent(...)

    -

    Uses simulateInput to send keypresses to the native parent screen.

    -
  • -
  • screen:show([parent])

    -

    Adds the screen to the display stack with the given screen as the parent; -if parent is not specified, places this one one topmost. Before calling -dfhack.screen.show, calls self:onAboutToShow(parent).

    -
  • -
  • screen:onAboutToShow(parent) (for overriding)

    -

    Called when dfhack.screen.show is about to be called.

    -
  • -
  • screen:onShow()

    -

    Called by dfhack.screen.show once the screen is successfully shown.

    -
  • -
  • screen:dismiss()

    -

    Dismisses the screen. A dismissed screen does not receive any more -events or paint requests, but may remain in the display stack for -a short time until the game removes it.

    -
  • -
  • screen:onDismiss() (for overriding)

    -

    Called by dfhack.screen.dismiss().

    -
  • -
  • screen:onDestroy() (for overriding)

    -

    Called by the native code when the screen is fully destroyed and removed -from the display stack. Place code that absolutely must be called whenever -the screen is removed by any means here.

    -
  • -
  • screen:onResize, screen:onRender

    -

    Defined as callbacks for native code.

    -
  • -
-
-
-

FramedScreen class

-

A Screen subclass that paints a visible frame around its body. -Most dialogs should inherit from this class.

-

A framed screen has the following attributes:

- --- - - - - - - - - - - - - - - -
frame_style:A table that defines a set of pens to draw various parts of the frame.
frame_title:A string to display in the middle of the top of the frame.
frame_width:Desired width of the client area. If nil, the screen will occupy the whole width.
frame_height:Likewise, for height.
frame_inset:The gap between the frame and the client area. Defaults to 0.
frame_background:
 The pen to fill in the frame with. Defaults to CLEAR_PEN.
-

There are the following predefined frame style tables:

-
    -
  • GREY_FRAME

    -

    A plain grey-colored frame.

    -
  • -
  • BOUNDARY_FRAME

    -

    The same frame as used by the usual full-screen DF views, like dwarfmode.

    -
  • -
  • GREY_LINE_FRAME

    -

    A frame consisting of grey lines, similar to the one used by titan announcements.

    -
  • -
-
-
-
-

gui.widgets

-

This module implements some basic widgets based on the View infrastructure.

-
-

Widget class

-

Base of all the widgets. Inherits from View and has the following attributes:

-
    -
  • frame = {...}

    -

    Specifies the constraints on the outer frame of the widget. -If omitted, the widget will occupy the whole parent rectangle.

    -

    The frame is specified as a table with the following possible fields:

    - --- - - - - - - - - - - - - - - - - - -
    l:gap between the left edges of the frame and the parent.
    t:gap between the top edges of the frame and the parent.
    r:gap between the right edges of the frame and the parent.
    b:gap between the bottom edges of the frame and the parent.
    w:maximum width of the frame.
    h:maximum heigth of the frame.
    xalign:X alignment of the frame.
    yalign:Y alignment of the frame.
    -

    First the l,t,r,b fields restrict the available area for -placing the frame. If w and h are not specified or -larger then the computed area, it becomes the frame. Otherwise -the smaller frame is placed within the are based on the -xalign/yalign fields. If the align hints are omitted, they -are assumed to be 0, 1, or 0.5 based on which of the l/r/t/b -fields are set.

    -
  • -
  • frame_inset = {...}

    -

    Specifies the gap between the outer frame, and the client area. -The attribute may be a simple integer value to specify a uniform -inset, or a table with the following fields:

    - --- - - - - - - - - - - - - - -
    l:left margin.
    t:top margin.
    r:right margin.
    b:bottom margin.
    x:left/right margin, if l and/or r are omitted.
    y:top/bottom margin, if t and/or b are omitted.
    -
  • -
  • frame_background = pen

    -

    The pen to fill the outer frame with. Defaults to no fill.

    -
  • -
-
-
-

Panel class

-

Inherits from Widget, and intended for grouping a number of subviews.

-

Has attributes:

-
    -
  • subviews = {}

    -

    Used to initialize the subview list in the constructor.

    -
  • -
  • on_render = function(painter)

    -

    Called from onRenderBody.

    -
  • -
-
-
-

Pages class

-

Subclass of Panel; keeps exactly one child visible.

-
    -
  • Pages{ ..., selected = ... }

    -

    Specifies which child to select initially; defaults to the first one.

    -
  • -
  • pages:getSelected()

    -

    Returns the selected index, child.

    -
  • -
  • pages:setSelected(index)

    -

    Selects the specified child, hiding the previous selected one. -It is permitted to use the subview object, or its view_id as index.

    -
  • -
-
-
-

EditField class

-

Subclass of Widget; implements a simple edit field.

-

Attributes:

- --- - - - - - - - - - - - -
text:The current contents of the field.
text_pen:The pen to draw the text with.
on_char:Input validation callback; used as on_char(new_char,text). -If it returns false, the character is ignored.
on_change:Change notification callback; used as on_change(new_text,old_text).
on_submit:Enter key callback; if set the field will handle the key and call on_submit(text).
-
-
-

Label class

-

This Widget subclass implements flowing semi-static text.

-

It has the following attributes:

- --- - - - - - - - - - - - - - -
text_pen:Specifies the pen for active text.
text_dpen:Specifies the pen for disabled text.
disabled:Boolean or a callback; if true, the label is disabled.
enabled:Boolean or a callback; if false, the label is disabled.
auto_height:Sets self.frame.h from the text height.
auto_width:Sets self.frame.w from the text width.
-

The text itself is represented as a complex structure, and passed -to the object via the text argument of the constructor, or via -the setText method, as one of:

-
    -
  • A simple string, possibly containing newlines.
  • -
  • A sequence of tokens.
  • -
-

Every token in the sequence in turn may be either a string, possibly -containing newlines, or a table with the following possible fields:

-
    -
  • token.text = ...

    -

    Specifies the main text content of a token, and may be a string, or -a callback returning a string.

    -
  • -
  • token.gap = ...

    -

    Specifies the number of character positions to advance on the line -before rendering the token.

    -
  • -
  • token.tile = pen

    -

    Specifies a pen to paint as one tile before the main part of the token.

    -
  • -
  • token.width = ...

    -

    If specified either as a value or a callback, the text field is padded -or truncated to the specified number.

    -
  • -
  • token.pad_char = '?'

    -

    If specified together with width, the padding area is filled with -this character instead of just being skipped over.

    -
  • -
  • token.key = '...'

    -

    Specifies the keycode associated with the token. The string description -of the key binding is added to the text content of the token.

    -
  • -
  • token.key_sep = '...'

    -

    Specifies the separator to place between the keybinding label produced -by token.key, and the main text of the token. If the separator is -'()', the token is formatted as text..' ('..binding..')'. Otherwise -it is simply binding..sep..text.

    -
  • -
  • token.enabled, token.disabled

    -

    Same as the attributes of the label itself, but applies only to the token.

    -
  • -
  • token.pen, token.dpen

    -

    Specify the pen and disabled pen to be used for the token's text. -The field may be either the pen itself, or a callback that returns it.

    -
  • -
  • token.on_activate

    -

    If this field is not nil, and token.key is set, the token will actually -respond to that key binding unless disabled, and call this callback. Eventually -this may be extended with mouse click support.

    -
  • -
  • token.id

    -

    Specifies a unique identifier for the token.

    -
  • -
  • token.line, token.x1, token.x2

    -

    Reserved for internal use.

    -
  • -
-

The Label widget implements the following methods:

-
    -
  • label:setText(new_text)

    -

    Replaces the text currently contained in the widget.

    -
  • -
  • label:itemById(id)

    -

    Finds a token by its id field.

    -
  • -
  • label:getTextHeight()

    -

    Computes the height of the text.

    -
  • -
  • label:getTextWidth()

    -

    Computes the width of the text.

    -
  • -
-
-
-

List class

-

The List widget implements a simple list with paging.

-

It has the following attributes:

- --- - - - - - - - - - - - - - - - - - - - - - -
text_pen:Specifies the pen for deselected list entries.
cursor_pen:Specifies the pen for the selected entry.
inactive_pen:If specified, used for the cursor when the widget is not active.
icon_pen:Default pen for icons.
on_select:Selection change callback; called as on_select(index,choice). -This is also called with nil arguments if setChoices is called -with an empty list.
on_submit:Enter key callback; if specified, the list reacts to the key -and calls it as on_submit(index,choice).
on_submit2:Shift-Enter key callback; if specified, the list reacts to the key -and calls it as on_submit2(index,choice).
row_height:Height of every row in text lines.
icon_width:If not nil, the specified number of character columns -are reserved to the left of the list item for the icons.
scroll_keys:Specifies which keys the list should react to as a table.
-

Every list item may be specified either as a string, or as a lua table -with the following fields:

- --- - - - - - - - - - - - - - -
text:Specifies the label text in the same format as the Label text.
caption, [1]:Deprecated legacy aliases for text.
text_*:Reserved for internal use.
key:Specifies a keybinding that acts as a shortcut for the specified item.
icon:Specifies an icon string, or a pen to paint a single character. May be a callback.
icon_pen:When the icon is a string, used to paint it.
-

The list supports the following methods:

-
    -
  • List{ ..., choices = ..., selected = ... }

    -

    Same as calling setChoices after construction.

    -
  • -
  • list:setChoices(choices[, selected])

    -

    Replaces the list of choices, possibly also setting the currently selected index.

    -
  • -
  • list:setSelected(selected)

    -

    Sets the currently selected index. Returns the index after validation.

    -
  • -
  • list:getChoices()

    -

    Returns the list of choices.

    -
  • -
  • list:getSelected()

    -

    Returns the selected index, choice, or nothing if the list is empty.

    -
  • -
  • list:getContentWidth()

    -

    Returns the minimal width to draw all choices without clipping.

    -
  • -
  • list:getContentHeight()

    -

    Returns the minimal width to draw all choices without scrolling.

    -
  • -
  • list:submit()

    -

    Call the on_submit callback, as if the Enter key was handled.

    -
  • -
  • list:submit2()

    -

    Call the on_submit2 callback, as if the Shift-Enter key was handled.

    -
  • -
-
-
-

FilteredList class

-

This widget combines List, EditField and Label into a combo-box like -construction that allows filtering the list by subwords of its items.

-

In addition to passing through all attributes supported by List, it -supports:

- --- - - - - - - - - -
edit_pen:If specified, used instead of cursor_pen for the edit field.
edit_below:If true, the edit field is placed below the list instead of above.
not_found_label:
 Specifies the text of the label shown when no items match the filter.
-

The list choices may include the following attributes:

- --- - - - -
search_key:If specified, used instead of text to match against the filter.
-

The widget implements:

-
    -
  • list:setChoices(choices[, selected])

    -

    Resets the filter, and passes through to the inner list.

    -
  • -
  • list:getChoices()

    -

    Returns the list of all choices.

    -
  • -
  • list:getFilter()

    -

    Returns the current filter string, and the filtered list of choices.

    -
  • -
  • list:setFilter(filter[,pos])

    -

    Sets the new filter string, filters the list, and selects the item at -index pos in the unfiltered list if possible.

    -
  • -
  • list:canSubmit()

    -

    Checks if there are currently any choices in the filtered list.

    -
  • -
  • list:getSelected(), list:getContentWidth(), list:getContentHeight(), list:submit()

    -

    Same as with an ordinary list.

    -
  • -
-
-
-
-
-

Plugins

-

DFHack plugins may export native functions and events -to lua contexts. They are automatically imported by -mkmodule('plugins.<name>'); this means that a lua -module file is still necessary for require to read.

-

The following plugins have lua support.

-
-

burrows

-

Implements extended burrow manipulations.

-

Events:

-
    -
  • onBurrowRename.foo = function(burrow)

    -

    Emitted when a burrow might have been renamed either through -the game UI, or renameBurrow().

    -
  • -
  • onDigComplete.foo = function(job_type,pos,old_tiletype,new_tiletype,worker)

    -

    Emitted when a tile might have been dug out. Only tracked if the -auto-growing burrows feature is enabled.

    -
  • -
-

Native functions:

-
    -
  • renameBurrow(burrow,name)

    -

    Renames the burrow, emitting onBurrowRename and updating auto-grow state properly.

    -
  • -
  • findByName(burrow,name)

    -

    Finds a burrow by name, using the same rules as the plugin command line interface. -Namely, trailing '+' characters marking auto-grow burrows are ignored.

    -
  • -
  • copyUnits(target,source,enable)

    -

    Applies units from source burrow to target. The enable -parameter specifies if they are to be added or removed.

    -
  • -
  • copyTiles(target,source,enable)

    -

    Applies tiles from source burrow to target. The enable -parameter specifies if they are to be added or removed.

    -
  • -
  • setTilesByKeyword(target,keyword,enable)

    -

    Adds or removes tiles matching a predefined keyword. The keyword -set is the same as used by the command line.

    -
  • -
-

The lua module file also re-exports functions from dfhack.burrows.

-
-
-

sort

-

Does not export any native functions as of now. Instead, it -calls lua code to perform the actual ordering of list items.

-
-
-

Eventful

-

This plugin exports some events to lua thus allowing to run lua functions -on DF world events.

-
-

List of events

-
    -
  1. onReactionComplete(reaction,unit,input_items,input_reagents,output_items,call_native)

    -

    Auto activates if detects reactions starting with LUA_HOOK_. Is called when reaction finishes.

    -
  2. -
  3. onItemContaminateWound(item,unit,wound,number1,number2)

    -

    Is called when item tries to contaminate wound (e.g. stuck in).

    -
  4. -
  5. onProjItemCheckMovement(projectile)

    -

    Is called when projectile moves.

    -
  6. -
  7. onProjItemCheckImpact(projectile,somebool)

    -

    Is called when projectile hits something.

    -
  8. -
  9. onProjUnitCheckMovement(projectile)

    -

    Is called when projectile moves.

    -
  10. -
  11. onProjUnitCheckImpact(projectile,somebool)

    -

    Is called when projectile hits something.

    -
  12. -
  13. onWorkshopFillSidebarMenu(workshop,callnative)

    -

    Is called when viewing a workshop in 'q' mode, to populate reactions, useful for custom viewscreens for shops.

    -
  14. -
  15. postWorkshopFillSidebarMenu(workshop)

    -

    Is called after calling (or not) native fillSidebarMenu(). Useful for job button -tweaking (e.g. adding custom reactions)

    -
  16. -
-
-
-

Events from EventManager

-

These events are straight from EventManager module. Each of them first needs to be enabled. See functions for more info. If you register a listener before the game is loaded, be aware that no events will be triggered immediately after loading, so you might need to add another event listener for when the game first loads in some cases.

-
    -
  1. onBuildingCreatedDestroyed(building_id)

    -

    Gets called when building is created or destroyed.

    -
  2. -
  3. onConstructionCreatedDestroyed(building_id)

    -

    Gets called when construction is created or destroyed.

    -
  4. -
  5. onJobInitiated(job)

    -

    Gets called when job is issued.

    -
  6. -
  7. onJobCompleted(job)

    -

    Gets called when job is finished. The job that is passed to this function is a copy. Requires a frequency of 0 in order to distinguish between workshop jobs that were cancelled by the user and workshop jobs that completed successfully.

    -
  8. -
  9. onUnitDeath(unit_id)

    -

    Gets called on unit death.

    -
  10. -
  11. onItemCreated(item_id)

    -

    Gets called when item is created (except due to traders, migrants, invaders and spider webs).

    -
  12. -
  13. onSyndrome(unit_id,syndrome_index)

    -

    Gets called when new syndrome appears on a unit.

    -
  14. -
  15. onInvasion(invasion_id)

    -

    Gets called when new invasion happens.

    -
  16. -
  17. onInventoryChange(unit_id,item_id,old_equip,new_equip)

    -

    Gets called when someone picks up an item, puts one down, or changes the way they are holding it. If an item is picked up, old_equip will be null. If an item is dropped, new_equip will be null. If an item is re-equipped in a new way, then neither will be null. You absolutely must NOT alter either old_equip or new_equip or you might break other plugins.

    -
  18. -
  19. onReport(reportId)

    -

    Gets called when a report happens. This happens more often than you probably think, even if it doesn't show up in the announcements.

    -
  20. -
  21. onUnitAttack(attackerId, defenderId, woundId)

    -

    Called when a unit wounds another with a weapon. Is NOT called if blocked, dodged, deflected, or parried.

    -
  22. -
  23. onUnload()

    -

    A convenience event in case you don't want to register for every onStateChange event.

    -
  24. -
  25. onInteraction(attackVerb, defendVerb, attackerId, defenderId, attackReportId, defendReportId)

    -

    Called when a unit uses an interaction on another.

    -
  26. -
-
-
-

Functions

-
    -
  1. registerReaction(reaction_name,callback)

    -

    Simplified way of using onReactionComplete; the callback is function (same params as event).

    -
  2. -
  3. removeNative(shop_name)

    -

    Removes native choice list from the building.

    -
  4. -
  5. addReactionToShop(reaction_name,shop_name)

    -

    Add a custom reaction to the building.

    -
  6. -
  7. enableEvent(evType,frequency)

    -

    Enable event checking for EventManager events. For event types use eventType table. Note that different types of events require different frequencies to be effective. The frequency is how many ticks EventManager will wait before checking if that type of event has happened. If multiple scripts or plugins use the same event type, the smallest frequency is the one that is used, so you might get events triggered more often than the frequency you use here.

    -
  8. -
  9. registerSidebar(shop_name,callback)

    -

    Enable callback when sidebar for shop_name is drawn. Usefull for custom workshop views e.g. using gui.dwarfmode lib. Also accepts a class instead of function -as callback. Best used with gui.dwarfmode class WorkshopOverlay.

    -
  10. -
-
-
-

Examples

-

Spawn dragon breath on each item attempt to contaminate wound:

-
-b=require "plugins.eventful"
-b.onItemContaminateWound.one=function(item,unit,un_wound,x,y)
-    local flw=dfhack.maps.spawnFlow(unit.pos,6,0,0,50000)
-end
-
-

Reaction complete example:

-
-b=require "plugins.eventful"
-
-b.registerReaction("LUA_HOOK_LAY_BOMB",function(reaction,unit,in_items,in_reag,out_items,call_native)
-  local pos=copyall(unit.pos)
-  -- spawn dragonbreath after 100 ticks
-  dfhack.timeout(100,"ticks",function() dfhack.maps.spawnFlow(pos,6,0,0,50000) end)
-  --do not call real item creation code
-  call_native.value=false
-end)
-
-

Grenade example:

-
-b=require "plugins.eventful"
-b.onProjItemCheckImpact.one=function(projectile)
-  -- you can check if projectile.item e.g. has correct material
-  dfhack.maps.spawnFlow(projectile.cur_pos,6,0,0,50000)
-end
-
-

Integrated tannery:

-
-b=require "plugins.eventful"
-b.addReactionToShop("TAN_A_HIDE","LEATHERWORKS")
-
-
-
-
-

Building-hacks

-

This plugin overwrites some methods in workshop df class so that mechanical workshops are possible. Although -plugin export a function it's recommended to use lua decorated function.

-
-

Functions

-
-
registerBuilding(table) where table must contain name, as a workshop raw name, the rest are optional:
-
    -
  1. name -- custom workshop id e.g. SOAPMAKER
  2. -
  3. fix_impassible -- if true make impassible tiles impassible to liquids too
  4. -
  5. consume -- how much machine power is needed to work. Disables reactions if not supplied enough and needs_power=1
  6. -
  7. produce -- how much machine power is produced.
  8. -
  9. needs_power -- if produced in network < consumed stop working, default true
  10. -
  11. gears -- a table or {x=?,y=?} of connection points for machines
  12. -
  13. action -- a table of number (how much ticks to skip) and a function which gets called on shop update
  14. -
  15. animate -- a table of frames which can be a table of:
      -
    1. tables of 4 numbers {tile,fore,back,bright} OR
    2. -
    3. empty table (tile not modified) OR
    4. -
    5. {x=<number> y=<number> + 4 numbers like in first case}, this generates full frame useful for animations that change little (1-2 tiles)
    6. -
    -
  16. -
  17. canBeRoomSubset -- a flag if this building can be counted in room. 1 means it can, 0 means it can't and -1 default building behaviour
  18. -
-
-
Animate table also might contain:
-
    -
  1. frameLenght -- how many ticks does one frame take OR
  2. -
  3. isMechanical -- a bool that says to try to match to mechanical system (i.e. how gears are turning)
  4. -
-
-
-

getPower(building) returns two number - produced and consumed power if building can be modified and returns nothing otherwise

-

setPower(building,produced,consumed) sets current productiona and consumption for a building.

-
-
-

Examples

-

Simple mechanical workshop:

-
-require('plugins.building-hacks').registerBuilding{name="BONE_GRINDER",
-  consume=15,
-  gears={x=0,y=0}, --connection point
-  animate={
-    isMechanical=true, --animate the same connection point as vanilla gear
-    frames={
-    {{x=0,y=0,42,7,0,0}}, --first frame, 1 changed tile
-    {{x=0,y=0,15,7,0,0}} -- second frame, same
-    }
-  }
-
-
-
-
-
-

Scripts

-

Any files with the .lua extension placed into hack/scripts/* -are automatically used by the DFHack core as commands. The -matching command name consists of the name of the file without -the extension. First DFHack searches for the script in the save folder/raw/scripts folder. If it is not found there, it searches in the DF/raw/scripts folder. If it is not there, it searches in DF/hack/scripts. If it is not there, it gives up.

-

If the first line of the script is a one-line comment, it is -used by the built-in ls and help commands.

-

NOTE: Scripts placed in subdirectories still can be accessed, but -do not clutter the ls command list; thus it is preferred -for obscure developer-oriented scripts and scripts used by tools. -When calling such scripts, always use '/' as the separator for -directories, e.g. devel/lua-example.

-

Scripts are re-read from disk if they have changed since the last time they were read. -Global variable values persist in memory between calls, unless the file has changed. -Every script gets its own separate environment for global -variables.

-

Arguments are passed in to the scripts via the ... built-in -quasi-variable; when the script is called by the DFHack core, -they are all guaranteed to be non-nil strings.

-

DFHack core invokes the scripts in the core context (see above); -however it is possible to call them from any lua code (including -from other scripts) in any context, via the same function the core uses:

- -

Note that this function lets errors propagate to the caller.

- -
-

Save init script

-

If a save directory contains a file called raw/init.lua, it is -automatically loaded and executed every time the save is loaded. -The same applies to any files called raw/init.d/*.lua. Every -such script can define the following functions to be called by dfhack:

-
    -
  • function onStateChange(op) ... end

    -

    Automatically called from the regular onStateChange event as long -as the save is still loaded. This avoids the need to install a hook -into the global dfhack.onStateChange table, with associated -cleanup concerns.

    -
  • -
  • function onUnload() ... end

    -

    Called when the save containing the script is unloaded. This function -should clean up any global hooks installed by the script. Note that -when this is called, the world is already completely unloaded.

    -
  • -
-

Within the init script, the path to the save directory is available as SAVE_PATH.

-
-
-
- - diff --git a/Readme.html b/Readme.html deleted file mode 100644 index 9df7c229d..000000000 --- a/Readme.html +++ /dev/null @@ -1,4043 +0,0 @@ - - - - - - -DFHack Readme - - - -
-

DFHack Readme

- -
-

Introduction

-

DFHack is a Dwarf Fortress memory access library, distributed with scripts -and plugins implementing a wide variety of useful functions and tools.

-

For users, it provides a significant suite of bugfixes and interface -enhancements by default, and more can be enabled. There are also many tools -(such as workflow or autodump) which can make life easier. You can -even add third-party scripts and plugins to do almost anything!

-

For modders, DFHack makes many things possible. Custom reactions, new -interactions, magic creature abilities, and more can be set through scripts -and custom raws. Non-standard DFHack scripts and inits can be stored in the -raw directory, making raws or saves fully self-contained for distribution - -or for coexistence in a single DF install, even with incompatible components.

-

For developers, DFHack unites the various ways tools access DF memory and -allows easier development of new tools. As an open-source project under -various copyleft licences, contributions are welcome.

-
-

Contents

- -
-
-
-

Getting DFHack

-

The project is currently hosted at http://www.github.com/

-

Recent releases are available in source and binary formats on the releases -page, while the binaries for releases 0.40.15-r1 to 0.34.11-r4 are on DFFD. -Even older versions are available here.

-

All new releases are announced in the bay12 forums thread, which is also a -good place for discussion and questions.

-
-
-

Compatibility

-

DFHack is available for Windows (XP or later), Linux (any modern distribution), -or OS X (10.6.8 to 10.9).

-

Most releases only support the version of DF mentioned in their title - for -example, DFHack 0.40.24-r2 only supports DF 0.40.24 - but some releases -support earlier DF versions as well. Wherever possible, use the latest version -built for the target version of DF.

-

On Windows, DFHack is compatible with the SDL version of DF, but not the legacy version.

-

It is also possible to use the Windows DFHack with Wine under Linux and OS X.

-
-
-

Installation/Removal

-

Installing DFhack involves copying files into your DF folder. -Copy the files from a release archive so that:

- -

Uninstalling is basically the same, in reverse:

- -

The stonesense plugin might require some additional libraries on Linux.

-

If any of the plugins or dfhack itself refuses to load, check the stderr.log -file created in your DF folder.

-
-

Getting started

-

If DFHack is installed correctly, it will automatically pop up a console -window once DF is started as usual on windows. Linux and Mac OS X require -running the dfhack script from the terminal, and will use that terminal for -the console.

-

NOTE: The dfhack-run executable is there for calling DFHack commands in -an already running DF+DFHack instance from external OS scripts and programs, -and is not the way how you use DFHack normally.

-

DFHack has a lot of features, which can be accessed by typing commands in the -console, or by mapping them to keyboard shortcuts. Most of the newer and more -user-friendly tools are designed to be at least partially used via the latter -way.

-

In order to set keybindings, you have to create a text configuration file -called dfhack.init; the installation comes with an example version called -dfhack.init-example, which is fully functional, covers all of the recent -features and can be simply renamed to dfhack.init. You are encouraged to look -through it to learn which features it makes available under which key combinations.

-

For more information, refer to the rest of this document.

-
-
-
-

Using DFHack

-

DFHack basically extends what DF can do with something similar to the drop-down -console found in Quake engine games. On Windows, this is a separate command line -window. On linux, the terminal used to launch the dfhack script is taken over -(so, make sure you start from a terminal). Basic interaction with dfhack -involves entering commands into the console. For some basic instructions, -use the 'help' command. To list all possible commands, use the 'ls' command. -Many commands have their own help or detailed description. You can use -'command help' or 'command ?' to show that.

-

The command line has some nice line editing capabilities, including history -that's preserved between different runs of DF (use up/down keys to go through -the history).

-

The second way to interact with DFHack is to bind the available commands -to in-game hotkeys. The old way to do this is via the hotkey/zoom menu (normally -opened with the 'h' key). Binding the commands is done by assigning a command as -a hotkey name (with 'n').

-

A new and more flexible way is the keybinding command in the dfhack console. -However, bindings created this way are not automatically remembered between runs -of the game, so it becomes necessary to use the dfhack.init file to ensure that -they are re-created every time it is loaded.

-

Interactive commands like 'liquids' cannot be used as hotkeys.

-

Most of the commands come from plugins. Those reside in 'hack/plugins/'.

-
-

Patched binaries

-

On linux and OSX, users of patched binaries may have to find the relevant -section in symbols.xml, and add a new line with the checksum of their -executable:

-
-<md5-hash value='????????????????????????????????'/>
-
-

In order to find the correct value of the hash, look into stderr.log; -DFHack prints an error there if it does not recognize the hash.

-

DFHack includes a small stand-alone utility for applying and removing -binary patches from the game executable. Use it from the regular operating -system console:

-
-
binpatch check "Dwarf Fortress.exe" patch.dif
-
Checks and prints if the patch is currently applied.
-
binpatch apply "Dwarf Fortress.exe" patch.dif
-
Applies the patch, unless it is already applied or in conflict.
-
binpatch remove "Dwarf Fortress.exe" patch.dif
-
Removes the patch, unless it is already removed.
-
-

The patches are expected to be encoded in text format used by IDA.

-
-

Live patching

-

As an alternative, you can use the binpatch dfhack command to apply/remove -patches live in memory during a DF session.

-

In this case, updating symbols.xml is not necessary.

-
-
-
-
-

Something doesn't work, help!

-

First, don't panic :)

-

Second, dfhack keeps a few log files in DF's folder (stderr.log and -stdout.log). Looking at these might help you solve the problem. -If it doesn't, you can ask for help in the forum thread or on IRC.

-

If you found a bug, you can report it in the Bay12 DFHack thread, the issues -tracker on github, or visit the #dfhack IRC channel on freenode.

-
-
-

The init file

-

If your DF folder contains a file named dfhack.init, its contents will be -run every time you start DF. This allows keybindings and other settings to -persist across runs. An example file is provided as dfhack.init-example - -you can tweak it and rename to dfhack.init if you want to use this -functionality. If only the example init file is found, will be used and a -warning will be shown.

-

When a savegame is loaded, an onLoad.init file in its raw folder is run, -as a save-portable alternative to dfhack.init. It is recommended that -modders use this to improve mobility of save games and compatibility of mods.

-
-

Setting keybindings

-

To set keybindings, use the built-in keybinding command. Like any other -command it can be used at any time from the console, but it is also meaningful -in the DFHack init file.

-

Currently it supports any combination of Ctrl/Alt/Shift with F1-F9, or A-Z.

-

Possible ways to call the command:

-
-
keybinding list <key>
-
List bindings active for the key combination.
-
keybinding clear <key> <key>...
-
Remove bindings for the specified keys.
-
keybinding add <key> "cmdline" "cmdline"...
-
Add bindings for the specified key.
-
keybinding set <key> "cmdline" "cmdline"...
-
Clear, and then add bindings for the specified key.
-
-

The <key> parameter above has the following case-sensitive syntax:

-
-[Ctrl-][Alt-][Shift-]KEY[@context]
-
-

where the KEY part can be F1-F9 or A-Z, and [] denote optional parts.

-

When multiple commands are bound to the same key combination, DFHack selects -the first applicable one. Later 'add' commands, and earlier entries within one -'add' command have priority. Commands that are not specifically intended for use -as a hotkey are always considered applicable.

-

The context part in the key specifier above can be used to explicitly restrict -the UI state where the binding would be applicable. If called without parameters, -the keybinding command among other things prints the current context string. -Only bindings with a context tag that either matches the current context fully, -or is a prefix ending at a '/' boundary would be considered for execution, i.e. -for context foo/bar/baz, possible matches are any of @foo/bar/baz, @foo/bar, -@foo or none.

-
-
-

Enabling plugins

-

Many plugins can be in a distinct enabled or disabled state. Some of -them activate and deactivate automatically depending on the contents -of the world raws. Others store their state in world data. However a -number of them have to be enabled globally, and the init file is the -right place to do it.

-

Most of such plugins support the built-in enable and disable -commands. Calling them at any time without arguments prints a list -of enabled and disabled plugins, and shows whether that can be changed -through the same commands.

-

To enable or disable plugins that support this, use their names as -arguments for the command:

-
-enable manipulator search
-
-
-
-
-

Commands

-

DFHack command syntax consists of a command name, followed by arguments separated -by whitespace. To include whitespace in an argument, quote it in double quotes. -To include a double quote character, use \" inside double quotes.

-

If the first non-whitespace character of a line is #, the line is treated -as a comment, i.e. a silent no-op command.

-

When reading commands from dfhack.init or with the script command, if the final character on a line is a backslash then the next uncommented line is considered a continuation of that line, with the backslash deleted. -Commented lines are skipped, so it is possible to comment out parts of a command with the # character.

-

If the first non-whitespace character is :, the command is parsed in a special -alternative mode: first, non-whitespace characters immediately following the : -are used as the command name; the remaining part of the line, starting with the first -non-whitespace character after the command name, is used verbatim as the first argument. -The following two command lines are exactly equivalent:

-
-:foo a b "c d" e f
-foo "a b \"c d\" e f"
-
-

This is intended for commands like rb_eval that evaluate script language statements.

-

Almost all the commands support using the 'help <command-name>' built-in command -to retrieve further help without having to look at this document. Alternatively, -some accept a 'help'/'?' option on their command line.

-
-

Game progress

-
-

die

-

Instantly kills DF without saving.

-
-
-

forcepause

-

Forces DF to pause. This is useful when your FPS drops below 1 and you lose -control of the game.

-
    -
  • Activate with 'forcepause 1'
  • -
  • Deactivate with 'forcepause 0'
  • -
-
-
-

nopause

-

Disables pausing (both manual and automatic) with the exception of pause forced -by 'reveal hell'. This is nice for digging under rivers.

-
-
-

fastdwarf

-

Controls speedydwarf and teledwarf. Speedydwarf makes dwarves move quickly and perform tasks quickly. Teledwarf makes dwarves move instantaneously, but do jobs at the same speed.

-
    -
  • 'fastdwarf 0 0' disables both
  • -
  • 'fastdwarf 0 1' disables speedydwarf and enables teledwarf
  • -
  • 'fastdwarf 1 0' enables speedydwarf and disables teledwarf
  • -
  • 'fastdwarf 1 1' enables both
  • -
  • 'fastdwarf 0' disables both
  • -
  • 'fastdwarf 1' enables speedydwarf and disables teledwarf
  • -
  • 'fastdwarf 2 ...' sets a native debug flag in the game memory -that implements an even more aggressive version of speedydwarf.
  • -
-
-
-
-

Game interface

-
-

follow

-

Makes the game view follow the currently highlighted unit after you exit from -current menu/cursor mode. Handy for watching dwarves running around. Deactivated -by moving the view manually.

-
-
-

tidlers

-

Toggle between all possible positions where the idlers count can be placed.

-
-
-

twaterlvl

-

Toggle between displaying/not displaying liquid depth as numbers.

-
-
-

stockpile settings management

-

Save and load stockpile settings. See the gui/stockpiles for an in-game GUI to -this plugin.

-
-

copystock

-

Copies the parameters of the currently highlighted stockpile to the custom -stockpile settings and switches to custom stockpile placement mode, effectively -allowing you to copy/paste stockpiles easily.

-
-
-

savestock

-

Saves the currently highlighted stockpile's settings to a file in your Dwarf -Fortress folder. This file can be used to copy settings between game saves or -players.

-

example:

-
-savestock food_settings.dfstock
-
-
-
-

loadstock

-

Loads a saved stockpile settings file and applies it to the currently selected -stockpile.

-

example:

-
-loadstock food_settings.dfstock
-
-

To use savestock and loadstock, use the 'q' command to highlight a stockpile. -Then run savestock giving it a descriptive filename. Then, in a different (or -same!) gameworld, you can highlight any stockpile with 'q' then execute the -'loadstock' command passing it the name of that file. The settings will be -applied to that stockpile.

-

Notes: It saves and loads files relative to the DF folder, so put your files -there or in a subfolder for easy access. Filenames should not have spaces.

-

Limitations: Generated materials, divine metals, etc are not saved as they -are different in every world.

-
-
-
-

rename

-

Allows renaming various things.

-

Options:

-
-
rename squad <index> "name"
-
Rename squad by index to 'name'.
-
rename hotkey <index> \"name\"
-
Rename hotkey by index. This allows assigning -longer commands to the DF hotkeys.
-
rename unit "nickname"
-
Rename a unit/creature highlighted in the DF user interface.
-
rename unit-profession "custom profession"
-
Change proffession name of the highlighted unit/creature.
-
rename building "name"
-
Set a custom name for the selected building. -The building must be one of stockpile, workshop, furnace, trap, -siege engine or an activity zone.
-
-
-
-

command-prompt

-

A one line command prompt in df. Same as entering command into dfhack console. Best -used as a keybinding. Can be called with optional "entry" that will start prompt with -that pre-filled.

-images/command-prompt.png -
-
-

rendermax

-

A collection of renderer replacing/enhancing filters. For better effect try changing the -black color in palette to non totally black. For more info see the Bay12 forum thread.

-

Options:

-
-
rendermax trippy
-
Randomizes the color of each tiles. Used for fun, or testing.
-
rendermax light
-
Enable lighting engine.
-
rendermax light reload
-
Reload the settings file.
-
rendermax light sun <x>|cycle
-
Set time to <x> (in hours) or set it to df time cycle.
-
rendermax occlusionON|occlusionOFF
-
Show debug occlusion info.
-
rendermax disable
-
Disable any filter that is enabled.
-
-

An image showing lava and dragon breath. Not pictured here: sunlight, shining items/plants, -materials that color the light etc...

-images/rendermax.png -
-
-
-

Adventure mode

-
-

adv-bodyswap

-

This allows taking control over your followers and other creatures in adventure -mode. For example, you can make them pick up new arms and armor and equip them -properly.

-

Usage:

-
    -
  • When viewing unit details, body-swaps into that unit.
  • -
  • In the main adventure mode screen, reverts transient swap.
  • -
-
-
-

advtools

-

A package of different adventure mode tools.

-

Usage:

-
-
list-equipped [all]
-
List armor and weapons equipped by your companions. -If all is specified, also lists non-metal clothing.
-
metal-detector [all-types] [non-trader]
-
Reveal metal armor and weapons in -shops. The options disable the checks -on item type and being in shop.
-
-
-
-
-

Map modification

-
-

3dveins

-

Removes all existing veins from the map and generates new ones using -3D Perlin noise, in order to produce a layout that smoothly flows between -Z levels. The vein distribution is based on the world seed, so running -the command for the second time should produce no change. It is best to -run it just once immediately after embark.

-

This command is intended as only a cosmetic change, so it takes -care to exactly preserve the mineral counts reported by prospect all. -The amounts of different layer stones may slightly change in some cases -if vein mass shifts between Z layers.

-

Note that there is no undo option other than restoring from backup.

-
-
-

changelayer

-

Changes material of the geology layer under cursor to the specified inorganic -RAW material. Can have impact on all surrounding regions, not only your embark! -By default changing stone to soil and vice versa is not allowed. By default -changes only the layer at the cursor position. Note that one layer can stretch -across lots of z levels. By default changes only the geology which is linked -to the biome under the cursor. That geology might be linked to other biomes -as well, though. Mineral veins and gem clusters will stay on the map. Use -'changevein' for them.

-

tl;dr: You will end up with changing quite big areas in one go, especially if -you use it in lower z levels. Use with care.

-

Options:

- --- - - - - - - - - - - - -
all_biomes:Change selected layer for all biomes on your map. -Result may be undesirable since the same layer can AND WILL -be on different z-levels for different biomes. Use the tool -'probe' to get an idea how layers and biomes are distributed -on your map.
all_layers:Change all layers on your map (only for the selected biome -unless 'all_biomes' is added). -Candy mountain, anyone? Will make your map quite boring, -but tidy.
force:Allow changing stone to soil and vice versa. !!THIS CAN HAVE -WEIRD EFFECTS, USE WITH CARE!! -Note that soil will not be magically replaced with stone. -You will, however, get a stone floor after digging so it -will allow the floor to be engraved. -Note that stone will not be magically replaced with soil. -You will, however, get a soil floor after digging so it -could be helpful for creating farm plots on maps with no -soil.
verbose:Give some details about what is being changed.
trouble:Give some advice about known problems.
-

Examples:

-
-
changelayer GRANITE
-
Convert layer at cursor position into granite.
-
changelayer SILTY_CLAY force
-
Convert layer at cursor position into clay even if it's stone.
-
changelayer MARBLE all_biomes all_layers
-
Convert all layers of all biomes which are not soil into marble.
-
-
-

Note

-
    -
  • If you use changelayer and nothing happens, try to pause/unpause the game -for a while and try to move the cursor to another tile. Then try again. -If that doesn't help try temporarily changing some other layer, undo your -changes and try again for the layer you want to change. Saving -and reloading your map might also help.
  • -
  • You should be fine if you only change single layers without the use -of 'force'. Still it's advisable to save your game before messing with -the map.
  • -
  • When you force changelayer to convert soil to stone you might experience -weird stuff (flashing tiles, tiles changed all over place etc). -Try reverting the changes manually or even better use an older savegame. -You did save your game, right?
  • -
-
-
-
-

changevein

-

Changes material of the vein under cursor to the specified inorganic RAW -material. Only affects tiles within the current 16x16 block - for veins and -large clusters, you will need to use this command multiple times.

-

Example:

-
-
changevein NATIVE_PLATINUM
-
Convert vein at cursor position into platinum ore.
-
-
-
-

changeitem

-

Allows changing item material and base quality. By default the item currently -selected in the UI will be changed (you can select items in the 'k' list -or inside containers/inventory). By default change is only allowed if materials -is of the same subtype (for example wood<->wood, stone<->stone etc). But since -some transformations work pretty well and may be desired you can override this -with 'force'. Note that some attributes will not be touched, possibly resulting -in weirdness. To get an idea how the RAW id should look like, check some items -with 'info'. Using 'force' might create items which are not touched by -crafters/haulers.

-

Options:

- --- - - - - - - - - - - - -
info:Don't change anything, print some info instead.
here:Change all items at the cursor position. Requires in-game cursor.
material, m:Change material. Must be followed by valid material RAW id.
quality, q:Change base quality. Must be followed by number (0-5).
force:Ignore subtypes, force change to new material.
-

Examples:

-
-
changeitem m INORGANIC:GRANITE here
-
Change material of all items under the cursor to granite.
-
changeitem q 5
-
Change currently selected item to masterpiece quality.
-
-
-
-

colonies

-

Allows listing all the vermin colonies on the map and optionally turning them into honey bee colonies.

-

Options:

- --- - - - -
bees:turn colonies into honey bee colonies
-
-
-

createitem

-

Allows creating new items of arbitrary types and made of arbitrary materials. -By default, items created are spawned at the feet of the selected unit.

-

Specify the item and material information as you would indicate them in custom reaction raws, with the following differences:

-
    -
  • Separate the item and material with a space rather than a colon
  • -
  • If the item has no subtype, omit the :NONE
  • -
  • If the item is REMAINS, FISH, FISH_RAW, VERMIN, PET, or EGG, specify a CREATURE:CASTE pair instead of a material token.
  • -
-

Corpses, body parts, and prepared meals cannot be created using this tool.

-

Examples:

-
-
createitem GLOVES:ITEM_GLOVES_GAUNTLETS INORGANIC:STEEL 2
-
Create 2 pairs of steel gauntlets.
-
createitem WOOD PLANT_MAT:TOWER_CAP:WOOD
-
Create tower-cap logs.
-
createitem FISH FISH_SHAD:MALE 5
-
Create a stack of 5 cleaned shad, ready to eat.
-
-

To change where new items are placed, first run the command with a destination type while an appropriate destination is selected.

-

Options:

- --- - - - - - - - -
floor:Subsequent items will be placed on the floor beneath the selected unit's feet.
item:Subsequent items will be stored inside the currently selected item.
building:Subsequent items will become part of the currently selected building. Best used for loading traps; do not use with workshops, or you will need to deconstruct the building to use the item.
-
-
-

deramp

-

Removes all ramps designated for removal from the map. This is useful for replicating the old channel digging designation. -It also removes any and all 'down ramps' that can remain after a cave-in (you don't have to designate anything for that to happen).

-
-
-

feature

-

Enables management of map features.

-
    -
  • Discovering a magma feature (magma pool, volcano, magma sea, or curious -underground structure) permits magma workshops and furnaces to be built.
  • -
  • Discovering a cavern layer causes plants (trees, shrubs, and grass) from -that cavern to grow within your fortress.
  • -
-

Options:

- --- - - - - - - - -
list:Lists all map features in your current embark by index.
show X:Marks the selected map feature as discovered.
hide X:Marks the selected map feature as undiscovered.
-
-
-

infiniteSky

-

Automatically allocates new z-levels of sky at the top of the map as you build up, or on request allocates many levels all at once.

-

Examples:

-
-
infiniteSky n
-
Raise the sky by n z-levels.
-
infiniteSky enable/disable
-
Enables/disables monitoring of constructions. If you build anything in the second to highest z-level, it will allocate one more sky level. This is so you can continue to build stairs upward.
-
-

Bugs have been reported with this version of the plugin, so be careful. It is possible that new z-levels will suddenly disappear and possibly cause cave-ins. Saving and loading after creating new z-levels should fix the problem.

-
-
-

liquids

-

Allows adding magma, water and obsidian to the game. It replaces the normal -dfhack command line and can't be used from a hotkey. Settings will be remembered -as long as dfhack runs. Intended for use in combination with the command -liquids-here (which can be bound to a hotkey).

-

For more information, refer to the command's internal help.

-
-

Note

-

Spawning and deleting liquids can F up pathing data and -temperatures (creating heat traps). You've been warned.

-
-
-
-

liquids-here

-

Run the liquid spawner with the current/last settings made in liquids (if no -settings in liquids were made it paints a point of 7/7 magma by default).

-

Intended to be used as keybinding. Requires an active in-game cursor.

-
-
-

tiletypes

-

Can be used for painting map tiles and is an interactive command, much like -liquids.

-

The tool works with two set of options and a brush. The brush determines which -tiles will be processed. First set of options is the filter, which can exclude -some of the tiles from the brush by looking at the tile properties. The second -set of options is the paint - this determines how the selected tiles are -changed.

-

Both paint and filter can have many different properties including things like -general shape (WALL, FLOOR, etc.), general material (SOIL, STONE, MINERAL, -etc.), state of 'designated', 'hidden' and 'light' flags.

-

The properties of filter and paint can be partially defined. This means that -you can for example do something like this:

-
-filter material STONE
-filter shape FORTIFICATION
-paint shape FLOOR
-
-

This will turn all stone fortifications into floors, preserving the material.

-

Or this:

-
-filter shape FLOOR
-filter material MINERAL
-paint shape WALL
-
-

Turning mineral vein floors back into walls.

-

The tool also allows tweaking some tile flags:

-

Or this:

-
-paint hidden 1
-paint hidden 0
-
-

This will hide previously revealed tiles (or show hidden with the 0 option).

-

More recently, the tool supports changing the base material of the tile to -an arbitrary stone from the raws, by creating new veins as required. Note -that this mode paints under ice and constructions, instead of overwriting -them. To enable, use:

-
-paint stone MICROCLINE
-
-

This mode is incompatible with the regular material setting, so changing -it cancels the specific stone selection:

-
-paint material ANY
-
-

Since different vein types have different drop rates, it is possible to choose -which one to use in painting:

-
-paint veintype CLUSTER_SMALL
-
-

When the chosen type is CLUSTER (the default), the tool may automatically -choose to use layer stone or lava stone instead of veins if its material matches -the desired one.

-

Any paint or filter option (or the entire paint or filter) can be disabled entirely by using the ANY keyword:

-
-paint hidden ANY
-paint shape ANY
-filter material any
-filter shape any
-filter any
-
-

You can use several different brushes for painting tiles:

-
    -
  • Point. (point)
  • -
  • Rectangular range. (range)
  • -
  • A column ranging from current cursor to the first solid tile above. (column)
  • -
  • DF map block - 16x16 tiles, in a regular grid. (block)
  • -
-

Example:

-
-range 10 10 1
-
-

This will change the brush to a rectangle spanning 10x10 tiles on one z-level. -The range starts at the position of the cursor and goes to the east, south and -up.

-

For more details, see the 'help' command while using this.

-
-
-

tiletypes-commands

-

Runs tiletypes commands, separated by ;. This makes it possible to change -tiletypes modes from a hotkey.

-
-
-

tiletypes-here

-

Apply the current tiletypes options at the in-game cursor position, including -the brush. Can be used from a hotkey.

-
-
-

tiletypes-here-point

-

Apply the current tiletypes options at the in-game cursor position to a single -tile. Can be used from a hotkey.

-
-
-

tubefill

-

Fills all the adamantine veins again. Veins that were hollow will be left -alone.

-

Options:

- --- - - - -
hollow:fill in naturally hollow veins too
-

Beware that filling in hollow veins will trigger a demon invasion on top of -your miner when you dig into the region that used to be hollow.

-
-
-

plant

-

A tool for creating shrubs, growing, or getting rid of them.

-

Subcommands:

- --- - - - - - - - - - -
create:Create a new shrub/sapling.
grow:Make saplings grow into trees.
extirpate:Kills trees and shrubs, turning them into ashes instantly.
immolate:Similar to extirpate, but sets the plants on fire instead. The fires can and will spread ;)
-

create creates a new sapling under the cursor. Takes a raw ID as -argument (e.g. TOWER_CAP). The cursor must be located on a dirt or grass -floor tile.

-

grow works on the sapling under the cursor, and turns it into a tree. -Works on all shrubs of the map if the cursor is hidden.

-

extirpate and immolate work only on the plant under the cursor.

-

For mass effects, use one of the additional options:

- --- - - - - - - - -
shrubs:affect all shrubs on the map
trees:affect all trees on the map
all:affect every plant!
-
-
-

regrass

-

Regrows grass. Not much to it ;)

-
-
-

weather

-

Prints the current weather map by default.

-

Also lets you change the current weather to 'clear sky', 'rainy' or 'snowing'.

-

Options:

- --- - - - - - - - -
snow:make it snow everywhere.
rain:make it rain.
clear:clear the sky.
-
-
-
-

Map inspection

-
-

cursecheck

-

Checks a single map tile or the whole map/world for cursed creatures (ghosts, -vampires, necromancers, werebeasts, zombies).

-

With an active in-game cursor only the selected tile will be observed. -Without a cursor the whole map will be checked.

-

By default cursed creatures will be only counted in case you just want to find -out if you have any of them running around in your fort. Dead and passive -creatures (ghosts who were put to rest, killed vampires, ...) are ignored. -Undead skeletons, corpses, bodyparts and the like are all thrown into the curse -category "zombie". Anonymous zombies and resurrected body parts will show -as "unnamed creature".

-

Options:

- --- - - - - - - - - - -
detail:Print full name, date of birth, date of curse and some status -info (some vampires might use fake identities in-game, though).
nick:Set the type of curse as nickname (does not always show up -in-game, some vamps don't like nicknames).
all:Include dead and passive cursed creatures (can result in a quite -long list after having FUN with necromancers).
verbose:Print all curse tags (if you really want to know it all).
-

Examples:

-
-
cursecheck detail all
-
Give detailed info about all cursed creatures including deceased ones (no -in-game cursor).
-
cursecheck nick
-
Give a nickname all living/active cursed creatures on the map(no in-game -cursor).
-
-
-

Note

-
    -
  • If you do a full search (with the option "all") former ghosts will show up -with the cursetype "unknown" because their ghostly flag is not set -anymore. But if you happen to find a living/active creature with cursetype -"unknown" please report that in the dfhack thread on the modding forum or -per irc. This is likely to happen with mods which introduce new types -of curses, for example.
  • -
-
-
-
-

flows

-

A tool for checking how many tiles contain flowing liquids. If you suspect that -your magma sea leaks into HFS, you can use this tool to be sure without -revealing the map.

-
-
-

probe

-

Can be used to determine tile properties like temperature.

-
-
-

prospect

-

Prints a big list of all the present minerals and plants. By default, only -the visible part of the map is scanned.

-

Options:

- --- - - - - - - - -
all:Scan the whole map, as if it was revealed.
value:Show material value in the output. Most useful for gems.
hell:Show the Z range of HFS tubes. Implies 'all'.
-
-

Pre-embark estimate

-

If prospect is called during the embark selection screen, it displays an estimate of -layer stone availability.

-
-

Note

-

The results of pre-embark prospect are an estimate, and can at best be expected -to be somewhere within +/- 30% of the true amount; sometimes it does a lot worse. -Especially, it is not clear how to precisely compute how many soil layers there -will be in a given embark tile, so it can report a whole extra layer, or omit one -that is actually present.

-
-

Options:

- --- - - - -
all:Also estimate vein mineral amounts.
-
-
-
-

reveal

-

This reveals the map. By default, HFS will remain hidden so that the demons -don't spawn. You can use 'reveal hell' to reveal everything. With hell revealed, -you won't be able to unpause until you hide the map again. If you really want -to unpause with hell revealed, use 'reveal demons'.

-

Reveal also works in adventure mode, but any of its effects are negated once -you move. When you use it this way, you don't need to run 'unreveal'.

-
-
-

unreveal

-

Reverts the effects of 'reveal'.

-
-
-

revtoggle

-

Switches between 'reveal' and 'unreveal'.

-
-
-

revflood

-

This command will hide the whole map and then reveal all the tiles that have -a path to the in-game cursor.

-
-
-

revforget

-

When you use reveal, it saves information about what was/wasn't visible before -revealing everything. Unreveal uses this information to hide things again. -This command throws away the information. For example, use in cases where -you abandoned with the fort revealed and no longer want the data.

-
-
-

showmood

-

Shows all items needed for the currently active strange mood.

-
-
-
-

Designations

-
-

burrow

-

Miscellaneous burrow control. Allows manipulating burrows and automated burrow -expansion while digging.

-

Options:

-
-
enable feature ...
-
Enable features of the plugin.
-
disable feature ...
-
Disable features of the plugin.
-
clear-unit burrow burrow ...
-
Remove all units from the burrows.
-
clear-tiles burrow burrow ...
-
Remove all tiles from the burrows.
-
set-units target-burrow src-burrow ...
-
Clear target, and adds units from source burrows.
-
add-units target-burrow src-burrow ...
-
Add units from the source burrows to the target.
-
remove-units target-burrow src-burrow ...
-
Remove units in source burrows from the target.
-
set-tiles target-burrow src-burrow ...
-
Clear target and adds tiles from the source burrows.
-
add-tiles target-burrow src-burrow ...
-
Add tiles from the source burrows to the target.
-
remove-tiles target-burrow src-burrow ...
-

Remove tiles in source burrows from the target.

-

For these three options, in place of a source burrow it is -possible to use one of the following keywords: ABOVE_GROUND, -SUBTERRANEAN, INSIDE, OUTSIDE, LIGHT, DARK, HIDDEN, REVEALED

-
-
-

Features:

- --- - - - -
auto-grow:When a wall inside a burrow with a name ending in '+' is dug -out, the burrow is extended to newly-revealed adjacent walls. -This final '+' may be omitted in burrow name args of commands above. -Digging 1-wide corridors with the miner inside the burrow is SLOW.
-
-
-

digv

-

Designates a whole vein for digging. Requires an active in-game cursor placed -over a vein tile. With the 'x' option, it will traverse z-levels (putting stairs -between the same-material tiles).

-
-
-

digvx

-

A permanent alias for 'digv x'.

-
-
-

digl

-

Designates layer stone for digging. Requires an active in-game cursor placed -over a layer stone tile. With the 'x' option, it will traverse z-levels -(putting stairs between the same-material tiles). With the 'undo' option it -will remove the dig designation instead (if you realize that digging out a 50 -z-level deep layer was not such a good idea after all).

-
-
-

diglx

-

A permanent alias for 'digl x'.

-
-
-

digexp

-

This command is for exploratory mining.

-

There are two variables that can be set: pattern and filter.

-

Patterns:

- --- - - - - - - - - - - - - - -
diag5:diagonals separated by 5 tiles
diag5r:diag5 rotated 90 degrees
ladder:A 'ladder' pattern
ladderr:ladder rotated 90 degrees
clear:Just remove all dig designations
cross:A cross, exactly in the middle of the map.
-

Filters:

- --- - - - - - - - -
all:designate whole z-level
hidden:designate only hidden tiles of z-level (default)
designated:Take current designation and apply pattern to it.
-

After you have a pattern set, you can use 'expdig' to apply it again.

-

Examples:

-
-
expdig diag5 hidden
-
Designate the diagonal 5 patter over all hidden tiles
-
expdig
-
Apply last used pattern and filter
-
expdig ladder designated
-
Take current designations and replace them with the ladder pattern
-
-
-
-

digcircle

-

A command for easy designation of filled and hollow circles. -It has several types of options.

-

Shape:

- --- - - - - - - - -
hollow:Set the circle to hollow (default)
filled:Set the circle to filled
#:Diameter in tiles (default = 0, does nothing)
-

Action:

- --- - - - - - - - -
set:Set designation (default)
unset:Unset current designation
invert:Invert designations already present
-

Designation types:

- --- - - - - - - - - - - - - - -
dig:Normal digging designation (default)
ramp:Ramp digging
ustair:Staircase up
dstair:Staircase down
xstair:Staircase up/down
chan:Dig channel
-

After you have set the options, the command called with no options -repeats with the last selected parameters.

-

Examples:

-
    -
  • 'digcircle filled 3' = Dig a filled circle with diameter = 3.
  • -
  • 'digcircle' = Do it again.
  • -
-
-
-

digtype

-

For every tile on the map of the same vein type as the selected tile, this command designates it to have the same designation as the selected tile. If the selected tile has no designation, they will be dig designated. -If an argument is given, the designation of the selected tile is ignored, and all appropriate tiles are set to the specified designation.

-

Options:

- --- - - - - - - - - - - - - - - - -
dig:
channel:
ramp:
updown:up/down stairs
up:up stairs
down:down stairs
clear:clear designation
-
-
-

digFlood

-

Automatically digs out specified veins as they are discovered. It runs once every time a dwarf finishes a dig job. It will only dig out appropriate tiles that are adjacent to the finished dig job. To add a vein type, use digFlood 1 [type]. This will also enable the plugin. To remove a vein type, use digFlood 0 [type] 1 to disable, then remove, then re-enable.

-

digFlood 0 disable

-

digFlood 1 enable

-

digFlood 0 MICROCLINE COAL_BITUMINOUS 1 disable plugin, remove microcline and bituminous coal from monitoring, then re-enable the plugin

-

digFlood CLEAR remove all inorganics from monitoring

-

digFlood digAll1 ignore the monitor list and dig any vein

-

digFlood digAll0 disable digAll mode

-

See help digFlood for details.

-
-
-

filltraffic

-

Set traffic designations using flood-fill starting at the cursor.

-

Traffic Type Codes:

- --- - - - - - - - - - -
H:High Traffic
N:Normal Traffic
L:Low Traffic
R:Restricted Traffic
-

Other Options:

- --- - - - - - - - -
X:Fill accross z-levels.
B:Include buildings and stockpiles.
P:Include empty space.
-

Example:

-
-
filltraffic H
-
When used in a room with doors, it will set traffic to HIGH in just that room.
-
-
-
-

alltraffic

-

Set traffic designations for every single tile of the map (useful for resetting traffic designations).

-

Traffic Type Codes:

- --- - - - - - - - - - -
H:High Traffic
N:Normal Traffic
L:Low Traffic
R:Restricted Traffic
-

Example:

-
-
alltraffic N
-
Set traffic to 'normal' for all tiles.
-
-
-
-

restrictliquid

-

Restrict traffic on all visible tiles with liquid.

-
-
-

restrictice

-

Restrict traffic on all tiles on top of visible ice.

-
-
-

getplants

-

This tool allows plant gathering and tree cutting by RAW ID. Specify the types -of trees to cut down and/or shrubs to gather by their plant names, separated -by spaces.

-

Options:

- --- - - - - - - - - - -
-t:Select trees only (exclude shrubs)
-s:Select shrubs only (exclude trees)
-c:Clear designations instead of setting them
-x:Apply selected action to all plants except those specified (invert -selection)
-

Specifying both -t and -s will have no effect. If no plant IDs are specified, -all valid plant IDs will be listed.

-
-
-
-

Cleanup and garbage disposal

-
-

clean

-

Cleans all the splatter that get scattered all over the map, items and -creatures. In an old fortress, this can significantly reduce FPS lag. It can -also spoil your !!FUN!!, so think before you use it.

-

Options:

- --- - - - - - - - -
map:Clean the map tiles. By default, it leaves mud and snow alone.
units:Clean the creatures. Will also clean hostiles.
items:Clean all the items. Even a poisoned blade.
-

Extra options for 'map':

- --- - - - - - -
mud:Remove mud in addition to the normal stuff.
snow:Also remove snow coverings.
-
-
-

spotclean

-

Works like 'clean map snow mud', but only for the tile under the cursor. Ideal -if you want to keep that bloody entrance 'clean map' would clean up.

-
-
-

autodump

-

This utility lets you quickly move all items designated to be dumped. -Items are instantly moved to the cursor position, the dump flag is unset, -and the forbid flag is set, as if it had been dumped normally. -Be aware that any active dump item tasks still point at the item.

-

Cursor must be placed on a floor tile so the items can be dumped there.

-

Options:

- --- - - - - - - - - - - - -
destroy:Destroy instead of dumping. Doesn't require a cursor.
destroy-here:Destroy items only under the cursor. Alias autodump-destroy-here, for keybindings.
visible:Only process items that are not hidden.
hidden:Only process hidden items.
forbidden:Only process forbidden items (default: only unforbidden).
-
-
-

autodump-destroy-item

-

Destroy the selected item. The item may be selected in the 'k' list, or inside -a container. If called again before the game is resumed, cancels destroy.

-
-
-

cleanowned

-

Confiscates items owned by dwarfs. By default, owned food on the floor -and rotten items are confistacted and dumped.

-

Options:

- --- - - - - - - - - - - - -
all:confiscate all owned items
scattered:confiscated and dump all items scattered on the floor
x:confiscate/dump items with wear level 'x' and more
X:confiscate/dump items with wear level 'X' and more
dryrun:a dry run. combine with other options to see what will happen -without it actually happening.
-

Example:

-
-
cleanowned scattered X
-
This will confiscate rotten and dropped food, garbage on the floors and any -worn items with 'X' damage and above.
-
-
-
-
-

Bugfixes

-
-

drybuckets

-

This utility removes water from all buckets in your fortress, allowing them to be safely used for making lye.

-
-
-

fixdiplomats

-

Up to version 0.31.12, Elves only sent Diplomats to your fortress to propose -tree cutting quotas due to a bug; once that bug was fixed, Elves stopped caring -about excess tree cutting. This command adds a Diplomat position to all Elven -civilizations, allowing them to negotiate tree cutting quotas - and you to -violate them and start wars.

-
-
-

fixmerchants

-

This command adds the Guild Representative position to all Human civilizations, -allowing them to make trade agreements (just as they did back in 0.28.181.40d -and earlier) in case you haven't already modified your raws accordingly.

-
-
-

fixveins

-

Removes invalid references to mineral inclusions and restores missing ones. -Use this if you broke your embark with tools like tiletypes, or if you -accidentally placed a construction on top of a valuable mineral floor.

-
-
-

tweak

-

Contains various tweaks for minor bugs.

-

One-shot subcommands:

- --- - - - - - - - - - -
clear-missing:Remove the missing status from the selected unit. -This allows engraving slabs for ghostly, but not yet -found, creatures.
clear-ghostly:Remove the ghostly status from the selected unit and mark -it as dead. This allows getting rid of bugged ghosts -which do not show up in the engraving slab menu at all, -even after using clear-missing. It works, but is -potentially very dangerous - so use with care. Probably -(almost certainly) it does not have the same effects like -a proper burial. You've been warned.
fixmigrant:Remove the resident/merchant flag from the selected unit. -Intended to fix bugged migrants/traders who stay at the -map edge and don't enter your fort. Only works for -dwarves (or generally the player's race in modded games). -Do NOT abuse this for 'real' caravan merchants (if you -really want to kidnap them, use 'tweak makeown' instead, -otherwise they will have their clothes set to forbidden etc).
makeown:Force selected unit to become a member of your fort. -Can be abused to grab caravan merchants and escorts, even if -they don't belong to the player's race. Foreign sentients -(humans, elves) can be put to work, but you can't assign rooms -to them and they don't show up in DwarfTherapist because the -game treats them like pets. Grabbing draft animals from -a caravan can result in weirdness (animals go insane or berserk -and are not flagged as tame), but you are allowed to mark them -for slaughter. Grabbing wagons results in some funny spam, then -they are scuttled.
-

Subcommands that persist until disabled or DF quits:

- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
adamantine-cloth-wear:
 

Prevents adamantine clothing from wearing out while being worn (bug 6481).

-
advmode-contained:
 

Works around bug 6202, i.e. custom reactions with container inputs -in advmode. The issue is that the screen tries to force you to select -the contents separately from the container. This forcefully skips child -reagents.

-
civ-view-agreement:
 

Fixes overlapping text on the "view agreement" screen

-
craft-age-wear:

Fixes the behavior of crafted items wearing out over time (bug 6003). -With this tweak, items made from cloth and leather will gain a level of wear every 20 years.

-
eggs-fertile:

Displays a fertility indicator on nestboxes

-
farm-plot-select:
 

Adds "Select all" and "Deselect all" options to farm plot menus

-
fast-heat:

Further improves temperature update performance by ensuring that 1 degree -of item temperature is crossed in no more than specified number of frames -when updating from the environment temperature. This reduces the time it -takes for stable-temp to stop updates again when equilibrium is disturbed.

-
fast-trade:

Makes Shift-Down in the Move Goods to Depot and Trade screens select -the current item (fully, in case of a stack), and scroll down one line.

-
fps-min:

Fixes the in-game minimum FPS setting

-
import-priority-category:
 

Allows changing the priority of all goods in a -category when discussing an import agreement with the liaison

-
manager-quantity:
 

Removes the limit of 30 jobs per manager order

-
max-wheelbarrow:
 

Allows assigning more than 3 wheelbarrows to a stockpile

-
military-color-assigned:
 
-
Color squad candidates already assigned to other squads in yellow/green
-

to make them stand out more in the list.

-
-
-images/tweak-mil-color.png -
military-stable-assign:
 

Preserve list order and cursor position when assigning to squad, -i.e. stop the rightmost list of the Positions page of the military -screen from constantly resetting to the top.

-
nestbox-color:

Fixes the color of built nestboxes

-
shift-8-scroll:

Gives Shift-8 (or *) priority when scrolling menus, instead of scrolling the map

-
stable-cursor:

Saves the exact cursor position between t/q/k/d/b/etc menus of fortress mode.

-
tradereq-pet-gender:
 

Displays pet genders on the trade request screen

-
-
-
-

fix-armory

-

Enables a fix for storage of squad equipment in barracks.

-

Specifically, it prevents your haulers from moving squad equipment -to stockpiles, and instead queues jobs to store it on weapon racks, -armor stands, and in containers.

-
-

Note

-

In order to actually be used, weapon racks have to be patched and -manually assigned to a squad. See documentation for gui/assign-rack -below.

-

Also, the default capacity of armor stands is way too low, so you -may want to also apply the armorstand-capacity patch. Check out -the bug report for more information.

-
-

Note that the buildings in the armory are used as follows:

-
    -
  • Weapon racks (when patched) are used to store any assigned weapons. -Each rack belongs to a specific squad, and can store up to 5 weapons.
  • -
  • Armor stands belong to specific squad members and are used for -armor and shields. By default one stand can store one item of each -type (hence one boot or gauntlet); if patched, the limit is raised to 2, -which should be sufficient.
  • -
  • Cabinets are used to store assigned clothing for a specific squad member. -They are never used to store owned clothing.
  • -
  • Chests (boxes, etc) are used for a flask, backpack or quiver assigned -to the squad member. Due to a probable bug, food is dropped out of the -backpack when it is stored.
  • -
-
-

Warning

-

Although armor stands, cabinets and chests properly belong only to one -squad member, the owner of the building used to create the barracks will -randomly use any containers inside the room. Thus, it is recommended to -always create the armory from a weapon rack.

-
-

Contrary to the common misconception, all these uses are controlled by the -Individual Equipment usage flag. The Squad Equipment flag is actually -intended for ammo, but the game does even less in that area than for armor -and weapons. This plugin implements the following rules almost from scratch:

-
    -
  • Combat ammo is stored in chests inside rooms with Squad Equipment enabled.
  • -
  • If a chest is assigned to a squad member due to Individual Equipment also -being set, it is only used for that squad's ammo; otherwise, any squads -with Squad Equipment on the room will use all of the chests at random.
  • -
  • Training ammo is stored in chests inside archery ranges designated from -archery targets, and controlled by the same Train flag as archery training -itself. This is inspired by some defunct code for weapon racks.
  • -
-

There are some minor traces in the game code to suggest that the first of -these rules is intended by Toady; the rest are invented by this plugin.

-
-
-
-

Mode switch and reclaim

-
-

lair

-

This command allows you to mark the map as 'monster lair', preventing item -scatter on abandon. When invoked as 'lair reset', it does the opposite.

-

Unlike reveal, this command doesn't save the information about tiles - you -won't be able to restore state of real monster lairs using 'lair reset'.

-

Options:

- --- - - - - - -
lair:Mark the map as monster lair
lair reset:Mark the map as ordinary (not lair)
-
-
-

mode

-

This command lets you see and change the game mode directly. -Not all combinations are good for every situation and most of them will -produce undesirable results. There are a few good ones though.

-
-

Example

-

You are in fort game mode, managing your fortress and paused. -You switch to the arena game mode, assume control of a creature and then -switch to adventure game mode(1). -You just lost a fortress and gained an adventurer. -You could also do this. -You are in fort game mode, managing your fortress and paused at the esc menu. -You switch to the adventure game mode, assume control of a creature, then save or retire. -You just created a returnable mountain home and gained an adventurer.

-
-

I take no responsibility of anything that happens as a result of using this tool

-
-
-
-

Visualizer and data export

-
-

stonesense

-

An isometric visualizer that runs in a second window. This requires working -graphics acceleration and at least a dual core CPU (otherwise it will slow -down DF). Invoked with stonesense, or alias ssense.

-

For detailed information, see the stonesense readme, the wiki page, -or the Bay12 forum thread.

-

Stonesense works on Windows XP SP3 or later, and most modern Linux distributions. -Each stonesense version is built for a particular version of DFHack, so -releases are now done through DFHack.

-
-
-

mapexport

-

Export the current loaded map as a file. This was used by visualizers for -DF 0.34.11, but is now basically obsolete.

-
-
-

dwarfexport

-

Export dwarves to RuneSmith-compatible XML; also unused by modern tools.

-
-
-

exportlegends

-

Controls legends mode to export data - especially useful to set-and-forget large -worlds, or when you want a map of every site when there are several hundred.

-

The 'info' option exports more data than is possible in vanilla, to a -region-date-legends_plus.xml file developed to extend the World -Viewer utility and potentially compatible with others.

-

Options:

- --- - - - - - - - - - -
info:Exports the world/gen info, the legends XML, and a custom XML with more information
sites:Exports all available site maps
maps:Exports all seventeen detailed maps
all:Equivalent to calling all of the above, in that order
-
-
-

blueprint

-

Exports a portion of your fortress into QuickFort style blueprint files.:

-
-blueprint <x> <y> <z> <name> [dig] [build] [place] [query]
-
-

Options:

- --- - - - - - - - - - - - - - -
x,y,z:Size of map area to export
name:Name of export files
dig:Export dig commands to "<name>-dig.csv"
build:Export build commands to "<name>-build.csv"
place:Export stockpile commands to "<name>-place.csv"
query:Export query commands to "<name>-query.csv"
-

If only region and name are given, all exports are performed.

-
-
-
-

Job management

-
-

job

-

Command for general job query and manipulation.

-

Options:

-
-
no extra options
-
Print details of the current job. The job can be selected -in a workshop, or the unit/jobs screen.
-
list
-
Print details of all jobs in the selected workshop.
-
item-material <item-idx> <material[:subtoken]>
-
Replace the exact material id in the job item.
-
item-type <item-idx> <type[:subtype]>
-
Replace the exact item type id in the job item.
-
-
-
-

job-material

-

Alter the material of the selected job.

-

Invoked as:

-
-job-material <inorganic-token>
-
-

Intended to be used as a keybinding:

-
    -
  • In 'q' mode, when a job is highlighted within a workshop or furnace, -changes the material of the job. Only inorganic materials can be used -in this mode.
  • -
  • In 'b' mode, during selection of building components positions the cursor -over the first available choice with the matching material.
  • -
-
-
-

job-duplicate

-

Duplicate the selected job in a workshop:

-
    -
  • In 'q' mode, when a job is highlighted within a workshop or furnace building, -instantly duplicates the job.
  • -
-
-
-

stockflow

-

Allows the fortress bookkeeper to queue jobs through the manager, -based on space or items available in stockpiles.

-

Usage:

-
-
stockflow enable
-
Enable the plugin.
-
stockflow disable
-
Disable the plugin.
-
stockflow fast
-
Enable the plugin in fast mode.
-
stockflow list
-
List any work order settings for your stockpiles.
-
stockflow status
-
Display whether the plugin is enabled.
-
-

While enabled, the 'q' menu of each stockpile will have two new options:

-
    -
  • j: Select a job to order, from an interface like the manager's screen.
  • -
  • J: Cycle between several options for how many such jobs to order.
  • -
-

Whenever the bookkeeper updates stockpile records, new work orders will -be placed on the manager's queue for each such selection, reduced by the -number of identical orders already in the queue.

-

In fast mode, new work orders will be enqueued once per day, instead of -waiting for the bookkeeper.

-
-
-

workflow

-

Manage control of repeat jobs.

-

Usage:

-
-
workflow enable [option...], workflow disable [option...]
-

If no options are specified, enables or disables the plugin. -Otherwise, enables or disables any of the following options:

-
    -
  • drybuckets: Automatically empty abandoned water buckets.
  • -
  • auto-melt: Resume melt jobs when there are objects to melt.
  • -
-
-
workflow jobs
-
List workflow-controlled jobs (if in a workshop, filtered by it).
-
workflow list
-
List active constraints, and their job counts.
-
workflow list-commands
-
List active constraints as workflow commands that re-create them; -this list can be copied to a file, and then reloaded using the -script built-in command.
-
workflow count <constraint-spec> <cnt-limit> [cnt-gap]
-
Set a constraint, counting every stack as 1 item.
-
workflow amount <constraint-spec> <cnt-limit> [cnt-gap]
-
Set a constraint, counting all items within stacks.
-
workflow unlimit <constraint-spec>
-
Delete a constraint.
-
workflow unlimit-all
-
Delete all constraints.
-
-
-

Function

-

When the plugin is enabled, it protects all repeat jobs from removal. -If they do disappear due to any cause, they are immediately re-added to their -workshop and suspended.

-

In addition, when any constraints on item amounts are set, repeat jobs that -produce that kind of item are automatically suspended and resumed as the item -amount goes above or below the limit. The gap specifies how much below the limit -the amount has to drop before jobs are resumed; this is intended to reduce -the frequency of jobs being toggled.

-

Check out the gui/workflow script below for a simple front-end integrated -in the game UI.

-
-
-

Constraint format

-

The constraint spec consists of 4 parts, separated with '/' characters:

-
-ITEM[:SUBTYPE]/[GENERIC_MAT,...]/[SPECIFIC_MAT:...]/[LOCAL,<quality>]
-
-

The first part is mandatory and specifies the item type and subtype, -using the raw tokens for items, in the same syntax you would e.g. use -for a custom reaction input. See this page for more info.

-

The subsequent parts are optional:

-
    -
  • A generic material spec constrains the item material to one of -the hard-coded generic classes, which currently include:

    -
    -PLANT WOOD CLOTH SILK LEATHER BONE SHELL SOAP TOOTH HORN PEARL YARN
    -METAL STONE SAND GLASS CLAY MILK
    -
    -
  • -
  • A specific material spec chooses the material exactly, using the -raw syntax for reaction input materials, e.g. INORGANIC:IRON, -although for convenience it also allows just IRON, or ACACIA:WOOD etc. -See this page for more details on the unabbreviated raw syntax.

    -
  • -
  • A comma-separated list of miscellaneous flags, which currently can -be used to ignore imported items or items below a certain quality.

    -
  • -
-
-
-

Constraint examples

-

Keep metal bolts within 900-1000, and wood/bone within 150-200:

-
-workflow amount AMMO:ITEM_AMMO_BOLTS/METAL 1000 100
-workflow amount AMMO:ITEM_AMMO_BOLTS/WOOD,BONE 200 50
-
-

Keep the number of prepared food & drink stacks between 90 and 120:

-
-workflow count FOOD 120 30
-workflow count DRINK 120 30
-
-

Make sure there are always 25-30 empty bins/barrels/bags:

-
-workflow count BIN 30
-workflow count BARREL 30
-workflow count BOX/CLOTH,SILK,YARN 30
-
-

Make sure there are always 15-20 coal and 25-30 copper bars:

-
-workflow count BAR//COAL 20
-workflow count BAR//COPPER 30
-
-

Produce 15-20 gold crafts:

-
-workflow count CRAFTS//GOLD 20
-
-

Collect 15-20 sand bags and clay boulders:

-
-workflow count POWDER_MISC/SAND 20
-workflow count BOULDER/CLAY 20
-
-

Make sure there are always 80-100 units of dimple dye:

-
-workflow amount POWDER_MISC//MUSHROOM_CUP_DIMPLE:MILL 100 20
-
-
-

Note

-

In order for this to work, you have to set the material of the PLANT input -on the Mill Plants job to MUSHROOM_CUP_DIMPLE using the 'job item-material' -command. Otherwise the plugin won't be able to deduce the output material.

-
-

Maintain 10-100 locally-made crafts of exceptional quality:

-
-workflow count CRAFTS///LOCAL,EXCEPTIONAL 100 90
-
-
-
-
-
-

Fortress activity management

-
-

seedwatch

-

Watches the numbers of seeds available and enables/disables seed and plant cooking.

-

Each plant type can be assigned a limit. If their number falls below that limit, -the plants and seeds of that type will be excluded from cookery. -If the number rises above the limit + 20, then cooking will be allowed.

-

The plugin needs a fortress to be loaded and will deactivate automatically otherwise. -You have to reactivate with 'seedwatch start' after you load the game.

-

Options:

- --- - - - - - - - - - - - -
all:Adds all plants from the abbreviation list to the watch list.
start:Start watching.
stop:Stop watching.
info:Display whether seedwatch is watching, and the watch list.
clear:Clears the watch list.
-

Examples:

-
-
seedwatch MUSHROOM_HELMET_PLUMP 30
-
add MUSHROOM_HELMET_PLUMP to the watch list, limit = 30
-
seedwatch MUSHROOM_HELMET_PLUMP
-
removes MUSHROOM_HELMET_PLUMP from the watch list.
-
seedwatch all 30
-
adds all plants from the abbreviation list to the watch list, the limit being 30.
-
-
-
-

zone

-

Helps a bit with managing activity zones (pens, pastures and pits) and cages.

-

Options:

- --- - - - - - - - - - - - - - - - - - - - - - - - - - -
set:Set zone or cage under cursor as default for future assigns.
assign:Assign unit(s) to the pen or pit marked with the 'set' command. -If no filters are set a unit must be selected in the in-game ui. -Can also be followed by a valid zone id which will be set -instead.
unassign:Unassign selected creature from it's zone.
nick:Mass-assign nicknames, must be followed by the name you want -to set.
remnick:Mass-remove nicknames.
tocages:Assign unit(s) to cages inside a pasture.
uinfo:Print info about unit(s). If no filters are set a unit must -be selected in the in-game ui.
zinfo:Print info about zone(s). If no filters are set zones under -the cursor are listed.
verbose:Print some more info.
filters:Print list of valid filter options.
examples:Print some usage examples.
not:Negates the next filter keyword.
-

Filters:

- --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
all:Process all units (to be used with additional filters).
count:Must be followed by a number. Process only n units (to be used -with additional filters).
unassigned:Not assigned to zone, chain or built cage.
minage:Minimum age. Must be followed by number.
maxage:Maximum age. Must be followed by number.
race:Must be followed by a race RAW ID (e.g. BIRD_TURKEY, ALPACA, -etc). Negatable.
caged:In a built cage. Negatable.
own:From own civilization. Negatable.
merchant:Is a merchant / belongs to a merchant. Should only be used for -pitting, not for stealing animals (slaughter should work).
war:Trained war creature. Negatable.
hunting:Trained hunting creature. Negatable.
tamed:Creature is tame. Negatable.
trained:Creature is trained. Finds war/hunting creatures as well as -creatures who have a training level greater than 'domesticated'. -If you want to specifically search for war/hunting creatures use -'war' or 'hunting' Negatable.
trainablewar:Creature can be trained for war (and is not already trained for -war/hunt). Negatable.
trainablehunt:Creature can be trained for hunting (and is not already trained -for war/hunt). Negatable.
male:Creature is male. Negatable.
female:Creature is female. Negatable.
egglayer:Race lays eggs. Negatable.
grazer:Race is a grazer. Negatable.
milkable:Race is milkable. Negatable.
-
-

Usage with single units

-

One convenient way to use the zone tool is to bind the command 'zone assign' to -a hotkey, maybe also the command 'zone set'. Place the in-game cursor over -a pen/pasture or pit, use 'zone set' to mark it. Then you can select units -on the map (in 'v' or 'k' mode), in the unit list or from inside cages -and use 'zone assign' to assign them to their new home. Allows pitting your -own dwarves, by the way.

-
-
-

Usage with filters

-

All filters can be used together with the 'assign' command.

-

Restrictions: It's not possible to assign units who are inside built cages -or chained because in most cases that won't be desirable anyways. -It's not possible to cage owned pets because in that case the owner -uncages them after a while which results in infinite hauling back and forth.

-

Usually you should always use the filter 'own' (which implies tame) unless you -want to use the zone tool for pitting hostiles. 'own' ignores own dwarves unless -you specify 'race DWARF' (so it's safe to use 'assign all own' to one big -pasture if you want to have all your animals at the same place). 'egglayer' and -'milkable' should be used together with 'female' unless you have a mod with -egg-laying male elves who give milk or whatever. Merchants and their animals are -ignored unless you specify 'merchant' (pitting them should be no problem, -but stealing and pasturing their animals is not a good idea since currently they -are not properly added to your own stocks; slaughtering them should work).

-

Most filters can be negated (e.g. 'not grazer' -> race is not a grazer).

-
-
-

Mass-renaming

-

Using the 'nick' command you can set the same nickname for multiple units. -If used without 'assign', 'all' or 'count' it will rename all units in the -current default target zone. Combined with 'assign', 'all' or 'count' (and -further optional filters) it will rename units matching the filter conditions.

-
-
-

Cage zones

-

Using the 'tocages' command you can assign units to a set of cages, for example -a room next to your butcher shop(s). They will be spread evenly among available -cages to optimize hauling to and butchering from them. For this to work you need -to build cages and then place one pen/pasture activity zone above them, covering -all cages you want to use. Then use 'zone set' (like with 'assign') and use -'zone tocages filter1 filter2 ...'. 'tocages' overwrites 'assign' because it -would make no sense, but can be used together with 'nick' or 'remnick' and all -the usual filters.

-
-
-

Examples

-
-
zone assign all own ALPACA minage 3 maxage 10
-
Assign all own alpacas who are between 3 and 10 years old to the selected -pasture.
-
zone assign all own caged grazer nick ineedgrass
-
Assign all own grazers who are sitting in cages on stockpiles (e.g. after -buying them from merchants) to the selected pasture and give them -the nickname 'ineedgrass'.
-
zone assign all own not grazer not race CAT
-
Assign all own animals who are not grazers, excluding cats.
-
zone assign count 5 own female milkable
-
Assign up to 5 own female milkable creatures to the selected pasture.
-
zone assign all own race DWARF maxage 2
-
Throw all useless kids into a pit :)
-
zone nick donttouchme
-
Nicknames all units in the current default zone or cage to 'donttouchme'. -Mostly intended to be used for special pastures or cages which are not marked -as rooms you want to protect from autobutcher.
-
zone tocages count 50 own tame male not grazer
-
Stuff up to 50 owned tame male animals who are not grazers into cages built -on the current default zone.
-
-
-
-
-

autonestbox

-

Assigns unpastured female egg-layers to nestbox zones. Requires that you create -pen/pasture zones above nestboxes. If the pen is bigger than 1x1 the nestbox -must be in the top left corner. Only 1 unit will be assigned per pen, regardless -of the size. The age of the units is currently not checked, most birds grow up -quite fast. Egglayers who are also grazers will be ignored, since confining them -to a 1x1 pasture is not a good idea. Only tame and domesticated own units are -processed since pasturing half-trained wild egglayers could destroy your neat -nestbox zones when they revert to wild. When called without options autonestbox -will instantly run once.

-

Options:

- --- - - - - - - - -
start:Start running every X frames (df simulation ticks). -Default: X=6000, which would be every 60 seconds at 100fps.
stop:Stop running automatically.
sleep:Must be followed by number X. Changes the timer to sleep X -frames between runs.
-
-
-

autobutcher

-

Assigns lifestock for slaughter once it reaches a specific count. Requires that -you add the target race(s) to a watch list. Only tame units will be processed.

-

Units will be ignored if they are:

-
    -
  • Nicknamed (for custom protection; you can use the rename unit tool -individually, or zone nick for groups)
  • -
  • Caged, if and only if the cage is defined as a room (to protect zoos)
  • -
  • Trained for war or hunting
  • -
-

Creatures who will not reproduce (because they're not interested in the -opposite sex or have been gelded) will be butchered before those who will. -Older adults and younger children will be butchered first if the population -is above the target (default 1 male, 5 female kids and adults). Note that -you may need to set a target above 1 to have a reliable breeding population -due to asexuality etc.

-

Options:

- --- - - - - - - - - - - - - - - - - - - - - - - - - - - -
start:Start running every X frames (df simulation ticks). -Default: X=6000, which would be every 60 seconds at 100fps.
stop:Stop running automatically.
sleep:Must be followed by number X. Changes the timer to sleep -X frames between runs.
watch R:Start watching a race. R can be a valid race RAW id (ALPACA, -BIRD_TURKEY, etc) or a list of ids seperated by spaces or -the keyword 'all' which affects all races on your current -watchlist.
unwatch R:Stop watching race(s). The current target settings will be -remembered. R can be a list of ids or the keyword 'all'.
forget R:Stop watching race(s) and forget it's/their target settings. -R can be a list of ids or the keyword 'all'.
autowatch:Automatically adds all new races (animals you buy from merchants, -tame yourself or get from migrants) to the watch list using -default target count.
noautowatch:Stop auto-adding new races to the watchlist.
list:Print the current status and watchlist.
list_export:Print the commands needed to set up status and watchlist, -which can be used to import them to another save (see notes).
target fk mk fa ma R:
 Set target count for specified race(s). -fk = number of female kids, -mk = number of male kids, -fa = number of female adults, -ma = number of female adults. -R can be a list of ids or the keyword 'all' or 'new'. -R = 'all': change target count for all races on watchlist -and set the new default for the future. R = 'new': don't touch -current settings on the watchlist, only set the new default -for future entries.
example:Print some usage examples.
-

Examples:

-

You want to keep max 7 kids (4 female, 3 male) and max 3 adults (2 female, -1 male) of the race alpaca. Once the kids grow up the oldest adults will get -slaughtered. Excess kids will get slaughtered starting with the youngest -to allow that the older ones grow into adults. Any unnamed cats will -be slaughtered as soon as possible.

-
-autobutcher target 4 3 2 1 ALPACA BIRD_TURKEY
-autobutcher target 0 0 0 0 CAT
-autobutcher watch ALPACA BIRD_TURKEY CAT
-autobutcher start
-
-

Automatically put all new races onto the watchlist and mark unnamed tame units -for slaughter as soon as they arrive in your fort. Settings already made -for specific races will be left untouched.

-
-autobutcher target 0 0 0 0 new
-autobutcher autowatch
-autobutcher start
-
-

Stop watching the races alpaca and cat, but remember the target count -settings so that you can use 'unwatch' without the need to enter the -values again. Note: 'autobutcher unwatch all' works, but only makes sense -if you want to keep the plugin running with the 'autowatch' feature or manually -add some new races with 'watch'. If you simply want to stop it completely use -'autobutcher stop' instead.:

-
-autobutcher unwatch ALPACA CAT
-
-

Note:

-

Settings and watchlist are stored in the savegame, so that you can have -different settings for each world. If you want to copy your watchlist to -another savegame you can export the commands with list_export:

-

To export, open an external terminal in the DF directory, and run -dfhack-run autobutcher list_export > filename.txt. To import, load your -new save and run script filename.txt in the DFHack terminal.

-
-
-

autochop

-

Automatically manage tree cutting designation to keep available logs withing given -quotas.

-

Open the dashboard by running:

-
-getplants autochop
-
-

The plugin must be activated (with c) before it can be used. You can then set logging quotas -and restrict designations to specific burrows (with 'Enter') if desired. The plugin's activity -cycle runs once every in game day.

-

If you add:

-
-enable getplants
-
-

to your dfhack.init there will be a hotkey to open the dashboard from the chop designation -menu.

-
-
-

autolabor

-

Automatically manage dwarf labors to efficiently complete jobs. -Autolabor tries to keep as many dwarves as possible busy but -also tries to have dwarves specialize in specific skills.

-

The key is that, for almost all labors, once a dwarf begins a job it will finish that -job even if the associated labor is removed. Autolabor therefore frequently checks -which dwarf or dwarves should take new jobs for that labor, and sets labors accordingly. -Labors with equiptment (mining, hunting, and woodcutting), which are abandoned -if labors change mid-job, are handled slightly differently to minimise churn.

-

Warning: autolabor will override any manual changes you make to labors -while it is enabled, including through other tools such as Dwarf Therapist

-

Simple usage:

- --- - - - - - - - -
enable autolabor:
 Enables the plugin with default settings. (Persistent per fortress)
disable autolabor:
 Disables the plugin.
-

Anything beyond this is optional - autolabor works well on the default settings.

-

Advanced usage:

- --- - - - - - - - - - - - - - - - - - - - - - -
autolabor <labor> <minimum> [<maximum>]:
 Set number of dwarves assigned to a labor.
autolabor <labor> haulers:
 Set a labor to be handled by hauler dwarves.
autolabor <labor> disable:
 Turn off autolabor for a specific labor.
autolabor <labor> reset:
 Return a labor to the default handling.
autolabor reset-all:
 Return all labors to the default handling.
autolabor list:List current status of all labors.
autolabor status:
 Show basic status information.
-

Examples:

- --- - - - - - - - - - - - - - - - - -
autolabor MINE 5:
 Keep at least 5 dwarves with mining enabled.
autolabor CUT_GEM 1 1:
 Keep exactly 1 dwarf with gemcutting enabled.
autolabor COOK 1 1 3:
 Keep 1 dwarf with cooking enabled, selected only from the top 3.
autolabor FEED_WATER_CIVILIANS haulers:
 Have haulers feed and water wounded dwarves.
autolabor CUTWOOD disable:
 Turn off autolabor for wood cutting.
-

By default, each labor is assigned to between 1 and 200 dwarves (2-200 for mining). -By default 33% of the workforce become haulers, who handle all hauling jobs as well -as cleaning, pulling levers, recovering wounded, removing constructions, and filling ponds. -Other jobs are automatically assigned as described above. Each of these settings can be adjusted.

-

Jobs are rarely assigned to nobles with responsibilities for meeting diplomats or merchants, -never to the chief medical dwarf, and less often to the bookeeper and manager.

-

Hunting is never assigned without a butchery, and fishing is never assigned without a fishery.

-

For each labor a preference order is calculated based on skill, biased against masters of other -trades and excluding those who can't do the job. The labor is then added to the best <minimum> -dwarves for that labor. We assign at least the minimum number of dwarfs, in order of preference, -and then assign additional dwarfs that meet any of these conditions:

-
    -
  • The dwarf is idle and there are no idle dwarves assigned to this labor
  • -
  • The dwarf has non-zero skill associated with the labor
  • -
  • The labor is mining, hunting, or woodcutting and the dwarf currently has it enabled.
  • -
-

We stop assigning dwarfs when we reach the maximum allowed.

-
-
-
-

Other

-
-

catsplosion

-

Makes cats just multiply. It is not a good idea to run this more than once or -twice.

-
-
-

dfusion

-

This is the DFusion system (a DFHack precursor) by Warmist, running as a DFHack -plugin. For detail on this legacy system, see the Bay12 forums thread.

-
-
-

embark-tools

-

A collection of embark-related tools.

-

Usage:

-
-embark-tools enable/disable tool [tool]...
-
-

Tools:

-
    -
  • anywhere: Allows embarking anywhere (including sites, mountain-only biomes, and oceans). Use with caution.
  • -
  • mouse: Implements mouse controls (currently in the local embark region only)
  • -
  • nano: An implementation of nano embark - allows resizing below 2x2 when enabled.
  • -
  • sand: Displays an indicator when sand is present in the currently-selected area, similar to the default clay/stone indicators.
  • -
  • sticky: Maintains the selected local area while navigating the world map
  • -
-
-
-

petcapRemover

-

This plugin allows you to remove or raise the pet population cap. In vanilla -DF, pets will not reproduce unless the population is below 50 and the number of -children of that species is below a certain percentage. This plugin allows -removing the second restriction and removing or raising the first. Pets still -require PET or PET_EXOTIC tags in order to reproduce. Type help petcapRemover -for exact usage. In order to make population more stable and avoid sudden -population booms as you go below the raised population cap, this plugin counts -pregnancies toward the new population cap. It can still go over, but only in the -case of multiple births.

-
-
petcapRemover
-
cause pregnancies now and schedule the next check
-
petcapRemover every n
-
set how often in ticks the plugin checks for possible pregnancies
-
petcapRemover cap n
-
set the new cap to n. if n = 0, no cap
-
petcapRemover pregtime n
-
sets the pregnancy duration to n ticks. natural pregnancies are 300000 ticks for the current race and 200000 for everyone else
-
-
-
-

misery

-

When enabled, every new negative dwarven thought will be multiplied by a factor (2 by default).

-

Usage:

- --- - - - - - - - - - - - - -
misery enable n:
 enable misery with optional magnitude n. If specified, n must be positive.
misery n:same as "misery enable n"
misery enable:same as "misery enable 2"
misery disable:stop adding new negative thoughts. This will not remove existing duplicated thoughts. Equivalent to "misery 1"
misery clear:remove fake thoughts added in this session of DF. Saving makes them permanent! Does not change factor.
-
-
-

strangemood

-

Creates a strange mood job the same way the game itself normally does it.

-

Options:

- --- - - - - - - - - - -
-force:Ignore normal strange mood preconditions (no recent mood, minimum moodable population, artifact limit not reached).
-unit:Make the strange mood strike the selected unit instead of picking one randomly. Unit eligibility is still enforced.
-type T:Force the mood to be of a particular type instead of choosing randomly based on happiness. -Valid values are "fey", "secretive", "possessed", "fell", and "macabre".
-skill S:Force the mood to use a specific skill instead of choosing the highest moodable skill. -Valid values are "miner", "carpenter", "engraver", "mason", "tanner", "weaver", "clothier", "weaponsmith", "armorsmith", "metalsmith", "gemcutter", "gemsetter", "woodcrafter", "stonecrafter", "metalcrafter", "glassmaker", "leatherworker", "bonecarver", "bowyer", and "mechanic".
-

Known limitations: if the selected unit is currently performing a job, the mood will not be started.

-
-
-

log-region

-

When enabled in dfhack.init, each time a fort is loaded identifying information will be written to the gamelog. Assists in parsing the file if you switch between forts, and adds information for story-building.

-
-
-
-
-

Scripts

-

Lua or ruby scripts placed in the hack/scripts/ directory are considered for -execution as if they were native DFHack commands. They are listed at the end -of the 'ls' command output.

-

Note: scripts in subdirectories of hack/scripts/ can still be called, but will -only be listed by ls if called as 'ls -a'. This is intended as a way to hide -scripts that are obscure, developer-oriented, or should be used as keybindings.

-

The following scripts are distibuted with DFHack:

-
-

fix/*

-

Scripts in this subdirectory fix various bugs and issues, some of them obscure.

-
    -
  • fix/blood-del

    -

    Makes it so that future caravans won't bring barrels full of blood, ichor, or goo.

    -
  • -
  • fix/build-location

    -

    Fixes construction jobs that are stuck trying to build a wall while standing -on the same exact tile (bug 5991), designates the tile restricted traffic to -hopefully avoid jamming it again, and unsuspends them.

    -
  • -
  • fix/cloth-stockpile

    -

    Fixes erratic behavior of cloth stockpiles by scanning material objects -in memory and patching up some invalid reference fields. Needs to be run -every time a save game is loaded; putting fix/cloth-stockpile enable -in dfhack.init makes it run automatically.

    -
  • -
  • fix/dead-units

    -

    Removes uninteresting dead units from the unit list. Doesn't seem to give any -noticeable performance gain, but migrants normally stop if the unit list grows -to around 3000 units, and this script reduces it back.

    -
  • -
  • fix/feeding-timers

    -

    Reset the GiveWater and GiveFood timers of all units as appropriate.

    -
  • -
  • fix/growth-bug

    -

    Fixes locally born units such that they will grow larger than their birth size. -Note that this bug was fixed in DF version 0.40.02.

    -
  • -
  • fix/item-occupancy

    -

    Diagnoses and fixes issues with nonexistant 'items occupying site', usually -caused by autodump bugs or other hacking mishaps.

    -
  • -
  • fix/population-cap

    -

    Run this after every migrant wave to ensure your population cap is not exceeded. -The issue with the cap is that it is compared to the population number reported -by the last caravan, so once it drops below the cap, migrants continue to come -until that number is updated again.

    -
  • -
  • fix/stable-temp

    -

    Instantly sets the temperature of all free-lying items to be in equilibrium with -the environment and stops temperature updates. In order to maintain this efficient -state however, use tweak stable-temp and tweak fast-heat.

    -
  • -
-
-
-

gui/*

-

Scripts that implement dialogs inserted into the main game window are put in this -directory.

-
    -
  • gui/hack-wish

    -

    A graphical interface for creating items.

    -
  • -
  • gui/stockpiles

    -

    Load and save stockpile settings from the 'q' menu. -Usage:

    -
    -gui/stockpiles -save       to save the current stockpile
    -gui/stockpiles -load       to load settings into the current stockpile
    -gui/stockpiles -dir <path> set the default directory to save settings into
    -gui/stockpiles -help       to see this message
    -
    -
  • -
-

Don't forget to enable stockpiles and create the stocksettings directory in -the DF folder before trying to use this plugin.

-
-
-

binpatch

-

Checks, applies or removes binary patches directly in memory at runtime:

-
-binpatch check/apply/remove <patchname>
-
-

If the name of the patch has no extension or directory separators, the -script uses hack/patches/<df-version>/<name>.dif, thus auto-selecting -the version appropriate for the currently loaded executable.

-
-
-

create-items

-

Spawn arbitrary items under the cursor.

-

The first argument gives the item category, the second gives the material, -and the optionnal third gives the number of items to create (defaults to 20).

-

Currently supported item categories: boulder, bar, plant, log, -web.

-

Instead of material, using list makes the script list eligible materials.

-

The web item category will create an uncollected cobweb on the floor.

-

Note that the script does not enforce anything, and will let you create -boulders of toad blood and stuff like that. -However the list mode will only show 'normal' materials.

-

Examples:

-
-create-items boulders COAL_BITUMINOUS 12
-create-items plant tail_pig
-create-items log list
-create-items web CREATURE:SPIDER_CAVE_GIANT:SILK
-create-items bar CREATURE:CAT:SOAP
-create-items bar adamantine
-
-
-
-

digfort

-

A script to designate an area for digging according to a plan in csv format.

-

This script, inspired from quickfort, can designate an area for digging. -Your plan should be stored in a .csv file like this:

-
-# this is a comment
-d;d;u;d;d;skip this tile;d
-d;d;d;i
-
-

Available tile shapes are named after the 'dig' menu shortcuts: -d for dig, u for upstairs, d downstairs, i updown, -h channel, r upward ramp, x remove designation. -Unrecognized characters are ignored (eg the 'skip this tile' in the sample).

-

Empty lines and data after a # are ignored as comments. -To skip a row in your design, use a single ;.

-

One comment in the file may contain the phrase start(3,5). It is interpreted -as an offset for the pattern: instead of starting at the cursor, it will start -3 tiles left and 5 tiles up from the cursor.

-

The script takes the plan filename, starting from the root df folder (where -Dwarf Fortress.exe is found).

-
-
-

drain-aquifer

-

Remove all 'aquifer' tag from the map blocks. Irreversible.

-
-
-

deathcause

-

Focus a body part ingame, and this script will display the cause of death of -the creature. -Also works when selecting units from the (u) unitlist viewscreen.

-
-
-

dfstatus

-

Show a quick overview of critical stock quantities, including food, drinks, wood, and various bars.

-
-
-

exterminate

-

Kills any unit of a given race.

-

With no argument, lists the available races and count eligible targets.

-

With the special argument him, targets only the selected creature.

-

With the special argument undead, targets all undeads on the map, -regardless of their race.

-

When specifying a race, a caste can be specified to further restrict the -targeting. To do that, append and colon and the caste name after the race.

-

Any non-dead non-caged unit of the specified race gets its blood_count -set to 0, which means immediate death at the next game tick. For creatures -such as vampires, it also sets animal.vanish_countdown to 2.

-

An alternate mode is selected by adding a 2nd argument to the command, -magma. In this case, a column of 7/7 magma is generated on top of the -targets until they die (Warning: do not call on magma-safe creatures. Also, -using this mode on birds is not recommended.)

-

Will target any unit on a revealed tile of the map, including ambushers, -but ignore caged/chained creatures.

-

Ex:

-
-exterminate gob
-exterminate gob:male
-
-

To kill a single creature, select the unit with the 'v' cursor and:

-
-exterminate him
-
-

To purify all elves on the map with fire (may have side-effects):

-
-exterminate elve magma
-
-
-
-

fortplan

-

Usage: fortplan [filename]

-

Designates furniture for building according to a .csv file with -quickfort-style syntax. Companion to digfort.

-

The first line of the file must contain the following:

-
-#build start(X; Y; <start location description>)
-
-

...where X and Y are the offset from the top-left corner of the file's area -where the in-game cursor should be located, and <start location description> -is an optional description of where that is. You may also leave a description -of the contents of the file itself following the closing parenthesis on the -same line.

-

The syntax of the file itself is similar to digfort or quickfort. At present, -only buildings constructed of an item with the same name as the building -are supported. All other characters are ignored. For example:

-
-`,`,d,`,`
-`,f,`,t,`
-`,s,b,c,`
-
-

This section of a file would designate for construction a door and some -furniture inside a bedroom: specifically, clockwise from top left, a cabinet, -a table, a chair, a bed, and a statue.

-

All of the building designation uses Planning Mode, so you do not need to -have the items available to construct all the buildings when you run -fortplan with the .csv file.

-
-
-

growcrops

-

Instantly grow seeds inside farming plots.

-

With no argument, this command list the various seed types currently in -use in your farming plots. -With a seed type, the script will grow 100 of these seeds, ready to be -harvested. You can change the number with a 2nd argument.

-

For example, to grow 40 plump helmet spawn:

-
-growcrops plump 40
-
-
-
-

hfs-pit

-

Creates a pit to the underworld at the cursor.

-

Takes three arguments: diameter of the pit in tiles, whether to wall off -the pit, and whether to insert stairs. If no arguments are given, the default -is "hfs-pit 1 0 0", ie single-tile wide with no walls or stairs.:

-
-hfs-pit 4 0 1
-hfs-pit 2 1 0
-
-

First example is a four-across pit with stairs but no walls; second is a -two-across pit with stairs but no walls.

-
-
-

hotkey-notes

-

Lists the key, name, and jump position of your hotkeys in the DFHack console.

-
-
-

lever

-

Allow manipulation of in-game levers from the dfhack console.

-

Can list levers, including state and links, with:

-
-lever list
-
-

To queue a job so that a dwarf will pull the lever 42, use lever pull 42. -This is the same as 'q'uerying the building and queue a 'P'ull request.

-

To magically toggle the lever immediately, use:

-
-lever pull 42 --now
-
-
-
-

locate-ore

-

Scan the map for metal ores.

-

Finds and designate for digging one tile of a specific metal ore. -Only works for native metal ores, does not handle reaction stuff (eg STEEL).

-

When invoked with the list argument, lists metal ores available on the map.

-

Examples:

-
-locate-ore list
-locate-ore hematite
-locate-ore iron
-
-
-
-

lua

-

There are the following ways to invoke this command:

-
    -
  1. lua (without any parameters)

    -

    This starts an interactive lua interpreter.

    -
  2. -
  3. lua -f "filename" or lua --file "filename"

    -

    This loads and runs the file indicated by filename.

    -
  4. -
  5. lua -s ["filename"] or lua --save ["filename"]

    -

    This loads and runs the file indicated by filename from the save -directory. If the filename is not supplied, it loads "dfhack.lua".

    -
  6. -
  7. :lua lua statement...

    -

    Parses and executes the lua statement like the interactive interpreter would.

    -
  8. -
-
-
-

masspit

-

Designate all creatures in cages on top of a pit/pond activity zone for pitting. -Works best with an animal stockpile on top of the zone.

-

Works with a zone number as argument (eg Activity Zone #6 -> masspit 6) -or with the game cursor on top of the area.

-
-
-

multicmd

-

Run multiple dfhack commands. The argument is split around the -character ; and all parts are run sequencially as independent -dfhack commands. Useful for hotkeys.

-

Example:

-
-multicmd locate-ore iron ; digv
-
-
-
-

position

-

Reports the current time: date, clock time, month, and season. Also reports -location: z-level, cursor position, window size, and mouse location.

-
-
-

putontable

-

Makes item appear on the table, like in adventure mode shops. Arguments: '-a' -or '--all' for all items.

-
-
-

quicksave

-

If called in dwarf mode, makes DF immediately auto-save the game by setting a flag -normally used in seasonal auto-save.

-
-
-

remove-stress

-

Sets stress to -1,000,000; the normal range is 0 to 500,000 with very stable or very stressed dwarves taking on negative or greater values respectively. Applies to the selected unit, or use "remove-stress -all" to apply to all units.

-
-
-

setfps

-

Run setfps <number> to set the FPS cap at runtime, in case you want to watch -combat in slow motion or something :)

-
-
-

siren

-

Wakes up sleeping units, cancels breaks and stops parties either everywhere, -or in the burrows given as arguments. In return, adds bad thoughts about -noise, tiredness and lack of protection. Also, the units with interrupted -breaks will go on break again a lot sooner. The script is intended for -emergencies, e.g. when a siege appears, and all your military is partying.

-
-
-

soundsense-season

-

It is a well known issue that Soundsense cannot detect the correct -current season when a savegame is loaded and has to play random -season music until a season switch occurs.

-

This script registers a hook that prints the appropriate string -to gamelog.txt on every map load to fix this. For best results -call the script from dfhack.init.

-
-
-

source

-

Create an infinite magma or water source or drain on a tile.

-

This script registers a map tile as a liquid source, and every 12 game ticks -that tile receives or remove 1 new unit of flow based on the configuration.

-

Place the game cursor where you want to create the source (must be a -flow-passable tile, and not too high in the sky) and call:

-
-source add [magma|water] [0-7]
-
-

The number argument is the target liquid level (0 = drain, 7 = source).

-

To add more than 1 unit everytime, call the command again on the same spot.

-

To delete one source, place the cursor over its tile and use delete. -To remove all existing sources, call source clear.

-

The list argument shows all existing sources.

-

Ex:

-
-source add water     - water source
-source add magma 7   - magma source
-source add water 0   - water drain
-
-
-
-

superdwarf

-

Similar to fastdwarf, per-creature.

-

To make any creature superfast, target it ingame using 'v' and:

-
-superdwarf add
-
-

Other options available: del, clear, list.

-

This plugin also shortens the 'sleeping' and 'on break' periods of targets.

-
-
-

stripcaged

-

For dumping items inside cages. Will mark selected items for dumping, then -a dwarf may come and actually dump it. See also autodump.

-

With the items argument, only dumps items laying in the cage, excluding -stuff worn by caged creatures. weapons will dump worn weapons, armor -will dump everything worn by caged creatures (including armor and clothing), -and all will dump everything, on a creature or not.

-

stripcaged list will display on the dfhack console the list of all cages -and their item content.

-

Without further arguments, all commands work on all cages and animal traps on -the map. With the here argument, considers only the in-game selected cage -(or the cage under the game cursor). To target only specific cages, you can -alternatively pass cage IDs as arguments:

-
-stripcaged weapons 25321 34228
-
-
-
-

teleport

-

Teleports a unit to given coordinates.

-

Examples:

-
-teleport -showunitid                 - prints unitid beneath cursor
-teleport -showpos                    - prints coordinates beneath cursor
-teleport -unit 1234 -x 56 -y 115 -z 26  - teleports unit 1234 to 56,115,26
-
-
-
-

undump-buildings

-

Undesignates building base materials for dumping.

-
-
-
-

modtools

-

These scripts are mostly useful for raw modders and scripters. They all have -standard arguments: arguments are of the form tool -argName1 argVal1 --argName2 argVal2. This is equivalent to tool -argName2 argVal2 -argName1 -argVal1. It is not necessary to provide a value to an argument name: tool --argName3 is fine. Supplying the same argument name multiple times will -result in an error. Argument names are preceded with a dash. The -help -argument will print a descriptive usage string describing the nature of the -arguments. For multiple word argument values, brackets must be used: tool --argName4 [ sadf1 sadf2 sadf3 ]. In order to allow passing literal braces as -part of the argument, backslashes are used: tool -argName4 [ \] asdf \foo ] -sets argName4 to \] asdf foo. The *-trigger scripts have a similar -policy with backslashes.

- -
-
-

In-game interface tools

-

These tools work by displaying dialogs or overlays in the game window, and -are mostly implemented by lua scripts.

-
-

Note

-

In order to avoid user confusion, as a matter of policy all these tools -display the word "DFHack" on the screen somewhere while active.

-

When that is not appropriate because they merely add keybinding hints to -existing DF screens, they deliberately use red instead of green for the key.

-

As an exception, the tweak plugin described above does not follow this -guideline because it arguably just fixes small usability bugs in the game UI.

-

All of these tools are disabled by default - in order to make them available, -you must enable the plugins which provide them.

-
-
-

Dwarf Manipulator

-

Implemented by the 'manipulator' plugin.

-

To activate, open the unit screen and press 'l'.

-images/manipulator.png -

This tool implements a Dwarf Therapist-like interface within the game UI. The -far left column displays the unit's Happiness (color-coded based on its -value), Name, Profession/Squad, and the right half of the screen displays each -dwarf's labor settings and skill levels (0-9 for Dabbling thru Professional, A-E for -Great thru Grand Master, and U-Z for Legendary thru Legendary+5).

-

Cells with teal backgrounds denote skills not controlled by labors, e.g. -military and social skills.

-images/manipulator2.png -

Press t to toggle between Profession and Squad view.

-images/manipulator3.png -

Use the arrow keys or number pad to move the cursor around, holding Shift to -move 10 tiles at a time.

-

Press the Z-Up (<) and Z-Down (>) keys to move quickly between labor/skill -categories. The numpad Z-Up and Z-Down keys seek to the first or last unit -in the list. Backspace seeks to the top left corner.

-

Press Enter to toggle the selected labor for the selected unit, or Shift+Enter -to toggle all labors within the selected category.

-

Press the +- keys to sort the unit list according to the currently selected -skill/labor, and press the */ keys to sort the unit list by Name, Profession/Squad, -Happiness, or Arrival order (using Tab to select which sort method to use here).

-

With a unit selected, you can press the "v" key to view its properties (and -possibly set a custom nickname or profession) or the "c" key to exit -Manipulator and zoom to its position within your fortress.

-

The following mouse shortcuts are also available:

-
    -
  • Click on a column header to sort the unit list. Left-click to sort it in one -direction (descending for happiness or labors/skills, ascending for name, -profession or squad) and right-click to sort it in the opposite direction.
  • -
  • Left-click on a labor cell to toggle that labor. Right-click to move the -cursor onto that cell instead of toggling it.
  • -
  • Left-click on a unit's name, profession or squad to view its properties.
  • -
  • Right-click on a unit's name, profession or squad to zoom to it.
  • -
-

Pressing ESC normally returns to the unit screen, but Shift-ESC would exit -directly to the main dwarf mode screen.

-
- -
-

AutoMaterial

-

Implemented by the 'automaterial' plugin.

-

This makes building constructions (walls, floors, fortifications, etc) a little bit -easier by saving you from having to trawl through long lists of materials each time -you place one.

-

Firstly, it moves the last used material for a given construction type to the top of -the list, if there are any left. So if you build a wall with chalk blocks, the next -time you place a wall the chalk blocks will be at the top of the list, regardless of -distance (it only does this in "grouped" mode, as individual item lists could be huge). -This should mean you can place most constructions without having to search for your -preferred material type.

-images/automaterial-mat.png -

Pressing 'a' while highlighting any material will enable that material for "auto select" -for this construction type. You can enable multiple materials as autoselect. Now the next -time you place this type of construction, the plugin will automatically choose materials -for you from the kinds you enabled. If there is enough to satisfy the whole placement, -you won't be prompted with the material screen - the construction will be placed and you -will be back in the construction menu as if you did it manually.

-

When choosing the construction placement, you will see a couple of options:

-images/automaterial-pos.png -

Use 'a' here to temporarily disable the material autoselection, e.g. if you need -to go to the material selection screen so you can toggle some materials on or off.

-

The other option (auto type selection, off by default) can be toggled on with 't'. If you -toggle this option on, instead of returning you to the main construction menu after selecting -materials, it returns you back to this screen. If you use this along with several autoselect -enabled materials, you should be able to place complex constructions more conveniently.

-
-
-

Stockpile Automation

-

Enable the automelt or autotrade plugins in your dfhack.init with:

-
-enable automelt
-enable autotrade
-
-

When querying a stockpile, options will appear to toggle automelt and/or autotrade for this stockpile. -When automelt is enabled for a stockpile, any meltable items placed in it will be designated to be melted. -When autotrade is enabled for a stockpile, any items placed in it will be designated to be taken to the Trade Depot whenever merchants are on the map.

-
-
-

Track Stop Menu

-

The q menu of track stops is completely blank by default. To enable one:

-
-enable trackstop
-
-

This allows you to view and/or change the track stop's friction and dump direction settings. -It re-uses the keybindings from the track stop building interface:

-
    -
  • BUILDING_TRACK_STOP_FRICTION_UP
  • -
  • BUILDING_TRACK_STOP_FRICTION_DOWN
  • -
  • BUILDING_TRACK_STOP_DUMP
  • -
-
-
-

gui/advfort

-

This script allows to perform jobs in adventure mode. For more complete help -press '?' while script is running. It's most confortable to use this as a -keybinding. (e.g. keybinding set Ctrl-T gui/advfort). Possible arguments:

-
    -
  • -a or --nodfassign - uses different method to assign items.
  • -
  • -i or --inventory - checks inventory for possible items to use in the job.
  • -
  • -c or --cheat - relaxes item requirements for buildings (e.g. walls from bones). -implies -a
  • -
  • job - selects that job (e.g. Dig or FellTree)
  • -
-

An example of player digging in adventure mode:

-images/advfort.png -
-

DISCLAIMER

-

advfort changes only persist in non procedural sites. Namely: player forts, caves, camps.

-
-
-
-

gui/assign-rack

-

Bind to a key (the example config uses P), and activate when viewing a weapon -rack in the 'q' mode.

-images/assign-rack.png -

This script is part of a group of related fixes to make the armory storage -work again. The existing issues are:

-
    -
  • Weapon racks have to each be assigned to a specific squad, like with -beds/boxes/armor stands and individual squad members, but nothing in -the game does this. This issue is what this script addresses.
  • -
  • Even if assigned by the script, the game will unassign the racks again without a binary patch. -This patch is called weaponrack-unassign, and can be applied via -the binpatch program, or the matching script. See the bug report for more info.
  • -
-
    -
  • Haulers still take equipment stored in the armory away to the stockpiles, -unless the fix-armory plugin above is used.
  • -
-

The script interface simply lets you designate one of the squads that -are assigned to the barracks/armory containing the selected stand as -the intended user. In order to aid in the choice, it shows the number -of currently assigned racks for every valid squad.

-
-
-

gui/choose-weapons

-

Bind to a key (the example config uses Ctrl-W), and activate in the Equip->View/Customize -page of the military screen.

-

Depending on the cursor location, it rewrites all 'individual choice weapon' entries -in the selected squad or position to use a specific weapon type matching the assigned -unit's top skill. If the cursor is in the rightmost list over a weapon entry, it rewrites -only that entry, and does it even if it is not 'individual choice'.

-

Rationale: individual choice seems to be unreliable when there is a weapon shortage, -and may lead to inappropriate weapons being selected.

-
-
-

gui/clone-uniform

-

Bind to a key (the example config uses Ctrl-C), and activate in the Uniforms -page of the military screen with the cursor in the leftmost list.

-

When invoked, the script duplicates the currently selected uniform template, -and selects the newly created copy.

-
-
-

gui/companion-order

-

A script to issue orders for companions. Select companions with lower case chars, issue orders with upper -case. Must be in look or talk mode to issue command on tile.

-images/companion-order.png -
    -
  • move - orders selected companions to move to location. If companions are following they will move no more than 3 tiles from you.
  • -
  • equip - try to equip items on the ground.
  • -
  • pick-up - try to take items into hand (also wield)
  • -
  • unequip - remove and drop equipment
  • -
  • unwield - drop held items
  • -
  • wait - temporarily remove from party
  • -
  • follow - rejoin the party after "wait"
  • -
  • leave - remove from party (can be rejoined by talking)
  • -
-
-
-

gui/gm-editor

-

There are three ways to open this editor:

-
    -
  • using gui/gm-editor command/keybinding - opens editor on what is selected -or viewed (e.g. unit/item description screen)
  • -
  • using gui/gm-editor <lua command> - executes lua command and opens editor on -its results (e.g. gui/gm-editor "df.global.world.items.all" shows all items)
  • -
  • using gui/gm-editor dialog - shows an in game dialog to input lua command. Works -the same as version above.
  • -
-images/gm-editor.png -

This editor allows to change and modify almost anything in df. Press '?' for an -in-game help.

-
-
-

Hotkeys

-

Opens an in-game screen showing DFHack keybindings that are valid in the current mode.

-images/hotkeys.png -

Type hotkeys into the DFHack console to open the screen, or bind the command to a -globally active hotkey in dfhack.init, e.g.:

-
-keybinding add Ctrl-F1 hotkeys
-
-
-
-

Stockpile Automation

-
-
Enable the autodump plugin in your dfhack.init with
-
enable autodump
-
-

When querying a stockpile an option will appear to toggle autodump for this stockpile. -Any items placed in this stockpile will be designated to be dumped.

-
-
-

gui/liquids

-

To use, bind to a key (the example config uses Alt-L) and activate in the 'k' mode.

-images/liquids.png -

This script is a gui front-end to the liquids plugin and works similar to it, -allowing you to add or remove water & magma, and create obsidian walls & floors. -Note that there is no undo support, and that bugs in this plugin have been -known to create pathfinding problems and heat traps.

-

The b key changes how the affected area is selected. The default Rectangle -mode works by selecting two corners like any ordinary designation. The p -key chooses between adding water, magma, obsidian walls & floors, or just -tweaking flags.

-

When painting liquids, it is possible to select the desired level with +-, -and choose between setting it exactly, only increasing or only decreasing -with s.

-

In addition, f allows disabling or enabling the flowing water computations -for an area, and r operates on the "permanent flow" property that makes -rivers power water wheels even when full and technically not flowing.

-

After setting up the desired operations using the described keys, use Enter to apply them.

-
-
-

gui/mechanisms

-

To use, bind to a key (the example config uses Ctrl-M) and activate in the 'q' mode.

-images/mechanisms.png -

Lists mechanisms connected to the building, and their links. Navigating the list centers -the view on the relevant linked buildings.

-

To exit, press ESC or Enter; ESC recenters on the original building, while Enter leaves -focus on the current one. Shift-Enter has an effect equivalent to pressing Enter, and then -re-entering the mechanisms ui.

-
-
-

gui/mod-manager

-

A simple way to install and remove small mods.

-

It looks for specially formatted mods in df subfolder 'mods'. Mods are not -included, but some examples are available here.

-images/mod-manager.png -
-
-

gui/rename

-

Backed by the rename plugin, this script allows entering the desired name -via a simple dialog in the game ui.

-
    -
  • gui/rename [building] in 'q' mode changes the name of a building.

    -images/rename-bld.png -

    The selected building must be one of stockpile, workshop, furnace, trap, or siege engine. -It is also possible to rename zones from the 'i' menu.

    -
  • -
  • gui/rename [unit] with a unit selected changes the nickname.

    -

    Unlike the built-in interface, this works even on enemies and animals.

    -
  • -
  • gui/rename unit-profession changes the selected unit's custom profession name.

    -images/rename-prof.png -

    Likewise, this can be applied to any unit, and when used on animals it overrides -their species string.

    -
  • -
-

The building or unit options are automatically assumed when in relevant ui state.

-

The example config binds building/unit rename to Ctrl-Shift-N, and -unit profession change to Ctrl-Shift-T.

-
-
-

gui/room-list

-

To use, bind to a key (the example config uses Alt-R) and activate in the 'q' mode, -either immediately or after opening the assign owner page.

-images/room-list.png -

The script lists other rooms owned by the same owner, or by the unit selected in the assign -list, and allows unassigning them.

-
-
-

gui/guide-path

-

Bind to a key (the example config uses Alt-P), and activate in the Hauling menu with -the cursor over a Guide order.

-images/guide-path.png -

The script displays the cached path that will be used by the order; the game -computes it when the order is executed for the first time.

-
-
-

gui/workflow

-

Bind to a key (the example config uses Alt-W), and activate with a job selected -in a workshop in the 'q' mode.

-images/workflow.png -

This script provides a simple interface to constraints managed by the workflow -plugin. When active, it displays a list of all constraints applicable to the -current job, and their current status.

-

A constraint specifies a certain range to be compared against either individual -item or whole stack count, an item type and optionally a material. When the -current count is below the lower bound of the range, the job is resumed; if it -is above or equal to the top bound, it will be suspended. Within the range, the -specific constraint has no effect on the job; others may still affect it.

-

Pressing 'I' switches the current constraint between counting stacks or items. -Pressing 'R' lets you input the range directly; 'e', 'r', 'd', 'f' adjust the -bounds by 5, 10, or 20 depending on the direction and the 'I' setting (counting -items and expanding the range each gives a 2x bonus).

-

Pressing 'A' produces a list of possible outputs of this job as guessed by -workflow, and lets you create a new constraint by choosing one as template. If you -don't see the choice you want in the list, it likely means you have to adjust -the job material first using job item-material or gui/workshop-job, -as described in workflow documentation above. In this manner, this feature -can be used for troubleshooting jobs that don't match the right constraints.

-images/workflow-new1.png -

If you select one of the outputs with Enter, the matching constraint is simply -added to the list. If you use Shift-Enter, the interface proceeds to the -next dialog, which allows you to edit the suggested constraint parameters to -suit your need, and set the item count range.

-images/workflow-new2.png -

Pressing 'S' (or, with the example config, Alt-W in the 'z' stocks screen) -opens the overall status screen, which was copied from the C++ implementation -by falconne for better integration with the rest of the lua script:

-images/workflow-status.png -

This screen shows all currently existing workflow constraints, and allows -monitoring and/or changing them from one screen. The constraint list can -be filtered by typing text in the field below.

-

The color of the stock level number indicates how "healthy" the stock level -is, based on current count and trend. Bright green is very good, green is good, -red is bad, bright red is very bad.

-

The limit number is also color-coded. Red means that there are currently no -workshops producing that item (i.e. no jobs). If it's yellow, that means the -production has been delayed, possibly due to lack of input materials.

-

The chart on the right is a plot of the last 14 days (28 half day plots) worth -of stock history for the selected item, with the rightmost point representing -the current stock value. The bright green dashed line is the target -limit (maximum) and the dark green line is that minus the gap (minimum).

-
-
-

gui/workshop-job

-

Bind to a key (the example config uses Alt-A), and activate with a job selected in -a workshop in the 'q' mode.

-images/workshop-job.png -

The script shows a list of the input reagents of the selected job, and allows changing -them like the job item-type and job item-material commands.

-

Specifically, pressing the 'i' key pops up a dialog that lets you select an item -type from a list.

-images/workshop-job-item.png -

Pressing 'm', unless the item type does not allow a material, -lets you choose a material.

-images/workshop-job-material.png -

Since there are a lot more materials than item types, this dialog is more complex -and uses a hierarchy of sub-menus. List choices that open a sub-menu are marked -with an arrow on the left.

-
-

Warning

-

Due to the way input reagent matching works in DF, you must select an item type -if you select a material, or the material will be matched incorrectly in some cases. -If you press 'm' without choosing an item type, the script will auto-choose it -if there is only one valid choice, or pop up an error message box instead of the -material selection dialog.

-
-

Note that both materials and item types presented in the dialogs are filtered -by the job input flags, and even the selected item type for material selection, -or material for item type selection. Many jobs would let you select only one -input item type.

-

For example, if you choose a plant input item type for your prepare meal job, -it will only let you select cookable materials.

-

If you choose a barrel item instead (meaning things stored in barrels, like -drink or milk), it will let you select any material, since in this case the -material is matched against the barrel itself. Then, if you select, say, iron, -and then try to change the input item type, now it won't let you select plant; -you have to unset the material first.

-
-
-
-

Behavior Mods

-

These plugins, when activated via configuration UI or by detecting certain -structures in RAWs, modify the game engine behavior concerning the target -objects to add features not otherwise present.

-
-

DISCLAIMER

-

The plugins in this section have mostly been created for fun as an interesting -technical challenge, and do not represent any long-term plans to produce more -similar modifications of the game.

-
-
-

Siege Engine

-

The siege-engine plugin enables siege engines to be linked to stockpiles, and -aimed at an arbitrary rectangular area across Z levels, instead of the original -four directions. Also, catapults can be ordered to load arbitrary objects, not -just stones.

-
-

Rationale

-

Siege engines are a very interesting feature, but sadly almost useless in the current state -because they haven't been updated since 2D and can only aim in four directions. This is an -attempt to bring them more up to date until Toady has time to work on it. Actual improvements, -e.g. like making siegers bring their own, are something only Toady can do.

-
-
-

Configuration UI

-

The configuration front-end to the plugin is implemented by the gui/siege-engine -script. Bind it to a key (the example config uses Alt-A) and activate after selecting -a siege engine in 'q' mode.

-images/siege-engine.png -

The main mode displays the current target, selected ammo item type, linked stockpiles and -the allowed operator skill range. The map tile color is changed to signify if it can be -hit by the selected engine: green for fully reachable, blue for out of range, red for blocked, -yellow for partially blocked.

-

Pressing 'r' changes into the target selection mode, which works by highlighting two points -with Enter like all designations. When a target area is set, the engine projectiles are -aimed at that area, or units within it (this doesn't actually change the original aiming -code, instead the projectile trajectory parameters are rewritten as soon as it appears).

-

After setting the target in this way for one engine, you can 'paste' the same area into others -just by pressing 'p' in the main page of this script. The area to paste is kept until you quit -DF, or select another area manually.

-

Pressing 't' switches to a mode for selecting a stockpile to take ammo from.

-

Exiting from the siege engine script via ESC reverts the view to the state prior to starting -the script. Shift-ESC retains the current viewport, and also exits from the 'q' mode to main -menu.

-
-
-
-

Power Meter

-

The power-meter plugin implements a modified pressure plate that detects power being -supplied to gear boxes built in the four adjacent N/S/W/E tiles.

-

The configuration front-end is implemented by the gui/power-meter script. Bind it to a -key (the example config uses Ctrl-Shift-M) and activate after selecting Pressure Plate -in the build menu.

-images/power-meter.png -

The script follows the general look and feel of the regular pressure plate build -configuration page, but configures parameters relevant to the modded power meter building.

-
-
-

Steam Engine

-

The steam-engine plugin detects custom workshops with STEAM_ENGINE in -their token, and turns them into real steam engines.

-
-

Rationale

-

The vanilla game contains only water wheels and windmills as sources of -power, but windmills give relatively little power, and water wheels require -flowing water, which must either be a real river and thus immovable and -limited in supply, or actually flowing and thus laggy.

-

Steam engines are an alternative to water reactors that actually makes -sense, and hopefully doesn't lag. Also, unlike e.g. animal treadmills, -it can be done just by combining existing features of the game engine -in a new way with some glue code and a bit of custom logic.

-
-
-

Construction

-

The workshop needs water as its input, which it takes via a -passable floor tile below it, like usual magma workshops do. -The magma version also needs magma.

-
-

ISSUE

-

Since this building is a machine, and machine collapse -code cannot be hooked, it would collapse over true open space. -As a loophole, down stair provides support to machines, while -being passable, so use them.

-
-

After constructing the building itself, machines can be connected -to the edge tiles that look like gear boxes. Their exact position -is extracted from the workshop raws.

-
-

ISSUE

-

Like with collapse above, part of the code involved in -machine connection cannot be hooked. As a result, the workshop -can only immediately connect to machine components built AFTER it. -This also means that engines cannot be chained without intermediate -short axles that can be built later than both of the engines.

-
-
-
-

Operation

-

In order to operate the engine, queue the Stoke Boiler job (optionally -on repeat). A furnace operator will come, possibly bringing a bar of fuel, -and perform it. As a result, a "boiling water" item will appear -in the 't' view of the workshop.

-
-

Note

-

The completion of the job will actually consume one unit -of the appropriate liquids from below the workshop. This means -that you cannot just raise 7 units of magma with a piston and -have infinite power. However, liquid consumption should be slow -enough that water can be supplied by a pond zone bucket chain.

-
-

Every such item gives 100 power, up to a limit of 300 for coal, -and 500 for a magma engine. The building can host twice that -amount of items to provide longer autonomous running. When the -boiler gets filled to capacity, all queued jobs are suspended; -once it drops back to 3+1 or 5+1 items, they are re-enabled.

-

While the engine is providing power, steam is being consumed. -The consumption speed includes a fixed 10% waste rate, and -the remaining 90% are applied proportionally to the actual -load in the machine. With the engine at nominal 300 power with -150 load in the system, it will consume steam for actual -300*(10% + 90%*150/300) = 165 power.

-

Masterpiece mechanism and chain will decrease the mechanical -power drawn by the engine itself from 10 to 5. Masterpiece -barrel decreases waste rate by 4%. Masterpiece piston and pipe -decrease it by further 4%, and also decrease the whole steam -use rate by 10%.

-
-
-

Explosions

-

The engine must be constructed using barrel, pipe and piston -from fire-safe, or in the magma version magma-safe metals.

-

During operation weak parts get gradually worn out, and -eventually the engine explodes. It should also explode if -toppled during operation by a building destroyer, or a -tantruming dwarf.

-
-
-

Save files

-

It should be safe to load and view engine-using fortresses -from a DF version without DFHack installed, except that in such -case the engines won't work. However actually making modifications -to them, or machines they connect to (including by pulling levers), -can easily result in inconsistent state once this plugin is -available again. The effects may be as weird as negative power -being generated.

-
-
-
-

Add Spatter

-

This plugin makes reactions with names starting with SPATTER_ADD_ -produce contaminants on the items instead of improvements. The produced -contaminants are immune to being washed away by water or destroyed by -the clean items command.

-

The plugin is intended to give some use to all those poisons that can -be bought from caravans. :)

-

To be really useful this needs patches from bug 808, tweak fix-dimensions -and tweak advmode-contained.

-
-
-
- - diff --git a/Compile.rst b/docs/Compile.rst similarity index 100% rename from Compile.rst rename to docs/Compile.rst diff --git a/Contributing.rst b/docs/Contributing.rst similarity index 100% rename from Contributing.rst rename to docs/Contributing.rst diff --git a/Contributors.rst b/docs/Contributors.rst similarity index 100% rename from Contributors.rst rename to docs/Contributors.rst diff --git a/Lua API.rst b/docs/Lua API.rst similarity index 100% rename from Lua API.rst rename to docs/Lua API.rst diff --git a/Readme.rst b/docs/Readme.rst similarity index 100% rename from Readme.rst rename to docs/Readme.rst diff --git a/images/advfort.png b/docs/images/advfort.png similarity index 100% rename from images/advfort.png rename to docs/images/advfort.png diff --git a/images/assign-rack.png b/docs/images/assign-rack.png similarity index 100% rename from images/assign-rack.png rename to docs/images/assign-rack.png diff --git a/images/automaterial-mat.png b/docs/images/automaterial-mat.png similarity index 100% rename from images/automaterial-mat.png rename to docs/images/automaterial-mat.png diff --git a/images/automaterial-pos.png b/docs/images/automaterial-pos.png similarity index 100% rename from images/automaterial-pos.png rename to docs/images/automaterial-pos.png diff --git a/images/command-prompt.png b/docs/images/command-prompt.png similarity index 100% rename from images/command-prompt.png rename to docs/images/command-prompt.png diff --git a/images/companion-order.png b/docs/images/companion-order.png similarity index 100% rename from images/companion-order.png rename to docs/images/companion-order.png diff --git a/images/gm-editor.png b/docs/images/gm-editor.png similarity index 100% rename from images/gm-editor.png rename to docs/images/gm-editor.png diff --git a/images/guide-path.png b/docs/images/guide-path.png similarity index 100% rename from images/guide-path.png rename to docs/images/guide-path.png diff --git a/images/hotkeys.png b/docs/images/hotkeys.png similarity index 100% rename from images/hotkeys.png rename to docs/images/hotkeys.png diff --git a/images/liquids.png b/docs/images/liquids.png similarity index 100% rename from images/liquids.png rename to docs/images/liquids.png diff --git a/images/manipulator.png b/docs/images/manipulator.png similarity index 100% rename from images/manipulator.png rename to docs/images/manipulator.png diff --git a/images/manipulator2.png b/docs/images/manipulator2.png similarity index 100% rename from images/manipulator2.png rename to docs/images/manipulator2.png diff --git a/images/manipulator3.png b/docs/images/manipulator3.png similarity index 100% rename from images/manipulator3.png rename to docs/images/manipulator3.png diff --git a/images/mechanisms.png b/docs/images/mechanisms.png similarity index 100% rename from images/mechanisms.png rename to docs/images/mechanisms.png diff --git a/images/mod-manager.png b/docs/images/mod-manager.png similarity index 100% rename from images/mod-manager.png rename to docs/images/mod-manager.png diff --git a/images/power-meter.png b/docs/images/power-meter.png similarity index 100% rename from images/power-meter.png rename to docs/images/power-meter.png diff --git a/images/rename-bld.png b/docs/images/rename-bld.png similarity index 100% rename from images/rename-bld.png rename to docs/images/rename-bld.png diff --git a/images/rename-prof.png b/docs/images/rename-prof.png similarity index 100% rename from images/rename-prof.png rename to docs/images/rename-prof.png diff --git a/images/rendermax.png b/docs/images/rendermax.png similarity index 100% rename from images/rendermax.png rename to docs/images/rendermax.png diff --git a/images/room-list.png b/docs/images/room-list.png similarity index 100% rename from images/room-list.png rename to docs/images/room-list.png diff --git a/images/search-stockpile.png b/docs/images/search-stockpile.png similarity index 100% rename from images/search-stockpile.png rename to docs/images/search-stockpile.png diff --git a/images/search.png b/docs/images/search.png similarity index 100% rename from images/search.png rename to docs/images/search.png diff --git a/images/siege-engine.png b/docs/images/siege-engine.png similarity index 100% rename from images/siege-engine.png rename to docs/images/siege-engine.png diff --git a/images/tweak-mil-color.png b/docs/images/tweak-mil-color.png similarity index 100% rename from images/tweak-mil-color.png rename to docs/images/tweak-mil-color.png diff --git a/images/tweak-plate.png b/docs/images/tweak-plate.png similarity index 100% rename from images/tweak-plate.png rename to docs/images/tweak-plate.png diff --git a/images/workflow-new1.png b/docs/images/workflow-new1.png similarity index 100% rename from images/workflow-new1.png rename to docs/images/workflow-new1.png diff --git a/images/workflow-new2.png b/docs/images/workflow-new2.png similarity index 100% rename from images/workflow-new2.png rename to docs/images/workflow-new2.png diff --git a/images/workflow-status.png b/docs/images/workflow-status.png similarity index 100% rename from images/workflow-status.png rename to docs/images/workflow-status.png diff --git a/images/workflow.png b/docs/images/workflow.png similarity index 100% rename from images/workflow.png rename to docs/images/workflow.png diff --git a/images/workshop-job-item.png b/docs/images/workshop-job-item.png similarity index 100% rename from images/workshop-job-item.png rename to docs/images/workshop-job-item.png diff --git a/images/workshop-job-material.png b/docs/images/workshop-job-material.png similarity index 100% rename from images/workshop-job-material.png rename to docs/images/workshop-job-material.png diff --git a/images/workshop-job.png b/docs/images/workshop-job.png similarity index 100% rename from images/workshop-job.png rename to docs/images/workshop-job.png diff --git a/fixTexts.sh b/fixTexts.sh deleted file mode 100755 index 4d025121b..000000000 --- a/fixTexts.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/bash -# regenerate documentation after editing the .rst files. Requires python and docutils. - -force= -reset= -while [ $# -gt 0 ] -do - case "$1" in - --force) force=1 - ;; - --reset) reset=1 - ;; - esac - shift -done - -rst2html=$(which rst2html || which rst2html.py) -if [[ -z "$rst2html" ]]; then - echo "Docutils not found: See http://docutils.sourceforge.net/" - exit 1 -fi -rst2html_version=$("$rst2html" --version | cut -d' ' -f3) - -if [[ $(echo $rst2html_version | cut -d. -f2) -lt 12 ]]; then - echo "You are using docutils $rst2html_version. Docutils 0.12+ is recommended -to build these documents." - read -r -n1 -p "Continue? [y/N] " reply - echo - if [[ ! $reply =~ ^[Yy]$ ]]; then - exit - fi -fi - -cd `dirname $0` -status=0 - -function process() { - if [ -n "$reset" ]; then - git checkout -- "$2" - elif [ "$1" -nt "$2" ] || [ -n "$force" ]; then - echo -n "Updating $2... " - if "$rst2html" --no-generator --no-datestamp "$1" "$2"; then - echo "Done" - else - status=1 - fi - else - echo "$2 - up to date." - fi -} - -process Readme.rst Readme.html -process Compile.rst Compile.html -process Lua\ API.rst Lua\ API.html -process Contributors.rst Contributors.html -process Contributing.rst Contributing.html -exit $status diff --git a/images/hotkeys.PNG b/images/hotkeys.PNG deleted file mode 100644 index bdf9c76b8..000000000 Binary files a/images/hotkeys.PNG and /dev/null differ diff --git a/index.rst b/index.rst index d9e648ac4..a7ea14ab6 100644 --- a/index.rst +++ b/index.rst @@ -1,8 +1,3 @@ -.. DFHack documentation master file, created by - sphinx-quickstart on Tue Sep 22 17:34:54 2015. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - Welcome to DFHack's documentation! ================================== @@ -11,12 +6,9 @@ Contents: .. toctree:: :maxdepth: 2 - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` + docs/Readme + docs/Contributing + docs/Contributors + docs/Compile + docs/Lua API