Dfhack
Dfhack
Release 0.47.04-r2
2020-08-27
Contents
I Quick Links 3
II User Manual 7
1 Introduction and Overview 9
2 Installing DFHack 11
3 DFHack Core 15
4 DFHack Plugins 25
5 DFHack Scripts 83
i
ii
DFHack Documentation, Release 0.47.04-r2
DFHack is a memory editing library for Dwarf Fortress that provides a unified, cross-platform environment where
tools can be developed to extend the game. The default distribution contains a variety of tools, including bugfixes,
interface improvements, automation tools, modding tools, and more. There are also a variety of third-party tools
available.
Contents 1
DFHack Documentation, Release 0.47.04-r2
2 Contents
Part I
Quick Links
3
DFHack Documentation, Release 0.47.04-r2
• Downloads
• Installation guide
• Source code (important: read Compiling DFHack before attempting to build from source)
• Bay 12 forums thread
• Bug tracker
5
DFHack Documentation, Release 0.47.04-r2
6
Part II
User Manual
7
CHAPTER 1
DFHack is a Dwarf Fortress memory access library, distributed with a wide variety of useful scripts and plugins.
The project is currently hosted on GitHub, and can be downloaded from the releases page - see Installing DFHack for
installation instructions. This is also where the DFHack bug tracker is hosted.
All new releases are announced in the Bay12 forums thread, which is also a good place for discussion and questions.
For users, DFHack 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 for Modders 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 open-source licences, contributions are welcome.
Contents
• Getting started
• Troubleshooting
9
DFHack Documentation, Release 0.47.04-r2
• Basic interaction with DFHack involves entering commands into the console. To learn what commands are
available, you can keep reading this documentation or skip ahead and use the ls and help commands.
• Another way to interact with DFHack is to set in-game keybindings for certain commands. Many of the newer
and user-friendly tools are designed to be used this way.
• Commands can also run at startup via init files, on in batches at other times with the script command.
• Finally, some commands are persistent once enabled, and will sit in the background managing or changing some
aspect of the game if you enable them.
1.2 Troubleshooting
Installing DFHack
• Requirements
– Windows
– Linux
– macOS
• Downloading DFHack
• Installing DFHack
• Uninstalling DFHack
• Upgrading DFHack
• Pre-packaged DFHack installations
2.1 Requirements
DFHack supports Windows, Linux, and macOS, and both 64-bit and 32-bit builds of Dwarf Fortress.
DFHack releases generally only support the version of Dwarf Fortress that they are named after. For example, DFHack
0.40.24-r5 only supported DF 0.40.24. DFHack releases never support newer versions of DF, because DFHack requires
data about DF that is only possible to obtain after DF has been released. Occasionally, DFHack releases will be able to
maintain support for older versions of DF - for example, DFHack 0.34.11-r5 supported both DF 0.34.11 and 0.34.10.
For maximum stability, you should usually use the latest versions of both DF and DFHack.
2.1.1 Windows
• DFHack only supports the SDL version of Dwarf Fortress. The “legacy” version will not work with DFHack
(the “small” SDL version is acceptable, however).
11
DFHack Documentation, Release 0.47.04-r2
• Windows XP and older are not supported, due in part to a Visual C++ 2015 bug
The Windows build of DFHack should work under Wine on other operating systems, although this is not tested very
often. It is recommended to use the native build for your operating system instead.
2.1.2 Linux
Generally, DFHack should work on any modern Linux distribution. There are multiple release binaries provided - as of
DFHack 0.47.04-r1, there are built with GCC 7 and GCC 4.8 (as indicated by the gcc component of their filenames).
Using the newest build that works on your system is recommended. The GCC 4.8 build is built on Ubuntu 14.04 and
targets an older glibc, so it should work on older distributions.
In the event that none of the provided binaries work on your distribution, you may need to compile DFHack from
source.
2.1.3 macOS
Stable builds of DFHack are available on GitHub. GitHub has been known to change their layout periodically, but
as of July 2020, downloads are available at the bottom of the release notes for each release, under a section named
“Assets” (which you may have to expand). The name of the file indicates which DF version, platform, and architecture
the build supports - the platform and architecture (64-bit or 32-bit) must match your build of DF. The DF version
should also match your DF version - see above for details. For example:
• [Link] supports 64-bit DF on Windows
• [Link].bz2 supports 32-bit DF on Linux (see Linux for
details on the GCC version indicator)
The DFHack website also provides links to unstable builds. These files have a different naming scheme, but the same
restrictions apply (e.g. a file named Windows64 is for 64-bit Windows DF).
Warning: Do not download the source code from GitHub, either from the releases page or by clicking “Download
ZIP” on the repo homepage. This will give you an incomplete copy of the DFHack source code, which will not
work as-is. (If you want to compile DFHack instead of using a pre-built release, see Compiling DFHack for
instructions.)
When you download DFHack, you will end up with a release archive (a .zip file on Windows, or a .tar.bz2 file
on other platforms). Your operating system should have built-in utilities capable of extracting files from these archives.
The release archives contain several files and folders, including a hack folder, a dfhack-config folder, and a
[Link]-example file. To install DFHack, copy all of the files from the DFHack archive into the root DF
folder, which should already include a data folder and a raw folder, among other things. Some packs and other
redistributions of Dwarf Fortress may place DF in another folder, so ensure that the hack folder ends up next to the
data folder.
Note: On Windows, installing DFHack will overwrite [Link]. This is intentional and necessary for DFHack
to work, so be sure to choose to overwrite [Link] if prompted. (If you are not prompted, you may be installing
DFHack in the wrong place.)
Uninstalling DFHack essentially involves reversing what you did to install DFHack. On Windows, replace [Link]
with [Link] first. Then, you can remove any files that were part of the DFHack archive. DFHack does not
currently maintain a list of these files, so if you want to completely remove them, you should consult the DFHack
archive that you installed for a full list. Generally, any files left behind should not negatively affect DF.
The recommended approach to upgrade DFHack is to uninstall DFHack first, then install the new version. This will
ensure that any files that are only part of the older DFHack installation do not affect the new DFHack installation
(although this is unlikely to occur).
It is also possible to overwrite an existing DFHack installation in-place. To do this, follow the installation instructions
above, but overwrite all files that exist in the new DFHack archive (on Windows, this includes [Link] again).
Note: You may wish to make a backup of your dfhack-config folder first if you have made changes to it. Some
archive managers (e.g. Archive Utility on macOS) will overwrite the entire folder, removing any files that you have
added.
There are several packs available that include DF, DFHack, and other utilities. If you are new to Dwarf Fortress and
DFHack, these may be easier to set up. Note that these packs are not maintained by the DFHack team and vary in
their release schedules and contents. Some may make significant configuration changes, and some may not include
DFHack at all.
DFHack Core
Contents
• Command Implementation
• Using DFHack Commands
– The DFHack Console
– Using an OS terminal
• Built-in Commands
– alias
– cls
– die
– enable
– fpause
– help
– hide
– keybinding
– kill-lua
– load
– ls
– plug
– sc-script
– script
15
DFHack Documentation, Release 0.47.04-r2
– show
– type
– Other Commands
• Init Files
– dfhack*.init
– onLoad*.init
– onUnload*.init
– Other init files
• Environment variables
• Miscellaneous Notes
DFHack commands can be implemented in three ways, all of which are used in the same way:
builtin commands are implemented by the core of DFHack. They manage other DFHack tools, interpret
commands, and control basic aspects of DF (force pause or quit).
plugins are stored in hack/plugins/ and must be compiled with the same version of DFHack. They
are less flexible than scripts, but used for complex or ongoing tasks because they run faster.
scripts are Ruby or Lua scripts stored in hack/scripts/. Because they don’t need to be compiled,
scripts are more flexible about versions, and easier to distribute. Most third-party DFHack addons
are scripts.
The command line has some nice line editing capabilities, including history that’s preserved between different runs of
DF - use ↑ and ↓ to go through the history.
To include whitespace in the argument/s to some command, quote it in double quotes. To include a double quote
character, use \".
If the first non-whitespace character is :, the command is parsed in an alternative mode. The non-whitespace characters
following the : are the command name, and the remaining part of the line is used verbatim as the first argument. This
is very useful for the lua and ruby commands. As an example, the following two command lines are exactly equivalent:
DFHack commands can be run from an OS terminal at startup, using ‘+ args’, or at any other time using the
dfhack-run executable.
If DF/DFHack is started with arguments beginning with +, the remaining text is treated as a command in the DFHack
console. It is possible to use multiple such commands, which are split on +. For example:
The first example (*nix), load-save, skips the main menu and loads region1 immediately. The second (Windows)
example prints Hello! in the DFHack console, and enables workflow. Note that the :foo syntax for whitespace in
arguments is not compatible with ‘+ args’.
dfhack-run
If DF and DFHack are already running, calling dfhack-run my command in an external terminal is equiva-
lent to calling my command in the DFHack console. Direct use of the DFHack console is generally easier, but
dfhack-run can be useful in a variety of circumstances:
• if the console is unavailable
– with the init setting PRINT_MODE:TEXT
– while running an interactive command (e.g. liquids or tiletypes)
• from external programs or scripts
• if DF or DFHack are not responding
Examples:
./dfhack-run cursecheck
dfhack-run kill-lua
The first (*nix) example checks for vampires; the second (Windows) example uses kill-lua to stop a Lua script.
Note: dfhack-run attempts to connect to a server on TCP port 5000. If DFHack was unable to start this server,
dfhack-run will not be able to connect. This could happen if you have other software listening on port 5000, or if
you have multiple copies of DF running simultaneously. To assign a different port, see Server configuration.
The following commands are provided by the ‘core’ components of DFHack, rather than plugins or scripts.
• alias
• cls
• die
• enable
• fpause
• help
• hide
• keybinding
• kill-lua
• load
• ls
• plug
• sc-script
• script
• show
• type
• Other Commands
3.3.1 alias
The alias command allows configuring aliases to other DFHack commands. Aliases are resolved immediately
after built-in commands, which means that an alias cannot override a built-in command, but can override a command
implemented by a plugin or script.
Usage:
alias list lists all configured aliases
alias add <name> <command> [arguments...] adds an alias
alias replace <name> <command> [arguments...] replaces an existing alias with a new
command, or adds the alias if it does not already exist
alias delete <name> removes the specified alias
Aliases can be given additional arguments when created and invoked, which will be passed to the underlying command
in order. An example with devel/print-args:
3.3.2 cls
3.3.3 die
3.3.4 enable
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 such plugins or scripts 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. Passing plugin names to these commands will enable or disable the specified plugins. For example, to
enable the manipulator plugin:
enable manipulator
3.3.5 fpause
Forces DF to pause. This is useful when your FPS drops below 1 and you lose control of the game.
3.3.6 help
Most commands support using the help <command> built-in command to retrieve further help without having to
look at this document. ? <cmd> and man <cmd> are aliases.
Some commands (including many scripts) instead take help or ? as an option on their command line - ie <cmd>
help.
3.3.7 hide
3.3.8 keybinding
To set keybindings, use the built-in keybinding command. Like any other command it can be used at any time
from the console, but bindings are not remembered between runs of the game unless re-created in dfhack*.init.
Currently, any combinations of Ctrl/Alt/Shift with A-Z, 0-9, or F1-F12 are supported.
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[|context...]]
where the KEY part can be any recognized key 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. when in context foo/bar/baz, keybindings restricted to any of @foo/
bar/baz, @foo/bar, @foo or none will be active.
Multiple contexts can be specified by separating them with a pipe (|) - for example, @foo|bar|baz/foo would
match anything under @foo, @bar, or @baz/foo.
Interactive commands like liquids cannot be used as hotkeys.
3.3.9 kill-lua
Stops any currently-running Lua scripts. By default, scripts can only be interrupted every 256 instructions. Use
kill-lua force to interrupt the next instruction.
3.3.10 load
load, unload, and reload control whether a plugin is loaded into memory - note that plugins are loaded but
disabled unless you do something. Usage:
load|unload|reload PLUGIN|(-a|--all)
3.3.11 ls
ls does not list files like the Unix command, but rather available commands - first built in commands, then plugins,
and scripts at the end. Usage:
ls -a Also list scripts in subdirectories of hack/scripts/, which are generally not intended for direct
use.
ls <plugin> List subcommands for the given plugin.
3.3.12 plug
3.3.13 sc-script
Allows additional scripts to be run when certain events occur (similar to onLoad*.init scripts)
3.3.14 script
Reads a text file, and runs each line as a DFHack command as if it had been typed in by the user - treating the input
like an init file.
Some other tools, such as autobutcher and workflow, export their settings as the commands to create them - which are
later loaded with script
3.3.15 show
Shows the terminal window after it has been hidden. Only available on Windows. You’ll need to use it from a
keybinding set beforehand, or the in-game command-prompt.
3.3.16 type
The following commands are not built-in, but offer similarly useful functions.
• command-prompt
• hotkeys
• lua
• multicmd
• nopause
• quicksave
• ruby
• repeat
• dfhack*.init
• onLoad*.init
• onUnload*.init
• Other init files
DFHack allows users to automatically run commonly-used DFHack commands when DF is first loaded, when a game
is loaded, and when a game is unloaded.
Init scripts function the same way they would if the user manually typed in their contents, but are much more conve-
nient. In order to facilitate savegave portability, mod merging, and general organization of init files, DFHack supports
multiple init files both in the main DF directory and save-specific init files in the save folders.
DFHack looks for init files in three places each time they could be run:
1. The main DF directory
2. data/save/world/raw, where world is the current save, and
3. data/save/world/raw/objects
When reading commands from [Link] 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.
3.4.1 dfhack*.init
If your DF folder contains at least one file named dfhack*.init (where * is a placeholder for any string), then all
such files are executed in alphabetical order when DF is first started.
DFHack is distributed with /[Link]-example as an example with an up-to-date collection of basic com-
mands; mostly setting standard keybindings and enabling plugins. You are encouraged to look through this file to
learn which features it makes available under which key combinations. You may also customise it and rename it to
[Link].
If your DF folder does not contain any dfhack*.init files, the example will be run as a fallback.
These files are best used for keybindings and enabling persistent plugins which do not require a world to be loaded.
3.4.2 onLoad*.init
When a world is loaded, DFHack looks for files of the form onLoad*.init, where * can be any string, including
the empty string.
All matching init files will be executed in alphabetical order. A world being loaded can mean a fortress, an adventurer,
or legends mode.
These files are best used for non-persistent commands, such as setting a fix script to run on repeat.
3.4.3 onUnload*.init
When a world is unloaded, DFHack looks for files of the form onUnload*.init. Again, these files may be in any
of the above three places. All matching init files will be executed in alphebetical order.
Modders often use such scripts to disable tools which should not affect an unmodded save.
• onMapLoad*.init and onMapUnload*.init are run when a map, distinct from a world, is loaded. This
is good for map-affecting commands (e.g. clean), or avoiding issues in Legends mode.
• Any lua script named raw/init.d/*.lua, in the save or main DF directory, will be run when any world or
that save is loaded.
DFHack’s behavior can be adjusted with some environment variables. For example, on UNIX-like systems:
DFHACK_SOME_VAR=1 ./dfhack
• DFHACK_PORT: the port to use for the RPC server (used by dfhack-run and remotefortressreader among
others) instead of the default 5000. As with the default, if this port cannot be used, the server is not started. See
DFHack Remote Interface for more details.
• DFHACK_DISABLE_CONSOLE: if set, the DFHack console is not set up. This is the default behavior if
PRINT_MODE:TEXT is set in data/init/[Link]. Intended for situations where DFHack cannot run
in a terminal window.
• DFHACK_HEADLESS: if set, and PRINT_MODE:TEXT is set, DF’s display will be hidden, and the console
will be started unless DFHACK_DISABLE_CONSOLE is also set. Intended for non-interactive gameplay only.
• DFHACK_NO_GLOBALS, DFHACK_NO_VTABLES: ignores all global or vtable addresses in [Link],
respectively. Intended for development use - e.g. to make sure tools do not crash when these addresses are
missing.
• DFHACK_NO_DEV_PLUGINS: if set, any plugins from the plugins/devel folder that are built and installed will
not be loaded on startup.
• DFHACK_LOG_MEM_RANGES (macOS only): if set, logs memory ranges to [Link]. Note that de-
vel/lsmem can also do this.
Other (non-DFHack-specific) variables that affect DFHack:
• TERM: if this is set to dumb or cons25 on *nix, the console will not support any escape sequences (arrow keys,
etc.).
• LANG, LC_CTYPE: if either of these contain “UTF8” or “UTF-8” (not case sensitive), DF2CONSOLE() will
produce UTF-8-encoded text. Note that this should be the case in most UTF-8-capable *nix terminal emulators
already.
This section is for odd but important notes that don’t fit anywhere else.
• If a DF H hotkey is named with a DFHack command, pressing the corresponding Fx button will run that com-
mand, instead of zooming to the set location. This feature will be removed in a future version. (see Issue
731)
• The binaries for 0.40.15-r1 to 0.34.11-r4 are on DFFD. Older versions are available here. These files will
eventually be migrated to GitHub. (see Issue 473)
DFHack Plugins
DFHack plugins are the commands, that are compiled with a specific version. They can provide anything from a small
keybinding, to a complete overhaul of game subsystems or the entire renderer.
Most commands offered by plugins are listed here, hopefully organised in a way you will find useful.
Contents
25
DFHack Documentation, Release 0.47.04-r2
– tweak
– fix-armory
• UI Upgrades
– automelt
– autotrade
– command-prompt
– debug
– hotkeys
– ruby
– manipulator
– search
– nopause
– embark-assistant
– embark-tools
– automaterial
– buildingplan
– confirm
– follow
– mousequery
– resume
– title-folder
– title-version
– trackstop
– sort-items
– sort-units
– stocks
– stockpiles
– rename
– rendermax
• Job and Fortress management
– autolabor
– labormanager
– autohauler
– job
– job-material
– job-duplicate
– autogems
– stockflow
– workflow
– clean
– spotclean
– autodump
– cleanowned
– dwarfmonitor
– dwarfvet
– workNow
– seedwatch
– zone
– autonestbox
– autobutcher
– autochop
– orders
– nestboxes
– tailor
– autoclothing
– autofarm
• Map modification
– 3dveins
– alltraffic
– burrow
– changelayer
– changevein
– changeitem
– cleanconst
– deramp
– dig
– digexp
– digcircle
– digtype
– digFlood
27
DFHack Documentation, Release 0.47.04-r2
– filltraffic
– fortplan
– getplants
– infiniteSky
– liquids
– plant
– regrass
– restrictice
– restrictliquids
– tiletypes
– tubefill
• Mods and Cheating
– add-spatter
– adv-bodyswap
– createitem
– diggingInvaders
– fastdwarf
– forceequip
– generated-creature-renamer
– lair
– misery
– mode
– strangemood
– siege-engine
– power-meter
– steam-engine
• Lua API
• stonesense
• blueprint
• remotefortressreader
• isoworldremote
• cursecheck
• flows
• pathable
• probe
• prospect
• reveal
• showmood
4.1.1 stonesense
4.1.2 blueprint
Options (If only region and name are given, export all):
x,y,z Size of map area to export
name Name of export files
dig Export dig commands to “<name>-[Link]”
build Export build commands to “<name>-[Link]”
place Export stockpile commands to “<name>-[Link]”
query Export query commands to “<name>-[Link]”
Goes very well with fortplan, for re-importing.
4.1.3 remotefortressreader
4.1.4 isoworldremote
4.1.5 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 nick-
names).
all Include dead and passive cursed creatures (can result in a quite long list after having FUN with necro-
mancers).
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.
Please report any living/active creatures with cursetype “unknown” - this is most likely with mods which introduce
new types of curses.
4.1.6 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.
4.1.7 pathable
This plugin implements the back end of the gui/pathable script. It exports a single Lua function, in hack/lua/
plugins/[Link]:
• paintScreen(cursor[,skip_unrevealed]): Paint each visible of the screen green or red, depending
on whether it can be pathed to from the tile at cursor. If skip_unrevealed is specified and true, do not
draw unrevealed tiles.
4.1.8 probe
4.1.9 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’.
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.
4.1.10 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.
Usage and related commands:
reveal Reveal the whole map, except for HFS to avoid demons spawning
reveal hell Also show hell, but requires unreveal before unpausing
reveal demon Reveals everything and allows unpausing - good luck!
unreveal Reverts the effects of reveal
revtoggle Switches between reveal and unreveal
revflood Hide everything, then reveal tiles with a path to the cursor (useful to make walled-off rooms
vanish)
revforget Discard info about what was visible before revealing the map. Only useful where (e.g.) you
abandoned with the fort revealed and no longer want the data.
4.1.11 showmood
Shows all items needed for the currently active strange mood.
4.2 Bugfixes
4.2. Bugfixes 31
DFHack Documentation, Release 0.47.04-r2
• fix-unit-occupancy
• fixveins
• petcapRemover
• tweak
• fix-armory
4.2.1 fix-unit-occupancy
This plugin fixes issues with unit occupancy, notably phantom “unit blocking tile” messages (Bug 3499). It can be run
manually, or periodically when enabled with the built-in enable/disable commands:
(no argument) Run the plugin once immediately, for the whole map.
-h, here, cursor Run immediately, only operate on the tile at the cursor
-n, dry, dry-run Run immediately, do not write changes to map
interval <X> Run the plugin every X ticks (when enabled). The default is 1200 ticks, or 1 day. Ticks are
only counted when the game is unpaused.
4.2.2 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.
4.2.3 petcapRemover
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.
Usage:
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
4.2.4 tweak
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 mi-
grants/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, 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.
block-labors Prevents labors that can’t be used from being toggled
burrow-name-cancel Implements the “back” option when renaming a burrow, which currently does
nothing (Bug 1518)
cage-butcher Adds an option to butcher units when viewing cages with q
civ-view-agreement Fixes overlapping text on the “view agreement” screen
condition-material Fixes a crash in the work order contition material list (Bug 9905).
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.
do-job-now Adds a job priority toggle to the jobs list
embark-profile-name Allows the use of lowercase letters when saving embark profiles
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 temper-
ature 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
hide-priority Adds an option to hide designation priority indicators
hotkey-clear Adds an option to clear currently-bound hotkeys (in the H menu)
4.2. Bugfixes 33
DFHack Documentation, Release 0.47.04-r2
import-priority-category Allows changing the priority of all goods in a category when discussing an
import agreement with the liaison
kitchen-prefs-all Adds an option to toggle cook/brew for all visible items in kitchen preferences
kitchen-prefs-color Changes color of enabled items to green in kitchen preferences
kitchen-prefs-empty Fixes a layout issue with empty kitchen tabs (Bug 9000)
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.
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
reaction-gloves Fixes reactions to produce gloves in sets with correct handedness (Bug 6273)
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.
stone-status-all Adds an option to toggle the economic status of all stones
title-start-rename Adds a safe rename option to the title screen “Start Playing” menu
tradereq-pet-gender Displays pet genders on the trade request screen
4.2.5 fix-armory
This plugin requires a binpatch, which has not been available since DF 0.34.11
4.3 UI Upgrades
Note: In order to avoid user confusion, as a matter of policy all GUI 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.
• automelt
• autotrade
• command-prompt
• debug
– help
– category
– filter
– set
– unset
– disable
– enable
• hotkeys
• ruby
• manipulator
– Professions
• search
• nopause
• embark-assistant
• embark-tools
• automaterial
• buildingplan
• confirm
• follow
• mousequery
• resume
• title-folder
• title-version
• trackstop
• sort-items
• sort-units
• stocks
• stockpiles
• rename
• rendermax
4.3. UI Upgrades 35
DFHack Documentation, Release 0.47.04-r2
4.3.1 automelt
When automelt is enabled for a stockpile, any meltable items placed in it will be designated to be melted. This plugin
adds an option to the q menu when enabled.
4.3.2 autotrade
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. This plugin adds an option to the q menu when enabled.
4.3.3 command-prompt
4.3.4 debug
Manager for DFHack runtime debug prints. Debug prints are grouped by plugin name, category name and print level.
Levels are trace, debug, info, warning and error.
The runtime message printing is controlled using filters. Filters set the visible messages of all matching categories.
Matching uses regular expression syntax, which allows listing multiple alternative matches or partial name matches.
This syntax is a C++ version of the ECMA-262 grammar (Javascript regular expressions). Details of differences can
be found at [Link]
Persistent filters are stored in dfhack-config/[Link]. Oldest filters are applied first. That
means a newer filter can override the older printing level selection.
Usage: debugfilter [subcommand] [parameters...]
The following subcommands are supported:
help
category
filter
set
unset
4.3. UI Upgrades 37
DFHack Documentation, Release 0.47.04-r2
disable
Disable a space separated list of filters but keep it in the filter list
Usage: debugfilter disable [id...]
enable
4.3.5 hotkeys
Opens an in-game screen showing which DFHack keybindings are active in the current context. See also hotkey-notes.
Keybinding: CtrlF1
Keybinding: AltF1
4.3.6 ruby
Ruby language plugin, which evaluates the following arguments as a ruby string. Best used as :rb [string], for
the special parsing mode. Alias rb_eval.
4.3.7 manipulator
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 through Professional,
A-E for Great through Grand Master, and U-Z for Legendary through Legendary+5).
Cells with teal backgrounds denote skills not controlled by labors, e.g. military and social skills.
Use the arrow keys or number pad to move the cursor around, holding Shift to move 10 tiles at a time.
4.3. UI Upgrades 39
DFHack Documentation, Release 0.47.04-r2
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 ShiftEsc would exit directly to the main dwarf mode screen.
Professions
The manipulator plugin supports saving professions: a named set of labors that can be quickly applied to one or
multiple dwarves.
To save a profession, highlight a dwarf and press P. The profession will be saved using the custom profession name of
the dwarf, or the default for that dwarf if no custom profession name has been set.
To apply a profession, either highlight a single dwarf or select multiple with x, and press p to select the profession to
apply. All labors for the selected dwarves will be reset to the labors of the chosen profession.
Professions are saved as human-readable text files in the “professions” folder within the DF folder, and can be edited
or deleted there.
4.3.8 search
The search plugin adds search to the Stocks, Animals, Trading, Stockpile, Noble (assignment candidates), Military
(position candidates), Burrows (unit list), Rooms, Announcements, Job List and Unit List screens.
Searching works the same way as the search option in Move to Depot. You will see the Search option displayed
on screen with a hotkey (usually s). Pressing it lets you start typing a query and the relevant list will start filtering
automatically.
Pressing Enter, Esc or the arrow keys will return you to browsing the now filtered list, which still functions as
normal. You can clear the filter by either going back into search mode and backspacing to delete it, or pressing the
“shifted” version of the search hotkey while browsing the list (e.g. if the hotkey is s, then hitting Shifts will clear
any filter).
Leaving any screen automatically clears the filter.
In the Trade screen, the actual trade will always only act on items that are actually visible in the list; the same effect
applies to the Trade Value numbers displayed by the screen. Because of this, the t key is blocked while search is
active, so you have to reset the filters first. Pressing AltC will clear both search strings.
In the stockpile screen the option only appears if the cursor is in the rightmost list:
Note that the ‘Permit XXX’/’Forbid XXX’ keys conveniently operate only on items actually shown in the rightmost
list, so it is possible to select only fat or tallow by forbidding fats, then searching for fat/tallow, and using Permit Fats
again while the list is filtered.
4.3.9 nopause
Disables pausing (both manual and automatic) with the exception of pause forced by reveal hell. This is nice for
digging under rivers.
4.3.10 embark-assistant
This plugin provides embark site selection help. It has to be run with the embark-assistant command while the
pre-embark screen is displayed and shows extended (and correct(?)) resource information for the embark rectangle as
well as normally undisplayed sites in the current embark region. It also has a site selection tool with more options than
DF’s vanilla search tool. For detailed help invoke the in game info screen.
4.3.11 embark-tools
4.3. UI Upgrades 41
DFHack Documentation, Release 0.47.04-r2
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)
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
4.3.12 automaterial
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.
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 auto-
matically 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:
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.
4.3.13 buildingplan
When active (via enable buildingplan), this plugin adds a planning mode for furniture placement. You can
then place furniture and other buildings before the required materials are available, and the job will be unsuspended
when the item is created.
Very useful when combined with workflow - you can set a constraint to always have one or two
doors/beds/tables/chairs/etc available, and place as many as you like. The plugins then take over and fulfill the or-
ders, with minimal space dedicated to stockpiles.
4.3.14 confirm
Implements several confirmation dialogs for potentially destructive actions (for example, seizing goods from traders
or deleting hauling routes).
Usage:
enable confirm Enable all confirmations; alias confirm enable all. Replace with disable to
disable.
confirm help List available confirmation dialogues.
confirm enable option1 [option2. . . ] Enable (or disable) specific confirmation dialogues.
4.3.15 follow
Makes the game view follow the currently highlighted unit after you exit from the current menu or cursor mode. Handy
for watching dwarves running around. Deactivated by moving the view manually.
4.3. UI Upgrades 43
DFHack Documentation, Release 0.47.04-r2
4.3.16 mousequery
4.3.17 resume
Allows automatic resumption of suspended constructions, along with colored UI hints for construction status.
4.3.18 title-folder
Displays the DF folder name in the window title bar when enabled.
4.3.19 title-version
4.3.20 trackstop
Adds a q menu for track stops, which is completely blank by default. This allows you to view and/or change the track
stop’s friction and dump direction settings, using the keybindings from the track stop building interface.
4.3.21 sort-items
Sort the item list using the given sequence of comparisons. The < prefix for an order makes undefined values sort first.
The > prefix reverses the sort order for defined values.
Item order examples:
4.3.22 sort-units
Sort the unit list using the given sequence of comparisons. The < prefix for an order makes undefined values sort first.
The > prefix reverses the sort order for defined values.
Unit order examples:
4.3.23 stocks
4.3.24 stockpiles
Offers the following commands to save and load stockpile settings. See gui/stockpiles for an in-game interface.
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.
Keybinding: AltP
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. e.g.: savestock
food_settings.dfstock
loadstock Loads a saved stockpile settings file and applies it to the currently selected stockpile. e.g.:
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 the 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.
Note that files are relative to the DF folder, so put your files there or in a subfolder for easy access. Filenames should
not have spaces. Generated materials, divine metals, etc are not saved as they are different in every world.
4.3.25 rename
4.3. UI Upgrades 45
DFHack Documentation, Release 0.47.04-r2
4.3.26 rendermax
A collection of renderer replacing/enhancing filters. For better effect try changing the black color in palette to non
totally black. See Bay12 forums thread 128487 for more info.
Options:
trippy Randomizes the color of each tiles. Used for fun, or testing.
light Enable lighting engine.
light reload Reload the settings file.
light sun <x>|cycle Set time to <x> (in hours) or set it to df time cycle.
occlusionON, occlusionOFF Show debug occlusion info.
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. . .
• autolabor
• labormanager
• autohauler
• job
• job-material
• job-duplicate
• autogems
• stockflow
• workflow
– Function
– Constraint format
– Constraint examples
– fix-job-postings
• clean
• spotclean
• autodump
• cleanowned
• dwarfmonitor
• dwarfvet
• workNow
• seedwatch
• zone
– Usage with single units
– Usage with filters
– Mass-renaming
– Cage zones
– Examples
• autonestbox
• autobutcher
• autochop
• orders
• nestboxes
• tailor
• autoclothing
• autofarm
4.4.1 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.
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 con-
structions, 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.
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.
See autolabor-artisans for a differently-tuned setup.
Examples:
4.4.2 labormanager
Automatically manage dwarf labors to efficiently complete jobs. Labormanager is derived from autolabor (above) but
uses a completely different approach to assigning jobs to dwarves. While autolabor tries to keep as many dwarves
busy as possible, labormanager instead strives to get jobs done as quickly as possible.
Labormanager frequently scans the current job list, current list of dwarfs, and the map to determine how many dwarves
need to be assigned to what labors in order to meet all current labor needs without starving any particular type of job.
Warning: As with autolabor, labormanager will override any manual changes you make to labors while it is
enabled, including through other tools such as Dwarf Therapist
Simple usage:
enable labormanager Enables the plugin with default settings. (Persistent per fortress)
disable labormanager Disables the plugin.
Anything beyond this is optional - labormanager works fairly well on the default settings.
The default priorities for each labor vary (some labors are higher priority by default than others). The way the plugin
works is that, once it determines how many of each labor is needed, it then sorts them by adjusted priority. (Labors
other than hauling have a bias added to them based on how long it’s been since they were last used, to prevent job
starvation.) The labor with the highest priority is selected, the “best fit” dwarf for that labor is assigned to that labor,
and then its priority is halved. This process is repeated until either dwarfs or labors run out.
Because there is no easy way to detect how many haulers are actually needed at any moment, the plugin always
ensures that at least one dwarf is assigned to each of the hauling labors, even if no hauling jobs are detected. At least
one dwarf is always assigned to construction removing and cleaning because these jobs also cannot be easily detected.
Lever pulling is always assigned to everyone. Any dwarfs for which there are no jobs will be assigned hauling, lever
pulling, and cleaning labors. If you use animal trainers, note that labormanager will misbehave if you assign specific
trainers to specific animals; results are only guaranteed if you use “any trainer”, and animal trainers will probably be
overallocated in any case.
Labormanager also sometimes assigns extra labors to currently busy dwarfs so that when they finish their current job,
they will go off and do something useful instead of standing around waiting for a job.
There is special handling to ensure that at least one dwarf is assigned to haul food whenever food is detected left in a
place where it will rot if not stored. This will cause a dwarf to go idle if you have no storepiles to haul food to.
Dwarfs who are unable to work (child, in the military, wounded, handless, asleep, in a meeting) are entirely excluded
from labor assignment. Any dwarf explicitly assigned to a burrow will also be completely ignored by labormanager.
The fitness algorithm for assigning jobs to dwarfs generally attempts to favor dwarfs who are more skilled over those
who are less skilled. It also tries to avoid assigning female dwarfs with children to jobs that are “outside”, favors
assigning “outside” jobs to dwarfs who are carrying a tool that could be used as a weapon, and tries to minimize how
often dwarfs have to reequip.
Labormanager automatically determines medical needs and reserves health care providers as needed. Note that this
may cause idling if you have injured dwarfs but no or inadequate hospital facilities.
Hunting is never assigned without a butchery, and fishing is never assigned without a fishery, and neither of these
labors is assigned unless specifically enabled.
The method by which labormanager determines what labor is needed for a particular job is complicated and, in places,
incomplete. In some situations, labormanager will detect that it cannot determine what labor is required. It will,
by default, pause and print an error message on the dfhack console, followed by the message “LABORMANAGER:
Game paused so you can investigate the above message.”. If this happens, please open an issue on github, reporting the
lines that immediately preceded this message. You can tell labormanager to ignore this error and carry on by typing
labormanager pause-on-error no, but be warned that some job may go undone in this situation.
Advanced usage:
labormanager enable Turn plugin on.
labormanager disable Turn plugin off.
labormanager priority <labor> <value> Set the priority value (see above) for labor <labor> to
<value>.
labormanager reset <labor> Reset the priority value of labor <labor> to its default.
labormanager reset-all Reset all priority values to their defaults.
labormanager allow-fishing Allow dwarfs to fish. Warning This tends to result in most of the fort going
fishing.
labormanager forbid-fishing Forbid dwarfs from fishing. Default behavior.
labormanager allow-hunting Allow dwarfs to hunt. Warning This tends to result in as many dwarfs
going hunting as you have crossbows.
labormanager forbid-hunting Forbid dwarfs from hunting. Default behavior.
labormanager list Show current priorities and current allocation stats.
labormanager pause-on-error yes Make labormanager pause if the labor inference engine fails. See
above.
labormanager pause-on-error no Allow labormanager to continue past a labor inference engine failure.
4.4.3 autohauler
4.4.4 job
4.4.5 job-material
Alter the material of the selected job. Similar to job item-material ...
Invoked as:
job-material <inorganic-token>
4.4.6 job-duplicate
In q mode, when a job is highlighted within a workshop or furnace building, calling job-duplicate instantly
duplicates the job.
Keybinding: CtrlD
4.4.7 autogems
Creates a new Workshop Order setting, automatically cutting rough gems when enabled.
See gui/autogems for a configuration UI. If necessary, the autogems-reload command reloads the configuration
file produced by that script.
4.4.8 stockflow
Allows the fortress bookkeeper to queue jobs through the manager, based on space or items available in stockpiles.
Inspired by workflow.
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.
4.4.9 workflow
Manage control of repeat jobs. gui/workflow provides a simple front-end integrated in the game UI.
Usage:
workflow enable [option...], workflow disable [option...] If no options are specified, en-
ables 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.
Constraint format
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 (the same syntax
used custom reaction inputs). For more information, see this wiki page.
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 the link
above 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 the number of prepared food & drink stacks between 90 and 120:
Make sure there are always 15-20 coal and 25-30 copper bars:
Note: In order for this to work, you have to set the material of the PLANT input on the Mill Plants job to MUSH-
ROOM_CUP_DIMPLE using the job item-material command. Otherwise the plugin won’t be able to deduce the
output material.
fix-job-postings
This command fixes crashes caused by previous versions of workflow, mostly in DFHack 0.40.24-r4, and should be
run automatically when loading a world (but can also be run manually if desired).
4.4.10 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.
4.4.11 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.
Keybinding: CtrlC
4.4.12 autodump
This plugin adds an option to the q menu for stckpiles when enabled. When autodump is enabled for a stockpile, any
items placed in the stockpile will automatically be designated to be dumped.
Alternatively, you can use it to 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. If called again before the game is resumed,
cancels destroy.
destroy-here As destroy, but only the selected item in the k list, or inside a container. Alias
autodump-destroy-here, for keybindings.
Keybinding: CtrlShiftK
visible Only process items that are not hidden.
hidden Only process hidden items.
forbidden Only process forbidden items (default: only unforbidden).
autodump-destroy-item destroys the selected item, which may be selected in the k list, or inside a container.
If called again before the game is resumed, cancels destruction of the item.
Keybinding: CtrlK
4.4.13 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.
4.4.14 dwarfmonitor
{
"widgets": [
{
"type": "widget type (weather, misery, etc.)",
"x": X coordinate,
"y": Y coordinate
<...additional options...>
}
]
}
X and Y coordinates begin at zero (in the upper left corner of the screen). Negative coordinates will be treated as
distances from the lower right corner, beginning at 1 - e.g. an x coordinate of 0 is the leftmost column, while an x
coordinate of 1 is the rightmost column.
By default, the x and y coordinates given correspond to the leftmost tile of the widget. Including an anchor option
set to right will cause the rightmost tile of the widget to be located at this position instead.
Some widgets support additional options:
• date widget:
– format: specifies the format of the date. The following characters are replaced (all others, such as
punctuation, are not modified)
– format: Specifies the format. X, x, Y, and y are replaced with the corresponding cursor cordinates, while
all other characters are unmodified.
– show_invalid: If set to true, the mouse coordinates will both be displayed as -1 when the cursor is
outside of the DF window; otherwise, nothing will be displayed.
4.4.15 dwarfvet
4.4.16 workNow
4.4.17 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.
4.4.18 zone
Helps a bit with managing activity zones (pens, pastures and pits) and cages.
Keybinding: AltShiftI -> "zone set" in dwarfmode/Zones
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.
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.
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 nick-
name ‘ineedgrass’.
zone assign all own not grazer not race CAT Assign all own animals who are not grazers, exclud-
ing cats.
zone assign count 5 own female milkable Assign up to 5 own female milkable creatures to the se-
lected 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.
4.4.19 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.
4.4.20 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. See fix-ster if this is a problem.
Options:
example Print some usage examples.
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 <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). The first four arguments are
the number of female and male kids, and female and male adults. R can be a list of spceies 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.
list_export Print the commands required to rebuild your current settings.
Note: Settings and watchlist are stored in the savegame, so that you can have different settings for each save. If you
want to copy your watchlist to another savegame you must export the commands required to recreate your settings.
To export, open an external terminal in the DF directory, and run dfhack-run autobutcher list_export
> [Link]. To import, load your new save and run script [Link] in the DFHack terminal.
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.
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.
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.
4.4.21 autochop
Automatically manage tree cutting designation to keep available logs withing given quotas.
Open the dashboard by running:
enable autochop
The plugin must be activated (with d-t-c-a) 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 autochop to your [Link] there will be a hotkey to open the dashboard from the chop
designation menu.
4.4.22 orders
4.4.23 nestboxes
Automatically scan for and forbid fertile eggs incubating in a nestbox. Toggle status with enable or disable.
4.4.24 tailor
Whenever the bookkeeper updates stockpile records, this plugin will scan every unit in the fort, count up the number
that are worn, and then order enough more made to replace all worn items. If there are enough replacement items in
inventory to replace all worn items, the units wearing them will have the worn items confiscated (in the same manner
as the cleanowned plugin) so that they’ll reeequip with replacement items.
Use the enable and disable commands to toggle this plugin’s status, or run tailor status to check its current
status.
4.4.25 autoclothing
Automatically manage clothing work orders, allowing the user to set how many of each clothing type every citizen
should have. Usage:
Examples:
• autoclothing cloth "short skirt" 10: Sets the desired number of cloth short skirts available per
citizen to 10.
• autoclothing cloth dress: Displays the currently set number of cloth dresses chosen per citizen.
4.4.26 autofarm
Automatically handles crop selection in farm plots based on current plant stocks, and selects crops for planting if
current stock is below a threshold. Selected crops are dispatched on all farmplots. (Note that this plugin replaces an
older Ruby script of the same name.)
Use the enable or disable commands to change whether this plugin is enabled.
Usage:
• autofarm runonce: Updates all farm plots once, without enabling the plugin
• autofarm status: Prints status information, including any applied limits
• autofarm default 30: Sets the default threshold
• autofarm threshold 150 helmet_plump tail_pig: Sets thresholds of individual plants
• 3dveins
• alltraffic
• burrow
• changelayer
• changevein
• changeitem
• cleanconst
• deramp
• dig
• digexp
• digcircle
• digtype
• digFlood
• filltraffic
• fortplan
• getplants
• infiniteSky
• liquids
– Commands
– liquids-here
• plant
• regrass
• restrictice
• restrictliquids
• tiletypes
– tiletypes-command
– tiletypes-here
– tiletypes-here-point
• tubefill
4.5.1 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.
The only undo option is to restore your save from backup.
4.5.2 alltraffic
Set traffic designations for every single tile of the map - useful for resetting traffic designations. See also filltraffic,
restrictice, and restrictliquids.
Options:
H High Traffic
N Normal Traffic
L Low Traffic
R Restricted Traffic
4.5.3 burrow
Miscellaneous burrow control. Allows manipulating burrows and automated burrow expansion while digging.
Options:
enable feature . . . Enable features of the plugin.
4.5.4 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?
4.5.5 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.
4.5.6 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.
4.5.7 cleanconst
This utility alters all constructions on the map so that they spawn their building component when they are disassembled,
allowing their actual build items to be safely deleted. This can improve FPS in extreme situations.
4.5.8 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).
4.5.9 dig
Note: All commands implemented by the dig plugin (listed by ls dig) support specifying the designation priority
with -p#, -p #, or p=#, where # is a number from 1 to 7. If a priority is not specified, the priority selected in-game
is used as the default.
4.5.10 digexp
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
4.5.11 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.
4.5.12 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
4.5.13 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.
Usage:
help digflood detailed help message
digFlood 0 disable the plugin
digFlood 1 enable the plugin
digFlood 0 MICROCLINE COAL_BITUMINOUS 1 disable plugin, remove microcline and bitumi-
nous 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
4.5.14 filltraffic
Set traffic designations using flood-fill starting at the cursor. See also alltraffic, restrictice, and restrictliquids. Options:
H High Traffic
N Normal Traffic
L Low Traffic
R Restricted Traffic
X Fill across 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.
4.5.15 fortplan
. . . where X and Y are the offset from the top-left corner of the file’s area where the in-game cursor should be lo-
cated, 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 buildingplan, so you do not need to have the items available to construct all the
buildings when you run fortplan with the .csv file.
4.5.16 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 Tree: Select trees only (exclude shrubs)
-s Shrub: Select shrubs only (exclude trees)
-f Farming: Designate only shrubs that yield seeds for farming. Implies -s
-c Clear: Clear designations instead of setting them
-x eXcept: Apply selected action to all plants except those specified (invert selection)
-a All: Select every type of plant (obeys -t/-s/-f)
-v Verbose: Lists the number of (un)designations per plant
-n * Number: Designate up to * (an integer number) plants of each species
Specifying both -t and -s or -f will have no effect. If no plant IDs are specified, all valid plant IDs will be listed,
with -t, -s, and -f restricting the list to trees, shrubs, and farmable shrubs, respectively.
Note: DF is capable of determining that a shrub has already been picked, leaving an unusable structure part behind.
This plugin does not perform such a check (as the location of the required information has not yet been identified).
This leads to some shrubs being designated when they shouldn’t be, causing a plant gatherer to walk there and do
nothing (except clearing the designation). See Issue 1479 for details.
The implementation another known deficiency: it’s incapable of detecting that raw definitions that specify a seed
extraction reaction for the structural part but has no other use for it cannot actually yield any seeds, as the part is never
used (parts of Bug 6940, e.g. Red Spinach), even though DF collects it, unless there’s a workshop reaction to do it
(which there isn’t in vanilla).
4.5.17 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.
Usage:
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.
Warning: Sometimes new z-levels disappear and cause cave-ins. Saving and loading after creating new z-levels
should fix the problem.
4.5.18 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). See also Issue 80.
Warning: Spawning and deleting liquids can mess up pathing data and temperatures (creating heat traps). You’ve
been warned.
Settings will be remembered until you quit DF. You can call liquids-here to execute the last configured action, which
is useful in combination with keybindings.
Usage: point the DF cursor at a tile you want to modify and use the commands.
If you only want to add or remove water or magma from one tile, source may be easier to use.
Commands
Misc commands:
q quit
help, ? print this list of commands
<empty line> put liquid
Modes:
m switch to magma
w switch to water
o make obsidian wall instead
of make obsidian floors
rs make a river source
f flow bits only
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.
4.5.19 plant
4.5.20 regrass
4.5.21 restrictice
Restrict traffic on all tiles on top of visible ice. See also alltraffic, filltraffic, and restrictliquids.
4.5.22 restrictliquids
Restrict traffic on all visible tiles with liquid. See also alltraffic, filltraffic, and restrictice.
4.5.23 tiletypes
Can be used for painting map tiles and is an interactive command, much like liquids. If something goes wrong, fixveins
may help.
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 turn all stone fortifica-
tions into floors, preserving the material:
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:
This mode is incompatible with the regular material setting, so changing it cancels the specific stone selection:
Since different vein types have different drop rates, it is possible to choose which one to use in painting:
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:
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, use tiletypes help.
tiletypes-command
Runs tiletypes commands, separated by ;. This makes it possible to change tiletypes modes from a hotkey or via
dfhack-run.
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.
4.5.24 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.
• add-spatter
• adv-bodyswap
• createitem
• diggingInvaders
• fastdwarf
• forceequip
• generated-creature-renamer
• lair
• misery
• mode
• strangemood
• siege-engine
• power-meter
• steam-engine
– Construction
– Operation
– Explosions
– Save files
4.6.1 add-spatter
This plugin makes reactions with names starting with SPATTER_ADD_ produce contaminants on the items instead
of improvements. The plugin is intended to give some use to all those poisons that can be bought from caravans, so
they’re immune to being washed away by water or destroyed by clean.
4.6.2 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.
4.6.3 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:
4.6.4 diggingInvaders
You can also use diggingInvaders setCost (race) (action) n to set the pathing cost of particular
action, or setDelay to set how long it takes. Costs and delays are per-tile, and the table shows default values.
Action Cost
De- Notes
lay
walk 1 0 base cost in the path algorithm
destroyBuilding 2 1,000 delay adds to the job_completion_timer of destroy building jobs that
are assigned to invaders
dig 10,000 1,000 digging soil or natural stone
1,000 1,000 constructions made from boulders
destroyRoughConstruction
100
destroySmoothConstruction 100 constructions made from blocks or bars
4.6.5 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 disables both (also 0 0)
fastdwarf 1 enables speedydwarf and disables teledwarf (also 1 0)
fastdwarf 2 sets a native debug flag in the game memory that implements an even more aggressive ver-
sion of speedydwarf.
fastdwarf 0 1 disables speedydwarf and enables teledwarf
fastdwarf 1 1 enables both
See superdwarf for a per-creature version.
4.6.6 forceequip
Forceequip moves local items into a unit’s inventory. It is typically used to equip specific clothing/armor items onto a
dwarf, but can also be used to put armor onto a war animal or to add unusual items (such as crowns) to any unit.
For more information run forceequip help. See also modtools/equip-item.
4.6.7 generated-creature-renamer
Automatically renames generated creatures, such as forgotten beasts, titans, etc, to have raw token names that match
the description given in-game.
The list-generated command can be used to list the token names of all generated creatures in a given save, with
an optional detailed argument to show the accompanying description.
The save-generated-raws command will save a sample creature graphics file in the Dwarf Fortress root direc-
tory, to use as a start for making a graphics set for generated creatures using the new names that they get with this
plugin.
The new names are saved with the save, and the plugin, when enabled, only runs once per save, unless there’s an
update.
4.6.8 lair
This command allows you to mark the map as a 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)
4.6.9 misery
4.6.10 mode
This command lets you see and change the game mode directly.
Examples:
• 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. Alternatively:
• 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.
4.6.11 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, arti-
fact 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 for T 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”, “ar-
morsmith”, “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.
4.6.12 siege-engine
Siege engines in DF haven’t been updated since the game was 2D, and can only aim in four directions. To make them
useful above-ground, this plugin allows you to:
• link siege engines to stockpiles
• restrict operator skill levels (like workshops)
• load any object into a catapult, not just stones
• aim at a rectangular area in any direction, and across Z-levels
The front-end is implemented by gui/siege-engine.
4.6.13 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 gui/power-meter.
4.6.14 steam-engine
The steam-engine plugin detects custom workshops with STEAM_ENGINE in their token, and turns them into real
steam engines.
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.
Compared to the water reactor exploit, steam engines make a lot of sense!
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.
Due to DFHack limits, the workshop will collapse over true open space. However down stairs are passable but support
machines, so you can 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.
Like with collapse above, due to DFHack limits the workshop can only immediately connect to machine components
built AFTER it. This also means that engines cannot be chained without intermediate axles built after both 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. Mas-
terpiece 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.
Some plugins consist solely of native libraries exposed to Lua. They are listed in the DFHack Lua API file under
Plugins:
• Eventful
• Building-hacks
• Luasocket
• map-render
• cxxrandom
• xlsxreader
DFHack Scripts
Lua or ruby scripts placed in the hack/scripts/ directory are considered for execution as if they were native
DFHack commands.
The following pages document all the scripts in the DFHack standard library.
Basic scripts are not stored in any subdirectory, and can be invoked directly. They are generally useful tools for any
player.
Contents
• adaptation
• add-recipe
• add-thought
• adv-fix-sleepers
• adv-max-skills
• adv-rumors
• animal-control
• armoks-blessing
• assign-attributes
• assign-beliefs
• assign-facets
• assign-goals
83
DFHack Documentation, Release 0.47.04-r2
• assign-preferences
• assign-profile
• assign-skills
• autolabor-artisans
• autounsuspend
• ban-cooking
• binpatch
• bodyswap
• brainwash
• break-dance
• burial
• cannibalism
• caravan
• catsplosion
• clear-smoke
• colonies
• color-schemes
• combat-harden
• combine-drinks
• combine-plants
• create-items
• deathcause
• deep-embark
• deteriorateclothes
• deterioratecorpses
• deterioratefood
• digfort
• dorf_tables
• drain-aquifer
• dwarf-op
• elevate-mental
• elevate-physical
• embark-skills
• emigration
• empty-bin
• exportlegends
• exterminate
• extinguish
• feature
• fillneeds
• firestarter
• fix-ster
• fixnaked
• flashstep
• force
• forget-dead-body
• forum-dwarves
• full-heal
• gaydar
• geld
• ghostly
• growcrops
• hermit
• hfs-pit
• hotkey-notes
• install-info
• item-descriptions
• launch
• lever
• light-aquifers-only
• linger
• list-agreements
• list-waves
• load-save
• locate-ore
• lua
• make-legendary
• make-monarch
• markdown
• masspit
• migrants-now
• multicmd
• names
• on-new-fortress
• once-per-save
• open-legends
• points
• position
• pref-adjust
• prefchange
• putontable
• questport
• quicksave
• region-pops
• rejuvenate
• remove-stress
• remove-wear
• repeat
• resurrect-adv
• reveal-hidden-units
• season-palette
• set-orientation
• setfps
• show-unit-syndromes
• siren
• source
• spawnunit
• startdwarf
• starvingdead
• stripcaged
• superdwarf
• tame
• teleport
• tidlers
• troubleshoot-item
• twaterlvl
• undump-buildings
• unforbid
• ungeld
• unretire-anyone
• unsuspend
• view-item-info
• view-unit-reports
• warn-starving
• weather
• workorder
5.1.1 adaptation
View or set level of cavern adaptation for the selected unit or the whole fort.
Usage:
5.1.2 add-recipe
Adds unknown weapon and armor crafting recipes to your civ. E.g. some civilizations never learn to craft high boots.
This script can help with that, and more. Only weapons, armor, and tools are currently supported; things such as
instruments are not. Available options:
• add-recipe all adds all available weapons and armor, including exotic items like blowguns, two-handed
swords, and capes.
• add-recipe native adds only native (but unknown) crafting recipes. Civilizations pick randomly from a
pool of possible recipes, which means not all civs get high boots, for instance. This command gives you all the
recipes your civilisation could have gotten.
• add-recipe single <item token> adds a single item by the given item token. For example:
5.1.3 add-thought
Adds a thought or emotion to the selected unit. Can be used by other scripts, or the gui invoked by running
add-thought -gui with a unit selected.
5.1.4 adv-fix-sleepers
Fixes Bug 6798. This bug is characterized by sleeping units who refuse to awaken in adventure mode regardless of
talking to them, hitting them, or waiting so long you die of thirst. If you come accross one or more bugged sleepers in
adventure mode, simply run the script and all nearby sleepers will be cured.
Usage:
adv-fix-sleepers
5.1.5 adv-max-skills
When creating an adventurer, raises all changeable skills and attributes to their maximum level.
5.1.6 adv-rumors
5.1.7 animal-control
Animal control is a script useful for deciding what animals to butcher and geld.
While not as powerful as Dwarf Therapist in managing animals - in so far as DT allows you to sort by various stats and
flags - this script does provide many options for filtering animals. Additionally you can mark animals for slaughter or
gelding, you can even do so enmasse if you so choose.
Examples:
Selection options:
These options are used to specify what animals you want or do not want to select.
-all: Selects all units. Note: cannot be used in conjunction with other selection options.
-id <value>: Selects the unit with the specified id value provided.
-race <value>: Selects units which match the race value provided.
-markedfor <action>: Selects units which have been marked for the action provided. Valid actions:
slaughter, gelding
-notmarkedfor <action>: Selects units which have not been marked for the action provided. Valid
actions: slaughter, gelding
5.1.8 armoks-blessing
Runs the equivalent of rejuvenate, elevate-physical, elevate-mental, and brainwash on all dwarves currently on the
map. This is an extreme change, which sets every stat and trait to an ideal easy-to-satisfy preference.
Without providing arguments, only attributes, age, and personalities will be adjusted. Adding arguments allows for
skills or classes to be adjusted to legendary (maximum).
Arguments:
• list Prints list of all skills
• classes Prints list of all classes
• all Set all skills, for all Dwarves, to legendary
• <skill name> Set a specific skill, for all Dwarves, to legendary
example: armoks-blessing RANGED_COMBAT
All Dwarves become a Legendary Archer
• <class name> Set a specific class (group of skills), for all Dwarves, to legendary
example: armoks-blessing Medical
All Dwarves will have all medical related skills set to legendary
5.1.9 assign-attributes
Tier Description
4 unbelievably strong
3 mighty
2 very strong
1 strong
0 (no description)
-1 weak
-2 very weak
-3 unquestionably weak
-4 unfathomably weak
This will reset all attributes to a neutral value and will set the following values (if the currently selected unit is a dwarf):
• Strength: a random value between 1750 and 1999 (tier 2);
• Agility: a random value between 401 and 650 (tier -1);
• Spatial sense: a random value between 1043 and 1292 (tier -1).
The final result will be: “She is very strong, but she is clumsy. She has a questionable spatial sense.”
5.1.10 assign-beliefs
Strength Effect
3 Highest
2 Very High
1 High
0 Neutral
-1 Low
-2 Very Low
-3 Lowest
Resetting a belief means setting it to a level that does not trigger a report in the “Thoughts and preferences” screen.
Usage:
-help: print the help page.
-unit <UNIT_ID>: set the target unit ID. If not present, the currently selected unit will be the target.
-beliefs [ <BELIEF> <LEVEL> <BELIEF> <LEVEL> <...> ]: the beliefs to modify and their levels.
The valid belief tokens can be found in the wiki page linked above; level values range from -3 to 3. There must
be a space before and after each square bracket.
-reset: reset all beliefs to a neutral level. If the script is called with both this option and a list of beliefs/levels, first
all the unit beliefs will be reset and then those beliefs listed after -beliefs will be modified.
Example:
Resets all the unit beliefs, then sets the listed beliefs to the following values:
• Tradition: a random value between 26 and 40 (level 2);
• Craftsmanship: a random value between 41 and 50 (level 3);
• Power: a random value between -10 and 10 (level 0);
• Cunning: a random value between -25 and -11 (level -1).
The final result (for a dwarf) will be: “She personally is a firm believer in the value of tradition and sees guile and
cunning as indirect and somewhat worthless.”
Note that the beliefs aligned with the cultural values of the unit have not triggered a report.
5.1.11 assign-facets
Strength Effect
3 Highest
2 Very High
1 High
0 Neutral
-1 Low
-2 Very Low
-3 Lowest
Resetting a facet means setting it to a level that does not trigger a report in the “Thoughts and preferences” screen.
Usage:
-help: print the help page.
-unit <UNIT_ID>: set the target unit ID. If not present, the currently selected unit will be the target.
-beliefs [ <FACET> <LEVEL> <FACET> <LEVEL> <...> ]: the facets to modify and their levels. The
valid facet tokens can be found in the wiki page linked above; level values range from -3 to 3. There must be a
space before and after each square bracket.
-reset: reset all facets to a neutral level. If the script is called with both this option and a list of facets/levels, first
all the unit facets will be reset and then those facets listed after -facets will be modified.
Example:
Resets all the unit facets, then sets the listed facets to the following values:
• Hate propensity: a value between 10 and 24 (level -2);
• Cheer propensity: a value between 25 and 39 (level -1).
The final result (for a dwarf) will be: “She very rarely develops negative feelings toward things. She is rarely happy
or enthusiastic, and she is conflicted by this as she values parties and merrymaking in the abstract.”
Note that the facets are compared to the beliefs, and if conflicts arise they will be reported.
5.1.12 assign-goals
Clears all the unit goals, then sets the “master a skill” goal. The final result will be: “dreams of mastering a skill”.
5.1.13 assign-preferences
-hatecreature [ <TOKEN> <TOKEN> <...> ]: works the same way as -likecreature, but this time
it’s one or more creatures that the unit detests. They should be a type of HATEABLE vermin which isn’t already
explicitly liked, but no check is performed about this. Like before, you can just list the creature species. There
must be a space before and after each square bracket.
-likeitem [ <TOKEN> <TOKEN> <...> ]: a kind of weapon, a kind of ammo, a kind of piece of armor,
a piece of clothing (including backpacks or quivers), a type of furniture (doors, floodgates, beds, chairs,
windows, cages, barrels, tables, coffins, statues, boxes, armor stands, weapon racks, cabinets, bins, hatch
covers, grates, querns, millstones, traction benches, or slabs), a kind of craft (figurines, amulets, scepters,
crowns, rings, earrings, bracelets, or large gems), or a kind of miscellaneous item (catapult parts, bal-
lista parts, a type of siege ammo, a trap component, coins, anvils, totems, chains, flasks, goblets, buck-
ets, animal traps, an instrument, a toy, splints, crutches, or a tool). The item tokens can be found here:
[Link] If you want to specify an item subtype, look into
the files listed under the column “Subtype” of the wiki page (they are in the “/raw/ojects/” folder), then specify
the items using the full tokens found in those files (see examples below). There must be a space before and after
each square bracket.
-likeplant [ <TOKEN> <TOKEN> <...> ]: works in a similar way as -likecreature, this time with
plants. You can just List the plant species (the middle part of the token as listed in “[Link]”). There must
be a space before and after each square bracket.
-liketree [ <TOKEN> <TOKEN> <...> ]: works exactly as -likeplant. I think this preference type is
here for backward compatibility (?). You can still use it, however. As before, you can just list the tree (plant)
species. There must be a space before and after each square bracket.
-likecolor [ <TOKEN> <TOKEN> <...> ]: you can find the color tokens here: [Link]
org/[Link]/DF2014:Color#Color_tokens or inside the “descriptor_color_standard.txt” file (in the
“/raw/ojects/” folder). You can use the full token or just the color name. There must be a space before and
after each square bracket.
-likeshape [ <TOKEN> <TOKEN> <...> ]: I couldn’t find a list of shape tokens in the wiki, but you can
find them inside the “descriptor_shape_standard.txt” file (in the “/raw/ojects/” folder). You can use the full token
or just the shape name. There must be a space before and after each square bracket.
-reset: clear all preferences. If the script is called with both this option and one or more preferences, first all the
unit preferences will be cleared and then the listed preferences will be added.
Examples:
• “likes alabaster and willow wood”:
• “likes stars”:
5.1.14 assign-profile
A script to change the characteristics of a unit according to a profile loaded from a json file.
A profile can describe which attributes, skills, preferences, beliefs, goals and facets a unit must have. The script relies
on the presence of the other assign-... modules in this collection: please refer to the other modules documentation
for more specific information.
For information about the json schema, please see the the “/hack/scripts/dwarf_profiles.json” file.
Usage:
-help: print the help page.
-unit <UNIT_ID>: the target unit ID. If not present, the target will be the currently selected unit.
-file <filename>: the json file containing the profile to apply. It’s a relative path, starting from the DF root di-
rectory and ending at the json file. It must begin with a slash. Default value: “/hack/scripts/dwarf_profiles.json”.
-profile <profile>: the profile to apply. It’s the name of the profile as stated in the json file.
-reset <list of characteristics>: the characteristics to be reset/cleared. If not present, it will not clear
or reset any characteristic. If it’s a valid list of characteristic, those characteristics will be reset, and then, if
present in the profile, the new values will be applied. If set to PROFILE, it will reset only the characteristics
changed in the profile (and then the new values will be applied). If set to ALL, it will reset EVERY characteristic.
Possible values: ALL, PROFILE, ATTRIBUTES, SKILLS, PREFERENCES, BELIEFS, GOALS, FACETS.
Examples:
• Resets/clears all the characteristics of the unit, leaving behind a very bland character:
• Loads and applies the profile called “CARPENTER” in the default json file, resetting/clearing all the character-
istics listed in the profile, and then applying the new values:
• Loads and applies the profile called “ARCHER” in the provided json file, keeping all the old characteristics but
the attributes, which will be reset (and then, if the profile provides some attributes values, those value will be
applied):
5.1.15 assign-skills
Clears all the unit skills, then adds the Wood cutter skill (competent level) and the Axeman skill (adequate level).
5.1.16 autolabor-artisans
Runs an autolabor command, for all labors where skill level influences output quality. Examples:
autolabor-artisans 0 2 3
autolabor-artisans disable
5.1.17 autounsuspend
5.1.18 ban-cooking
A more convenient way to ban cooking various categories of foods than the kitchen interface. Usage: ban-cooking
<type>. Valid types are booze, honey, tallow, oil, seeds (non-tree plants with seeds), brew, fruit, mill,
thread, and milk.
5.1.19 binpatch
5.1.20 bodyswap
This script allows the player to take direct control of any unit present in adventure mode whilst giving up control of
their current player character.
To specify the target unit, simply select it in the user interface, such as by opening the unit’s status screen or viewing
its description, and enter “bodyswap” in the DFHack console.
Alternatively, the target unit can be specified by its unit id as shown below.
Arguments:
-unit id
replace "id" with the unit id of your target
example:
bodyswap -unit 42
5.1.21 brainwash
Modify the personality traits of the selected dwarf to match an idealised personality - for example, as stable and reliable
as possible to prevent tantrums even after months of misery.
Usage: brainwash <type>, with one of the following types:
ideal reliable, with generally positive personality traits
baseline reset all personality traits to the average
stepford amplifies all good qualities to an excessive degree
wrecked amplifies all bad qualities to an excessive degree
5.1.22 break-dance
Breaks up dances, such as broken or otherwise hung dances that occur when a unit can’t find a partner.
5.1.23 burial
Sets all unowned coffins to allow burial. burial -pets also allows burial of pets.
5.1.24 cannibalism
Allows consumption of sapient corpses. Use from an adventurer’s inventory screen or an individual item’s detail
screen.
5.1.25 caravan
Adjusts properties of caravans on the map. See also force to create caravans.
This script has multiple subcommands. Commands listed with the argument [IDS] can take multiple caravan IDs
(see caravan list). If no IDs are specified, then the commands apply to all caravans on the map.
Subcommands:
• list: lists IDs and information about all caravans on the map.
• extend [DAYS] [IDS]: extends the time that caravans stay at the depot by the specified number of days
(defaults to 7 if not specified). Also causes caravans to return to the depot if applicable.
• happy [IDS]: makes caravans willing to trade again (after seizing goods, annoying merchants, etc.). Also
causes caravans to return to the depot if applicable.
• leave [IDS]: makes caravans pack up and leave immediately.
5.1.26 catsplosion
Makes cats (and other animals) just multiply. It is not a good idea to run this more than once or twice.
Usage:
catsplosion Make all cats pregnant
catsplosion list List IDs of all animals on the map
catsplosion ID . . . Make animals with given ID(s) pregnant
Animals will give birth within two in-game hours (100 ticks or fewer).
5.1.27 clear-smoke
Removes all smoke from the map. Note that this can leak memory and should be used sparingly.
5.1.28 colonies
List vermin colonies, place honey bees, or convert all vermin to honey bees. Usage:
colonies List all vermin colonies on the map.
colonies place Place a honey bee colony under the cursor.
colonies convert Convert all existing colonies to honey bees.
The place and convert subcommands by default create or convert to honey bees, as this is the most commonly
useful. However both accept an optional flag to use a different vermin type, for example colonies place ANT
creates an ant colony and colonies convert TERMITE ends your beekeeping industry.
5.1.29 color-schemes
5.1.30 combat-harden
Sets the combat-hardened value on a unit, making them care more/less about seeing corpses. Requires a value and a
target.
Valid values:
-value <0-100> A percent value to set combat hardened to.
-tier <1-4>
Choose a tier of hardenedness to set it to. 1 = No hardenedness. 2 = “is getting used to tragedy”
3 = “is a hardened individual” 4 = “doesn’t really care about anything anymore” (max)
5.1.31 combine-drinks
5.1.32 combine-plants
5.1.33 create-items
5.1.34 deathcause
Select a body part ingame, or a unit from the u unit list, and this script will display the cause of death of the creature.
5.1.35 deep-embark
Moves the starting units and equipment to a specific underground region upon embarking.
This script can be run directly from the console at any point whilst setting up an embark.
Alternatively, create a file called “[Link]” in the DF raw folder (if one does not exist already) and enter the script
command within it. Doing so will cause the script to run automatically and should hence be especially useful for
modders who want their mod to include underground embarks by default.
Example:
Usage:
-depth X
(obligatory)
replace "X" with one of the following:
CAVERN_1
CAVERN_2
CAVERN_3
UNDERWORLD
-blockDemons
including this arg will prevent demon surges
in the context of breached underworld spires
(intended mainly for UNDERWORLD embarks)
("wildlife" demon spawning will be unaffected)
-atReclaim
if the script is being run from [Link],
including this arg will enable deep embarks
when reclaiming sites too
(there's no need to specify this if running
the script directly from the console)
-clear
re-enable normal surface embarks
5.1.36 deteriorateclothes
Somewhere between a “mod” and a “fps booster”, with a small impact on vanilla gameplay. All of those slightly
worn wool shoes that dwarves scatter all over the place will deteriorate at a greatly increased rate, and eventually just
crumble into nothing. As warm and fuzzy as a dining room full of used socks makes your dwarves feel, your FPS does
not like it.
Usage:
deteriorateclothes start|stop
5.1.37 deterioratecorpses
Somewhere between a “mod” and a “fps booster”, with a small impact on vanilla gameplay.
In long running forts, especially evil biomes, you end up with a lot of toes, teeth, fingers, and limbs scattered all
over the place. Various corpses from various sieges, stray kitten corpses, probably some heads. Basically, your map
will look like a giant pile of assorted body parts, all of which individually eat up a small part of your FPS, which
collectively eat up quite a bit.
In addition, this script also targets various butchery byproducts. Enjoying your thriving animal industry? Your FPS
does not. Those thousands of skulls, bones, hooves, and wool eat up precious FPS that could be used to kill goblins
and elves. Whose corpses will also get destroyed by the script to kill more goblins and elves.
This script causes all of those to rot away into nothing after several months.
Usage:
deterioratecorpses start|stop
5.1.38 deterioratefood
Somewhere between a “mod” and a “fps booster”, with a small impact on vanilla gameplay.
With this script running, all food and plants wear out and disappear after several months. Barrels and stockpiles will
keep them from rotting, but it won’t keep them from decaying. No more sitting on a hundred years worth of food. No
more keeping barrels of pig tails sitting around until you decide to use them. Either use it, eat it, or lose it. Seeds, are
excluded from this, if you aren’t planning on using your pig tails, hold onto the seeds for a rainy day.
This script is. . . pretty far reaching. However, almost all long running forts I’ve had end up sitting on thousands and
thousands of food items. Several thousand cooked meals, three thousand plump helmets, just as many fish and meat.
It gets pretty absurd. And your FPS doesn’t like it.
Usage:
deterioratefood start|stop
5.1.39 digfort
# this is a comment
d,d,u,d,d,skip this tile,d
d,d,d,i
Other than d, tile shapes are named after the ‘dig’ menu shortcuts: d for default, u upstairs, j downstairs, i updown,
h channel, r upward ramp, and x remove designation. Unrecognized characters are ignored (e.g. the ‘skip this tile’ in
the sample). d is interpreted based on the shape of the current tile. It will dig walls, remove stairs and ramps, gather
plants, and fell trees.
Empty lines and data after a # are ignored as comments. Double quote (") characters that are inserted at the beginning
of strings by csv exporters are also ignored. To skip a row in your design, add a row consisting only of , characters.
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.
Additionally a comment can have a < for a rise in z level or a > for a drop in z.
The script takes the plan filename, starting from the root df folder (where [Link] is found).
Additional options can be specified after the filename:
• force: if the blueprint would extend beyond the edge of the map, still draw the parts that remain on the map.
(The default behavior in this case is to fail with an error message.)
5.1.40 dorf_tables
To see a full list of built-in professions and jobs, you can run these commands:
5.1.41 drain-aquifer
5.1.42 dwarf-op
Dwarf optimization is a script designed to provide a robust solution to hacking dwarves to be better at work. The
primary use case is as follows:
1) take a dwarf
2) delete their ability to do anything, even walk (job skills, phyiscal/mental attributes)
3) load the job distribution table from dorf_tables
4) update values in said table so the table accurately represents the distribution of your dwarves
5) pick an under-represented job from the table
6) apply the job to the dwarf, which means:
• apply professions
• provide custom profession name
• add job skills
• apply dwarf types
• etc.
Beyond this use case of optimizing dwarves according to the tables in dorf_tables, this script makes each step in the
process available to use separately, if you so choose.
There are two basic steps to using this script: selecting a subset of your dwarves, and running commands on those
dwarves.
Usage:
dwarf-op -help
dwarf-op -select <select-option> -<command> <args>
Examples:
Select options:
Note: Prepend the letter p to any option to include protected dwarves in your selection
optimized selects dwarves based on session data. Dwarves who have been optimized should be listed in
this data.
unoptimized selects any dwarves that don’t appear in session data.
protected selects any dwarves which use protection signals in their name or profession. (i.e. ., ,)
unprotected selects any dwarves which don’t use protection signals in their name or profession.
drunks selects any dwarves which are currently zeroed, or were originally drunks as their profession.
jobs selects any dwarves with the listed jobs. This will only match with custom professions, or optimized
dwarves (for optimized dwarves see jobs in dorf_tables).
Usage:
Example:
waves selects dwarves from the specified migration waves. Waves are enumerated starting at 0 and
increasing by 1 with each wave. The waves go by season and year and thus should match what
you see in list-waves or Dwarf Therapist. It is recommended that you -show the selected dwarves
before modifying.
Example:
General commands:
• -reset: deletes json file containing session data (bug: might not delete session data)
• -resetall: deletes both json files. session data and existing persistent data (bug: might not delete session
data)
• -show: displays affected dwarves (id, name, migration wave, primary job). Useful for previewing selected
dwarves before modifying them, or looking up the migration wave number for a group of dwarves.
Dwarf commands:
clean <value>: Cleans selected dwarves. Checks for skills with a rating of <value> and deletes them from
the dwarf’s skill list
-clear: Zeroes selected dwarves, or zeroes all dwarves if no selection is given. No attributes, no labours. As-
signs DRUNK profession.
-reroll [inclusive]: zeroes selected dwarves, then rerolls that dwarf based on its job.
• Ignores dwarves with unlisted jobs.
• optional argument: inclusive - means your dorf(s) get the best of N rolls.
• See attrib_levels table in dorf_tables for p values describing the normal distribution of stats (each p value has
a sub-distribution, which makes the bell curve not so bell-shaped). Labours do not follow the same stat system
and are more uniformly random, which are compensated for in the description of jobs/professions.
-optimize: Performs a job search for unoptimized dwarves. Each dwarf will be found a job according to the
job_distribution table in dorf_tables.
-applyjobs: Applies the listed jobs to the selected dwarves.
• List format: [ job1 job2 jobn ] (brackets and jobs all separated by spaces)
5.1.43 elevate-mental
Set all mental attributes of the selected dwarf to the maximum possible, or any number numbers between 0 and 5000
passed as an argument: elevate-mental 100 for example would make the dwarf very stupid indeed.
5.1.44 elevate-physical
Set all physical attributes of the selected dwarf to the maximum possible, or any number numbers between 0 and 5000
passed as an argument. Higher is usually better, but an ineffective hammerer can be useful too. . .
5.1.45 embark-skills
5.1.46 emigration
Allows dwarves to emigrate from the fortress when stressed, in proportion to how badly stressed they are and adjusted
for who they would have to leave with - a dwarven merchant being more attractive than leaving alone (or with an elf).
The check is made monthly.
A happy dwarf (ie with negative stress) will never emigrate.
Usage:
emigration enable|disable
5.1.47 empty-bin
5.1.48 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 World Viewer and other legends utilities.
Usage:
exportlegends all
• Export just the files included in info (above) to the legends-regionX-YYYYY-MM-DD folder:
exportlegends info
• Export just the custom XML file to the DF folder (no subfolder):
exportlegends custom .
5.1.49 exterminate
exterminate gob
exterminate gob:male
exterminate gob:enemy
To kill a single creature, select the unit with the ‘v’ cursor and:
exterminate this
To purify all elves on the map with fire (may have side-effects):
5.1.50 extinguish
This script allows the user to put out fires affecting map tiles, plants, units, items and buildings.
To select a target, place the cursor over it before running the script. Alternatively, use one of the arguments below.
Arguments:
-all
extinguish everything on the map
-location [ x y z ]
extinguish only at the specified coordinates
5.1.51 feature
• 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.
magma Enable magma furnaces (discovers a random magma feature).
show X Marks the selected map feature as discovered.
hide X Marks the selected map feature as undiscovered.
5.1.52 fillneeds
5.1.53 firestarter
Lights things on fire: items, locations, entire inventories even! Use while viewing an item, unit inventory, or tile to
start fires.
5.1.54 fix-ster
Utilizes the orientation tag to either fix infertile creatures or inflict infertility on creatures that you do not want to
breed. Usage:
fix-ster [fert|ster] [all|animals|only:<creature>]
fert or ster is a required argument; whether to make the target fertile or sterile. Optional arguments specify the
target: no argument for the selected unit, all for all units on the map, animals for all non-dwarf creatures, or
only:<creature> to only process matching creatures.
5.1.55 fixnaked
5.1.56 flashstep
A hotkey-friendly teleport that places your adventurer where your cursor is.
5.1.57 force
5.1.58 forget-dead-body
5.1.59 forum-dwarves
Saves a copy of a text screen, formatted in bbcode for posting to the Bay12 Forums. See markdown to export for
Reddit etc.
This script will attempt to read the current df-screen, and if it is a text-viewscreen (such as the dwarf ‘thoughts’ screen
or an item ‘description’) then append a marked-up version of this text to the target file. Previous entries in the file are
not overwritten, so you may use the ‘forumdwarves’ command multiple times to create a single document containing
the text from multiple screens (eg: text screens from several dwarves, or text screens from multiple artifacts/items, or
some combination).
The screens which have been tested and known to function properly with this script are:
1. dwarf/unit ‘thoughts’ screen
2. item/art ‘description’ screen
3. individual ‘historical item/figure’ screens
There may be other screens to which the script applies. It should be safe to attempt running the script with any screen
active, with an error message to inform you when the selected screen is not appropriate for this script.
The target file’s name is ‘[Link]’. A reminder to this effect will be displayed if the script is successful.
Note: The text will be encoded in CP437, which is likely to be incompatible with the system default. This causes
incorrect display of special characters (eg. é õ ç = é õ ç). You can fix this by opening the file in an editor such as
Notepad++ and selecting the correct encoding before using the text.
5.1.60 full-heal
Attempts to fully heal the selected unit from anything, optionally including death. Usage:
full-heal Completely heal the currently selected unit.
full-heal -unit [unitId] Apply command to the unit with the given ID, instead of selected unit.
full-heal -r [-keep_corpse] Heal the unit, raising from the dead if needed. Add -keep_corpse to
avoid removing their corpse. The unit can be targeted by selecting its corpse on the UI.
full-heal -all [-r] [-keep_corpse] Heal all units on the map.
full-heal -all_citizens [-r] [-keep_corpse] Heal all fortress citizens on the map. Does not include pets.
full-heal -all_civ [-r] [-keep_corpse] Heal all units belonging to your parent civilisation, including pets
and visitors.
For example, full-heal -r -keep_corpse -unit ID_NUM will fully heal unit ID_NUM. If this unit was
dead, it will be resurrected without deleting the corpse - creepy!
5.1.61 gaydar
Shows the sexual orientation of units, useful for social engineering or checking the viability of livestock breeding
programs.
Targets:
-all shows orientation of every creature
-citizens shows only orientation of citizens in fort mode
-named shows orientation of all named units on map
(no target) shows orientation of the unit under the cursor
Orientation filters:
-notStraight only creatures who are not strictly straight
-gayOnly only creatures who are strictly gay
-biOnly only creatures who can get into romances with both sexes
-straightOnly only creatures who are strictly straight
-asexualOnly only creatures who are strictly asexual
5.1.62 geld
5.1.63 ghostly
Toggles an adventurer’s ghost status. Useful for walking through walls, avoiding attacks, or recovering after a death.
5.1.64 growcrops
5.1.65 hermit
Blocks all caravans, migrants, diplomats, and forgotten beasts (not wildlife). Useful for attempting the hermit chal-
lenge.
Use enable or disable to enable/disable, or help for this help.
Warning: This does not block sieges, and may not block visitors or monarchs.
5.1.66 hfs-pit
Creates a pit to the underworld at the cursor, taking three numbers as arguments. Usage: hfs-pit <size>
<walls> <stairs>
The first argument is size of the (square) pit in all directions. The second is 1 to wall off the sides of the pit on all
layers except the underworld, or anything else to leave them open. The third parameter is 1 to add stairs. Stairs are
buggy; they will not reveal the bottom until you dig somewhere, but underworld creatures will path in.
Examples:
hfs-pit 1 0 0
A single-tile wide pit with no walls or stairs.
This is the default if no numbers are given.
hfs-pit 4 0 1
A four-across pit with no stairs but adding walls.
hfs-pit 2 1 0
A two-across pit with stairs but no walls.
5.1.67 hotkey-notes
Lists the key, name, and jump position of your hotkeys in the DFHack console.
5.1.68 install-info
Saves information about the current DFHack installation to [Link] in the current DF folder. Useful
for bug reports.
5.1.69 item-descriptions
Exports a table with custom description text for every item in the game. Used by view-item-info; see instructions there
for how to override for mods.
5.1.70 launch
Activate with a cursor on screen and you will go there rapidly. Attack something first to ride them there.
5.1.71 lever
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 querying the
building and queue a P pull request.
To queue a job at high priority, add --high or --priority:
5.1.72 light-aquifers-only
This script behaves differently depending on whether it’s called pre embark or post embark. Pre embark it changes all
aquifers in the world to light ones, while post embark it only changes the ones at the embark to light ones, leaving the
rest of the world unchanged.
Pre embark: Changes the Drainage of all world tiles that would generate Heavy aquifers into a value that results in
Light aquifers instead.
This script is based on logic revealed by ToadyOne in a FotF answer: [Link]
topic=169696.msg8099138#msg8099138 Basically the Drainage is used as an “RNG” to cause an aquifer to be heavy
about 5% of the time. The script shifts the matching numbers to a neighboring one, which does not result in any
change of the biome.
Post embark: Clears the flags that mark aquifer tiles as heavy, converting them to light.
5.1.73 linger
Enables the player to take control of their adventurer’s killer. Run this script after being presented with “You are
deceased.”
The killer is identified by examining the historical event generated when the adventurer died. If this is unsuccessful,
the killer is assumed to be the last unit to have attacked the adventurer prior to their death.
This will fail if the unit in question is no longer present on the local map.
(Adventure mode only!)
5.1.74 list-agreements
5.1.75 list-waves
This script displays information about migration waves of the specified citizen(s).
Examples:
Selection options:
These options are used to specify what wave information to display
-unit: Displays the highlighted unit’s arrival wave information
-all: Displays all citizens’ arrival wave information
Other options:
-granularity <value>: Specifies the granularity of wave enumeration: years, seasons, months, days
If omitted, the default granularity is seasons, the same as Dwarf Therapist
-showarrival: Shows the arrival information for the selected unit. If -all is specified the info displayed will be
relative to the granularity used. Note: this option is always used when -unit is used.
5.1.76 load-save
When run on the title screen or “load game” screen, loads the save with the given folder name without requiring
interaction. Note that inactive saves (i.e. saves under the “start game” menu) are currently not supported.
Example:
load-save region1
This can also be run when starting DFHack from the command line. For example, on Linux/macOS:
5.1.77 locate-ore
locate-ore list
locate-ore hematite
locate-ore iron
5.1.78 lua
5.1.79 make-legendary
Makes the selected dwarf legendary in one skill, a group of skills, or all skills. View groups with make-legendary
classes, or all skills with make-legendary list. Use make-legendary MINING when you need some-
thing dug up, or make-legendary all when only perfection will do.
5.1.80 make-monarch
5.1.81 markdown
Save a copy of a text screen in markdown (useful for Reddit, among other sites). See forum-dwarves for BBCode
export (for e.g. the Bay12 Forums).
This script will attempt to read the current df-screen, and if it is a text-viewscreen (such as the dwarf ‘thoughts’
screen or an item / creature ‘description’) or an announcement list screen (such as announcements and combat reports)
then append a marked-down version of this text to the target file (for easy pasting on reddit for example). Previous
entries in the file are not overwritten, so you may use the‘‘markdown‘‘ command multiple times to create a single
document containing the text from multiple screens (eg: text screens from several dwarves, or text screens from
multiple artifacts/items, or some combination).
Usage:
5. announements screen
6. combat reports screen
7. latest news (when meeting with liaison)
There may be other screens to which the script applies. It should be safe to attempt running the script with any screen
active, with an error message to inform you when the selected screen is not appropriate for this script.
5.1.82 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.
5.1.83 migrants-now
Forces an immediate migrant wave. Only works after migrants have arrived naturally. Roughly equivalent to mod-
tools/force with:
5.1.84 multicmd
Run multiple dfhack commands. The argument is split around the character ; and all parts are run sequentially as
independent dfhack commands. Useful for hotkeys.
Example:
5.1.85 names
Rename units or items (including artifacts) with the native interface. If a first name is desired, press f. To clear the
current first name, leave this blank.
5.1.86 on-new-fortress
˓→ban-cooking milk;
on-new-fortress 3dveins
5.1.87 once-per-save
Runs commands like multicmd, but only unless not already ran once in current save. You may actually want on-new-
fortress.
Only successfully ran commands are saved.
Parameters:
--help display this help
--rerun commands ignore saved commands
--reset deletes saved commands
5.1.88 open-legends
Open a legends screen when in fortress mode. Requires a world loaded in fortress or adventure mode. Compatible
with exportlegends.
Note that this script carries a significant risk of save corruption if the game is saved after exiting legends mode. To
avoid this:
1. Pause DF
2. Run quicksave to save the game
3. Run open-legends (this script) and browse legends mode as usual
4. Immediately after exiting legends mode, run die to quit DF without saving (saving at this point instead may
corrupt your save)
Note that it should be safe to run “open-legends” itself multiple times in the same DF session, as long as DF is killed
immediately after the last run. Unpausing DF or running other commands risks accidentally autosaving the game,
which can lead to save corruption.
The optional force argument will bypass all safety checks, as well as the save corruption warning.
5.1.89 points
Sets available points at the embark screen to the specified number. Eg. points 1000000 would allow you to buy
everything, or points 0 would make life quite difficult.
5.1.90 position
Reports the current time: date, clock time, month, and season. Also reports location: z-level, cursor position, window
size, and mouse location.
5.1.91 pref-adjust
pref-adjust all removes/changes preferences from all dwarves, and pref-adjust one which works for a
single currently selected dwarf. For either, the script inserts an ‘ideal’ set which is easy to satisfy:
. . . likes iron, steel, weapons, armor, shields/bucklers and plump helmets for their rounded tops. When
possible, she prefers to consume dwarven wine, plump helmets, and prepared meals (quarry bush). She
absolutely detests trolls, buzzards, vultures and crundles.
Additionally, pref-adjust goth will insert a less than ideal set, which is quite challenging, for a single dwarf:
. . . likes dwarf skin, corpses, body parts, remains, coffins, the color black, crosses, glumprongs for their
living shadows and snow demons for their horrifying features. When possible, she prefers to consume
sewer brew, gutter cruor and bloated tubers. She absolutely detests elves, humans and dwarves.
To see what values can be used with each type of preference, use pref-adjust list. Optionally, a single dwarf or
all dwarves can have their preferences cleared manually with the use of pref-adjust clear and pref-adjust
clear_all, respectively. Existing preferences are automatically cleared, normally.
5.1.92 prefchange
Sets preferences for mooding to include a weapon type, equipment type, and material. If you also wish to trigger a
mood, see strangemood.
Valid options:
show show preferences of all units
c clear preferences of selected unit
all clear preferences of all units
axp likes axes, breastplates, and steel
has likes hammers, mail shirts, and steel
swb likes short swords, high boots, and steel
spb likes spears, high boots, and steel
mas likes maces, shields, and steel
xbh likes crossbows, helms, and steel
pig likes picks, gauntlets, and steel
log likes long swords, gauntlets, and steel
dap likes daggers, greaves, and steel
Feel free to adjust the values as you see fit, change the has steel to platinum, change the axp axes to great axes, whatnot.
5.1.93 putontable
Makes item appear on the table, like in adventure mode shops. Arguments:
• -a or --all: apply to all items at the cursor
5.1.94 questport
Sends your adventurer to the location of your quest log map cursor. Usable from travel mode or on foot. Can be used
in situations where fast travel is normally prohibited.
5.1.95 quicksave
If called in dwarf mode, makes DF immediately saves the game by setting a flag normally used in seasonal auto-save.
Keybinding: CtrlAltS in dwarfmode/Default
5.1.96 region-pops
5.1.97 rejuvenate
Decreases the age of the selected dwarf to 20 years. Useful if valuable citizens are getting old.
Arguments:
• -all: applies to all citizens
• -force: also applies to units under 20 years old. Useful if there are too many babies around. . .
• -dry-run: only list units that would be changed; don’t actually change ages
5.1.98 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.
Using the argument -value 0 will reduce stress to the value 0 instead of -1,000,000. Negative values must be
preceded by a backslash (): -value \-10000. Note that this can only be used to decrease stress - it cannot be
increased with this argument.
5.1.99 remove-wear
5.1.100 repeat
Repeatedly calls a lua script at the specified interval. This can be used from init files. Note that any time units other
than frames are unsupported when a world is not loaded (see [Link]()).
Usage examples:
repeat -list
The first example is abstract; the second will regularly remove all contaminants and worn items from the game.
Arguments:
-name sets the name for the purposes of cancelling and making sure you don’t schedule the same repeating event
twice. If not specified, it’s set to the first argument after -command.
-time DELAY -timeUnits UNITS DELAY is some positive integer, and UNITS is some valid time unit for
[Link] (default “ticks”). Units can be in simulation-time “frames” (raw FPS) or “ticks” (only
while unpaused), while “days”, “months”, and “years” are by in-world time.
-command [ ... ] ... specifies the command to be run
-cancel NAME cancels the repetition with the name NAME
-list prints names of scheduled commands
5.1.101 resurrect-adv
Brings a dead adventurer back to life, fully healing them in the process.
This script only targets the current player character in your party, and should be run after being presented with the
“You are deceased” message. It is not possible to resurrect the adventurer after the game has been ended.
5.1.102 reveal-hidden-units
This script exposes all units on the map who are currently sneaking or waiting in ambush and thus hidden from the
player’s view.
Usable in both fortress and adventure mode.
5.1.103 season-palette
5.1.104 set-orientation
Edit a unit’s orientation. Interest levels are 0 for Uninterested, 1 for Romance, 2 for Marry.
unit <UNIT ID> The given unit will be affected. If not found/provided, the script will try defaulting to
the currently selected unit.
male <INTEREST> Set the interest level towards male sexes
female <INTEREST> Set the interest level towards female sexes
opposite <INTEREST> Set the interest level towards the opposite sex to the unit
same <INTEREST> Set the interest level towards the same sex as the unit
random Randomise the unit’s interest towards both sexes, respecting their ORIENTATION token odds.
Other arguments:
help Shows this help page.
view Print the unit’s orientation values in the console.
5.1.105 setfps
Sets the FPS cap at runtime. Useful in case you want to speed up the game or watch combat in slow motion.
Usage:
setfps <number>
5.1.106 show-unit-syndromes
Show syndromes affecting units and the remaining and maximum duration, along with (optionally) substantial detail
on the effects.
Use one or more of the following options:
help Show the help message
showall Show units even if not affected by any syndrome
showeffects Show detailed effects of each syndrome
showdisplayeffects Show effects that only change the look of the unit
selected Show selected unit
dwarves Show dwarves
livestock Show livestock
wildanimals Show wild animals
5.1.107 siren
Wakes up sleeping units and stops parties, either everywhere or in the burrows given as arguments. In return, adds
bad thoughts about noise, tiredness and lack of protection. The script is intended for emergencies, e.g. when a siege
appears, and all your military is partying.
5.1.108 source
Create an infinite magma or water source or drain on a tile. For more complex commands, try the liquids plugin.
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:
5.1.109 spawnunit
5.1.110 startdwarf
Use at the embark screen to embark with the specified number of dwarves. Eg. startdwarf 500 would lead to a
severe food shortage and FPS issues, while startdwarf 10 would just allow a few more warm bodies to dig in.
The number must be 7 or greater.
5.1.111 starvingdead
Somewhere between a “mod” and a “fps booster”, with a small impact on vanilla gameplay. It mostly helps prevent un-
dead cascades in the caverns, where constant combat leads to hundreds of undead roaming the caverns and destroying
your FPS.
With this script running, all undead that have been on the map for one month gradually decay, losing strength, speed,
and toughness. After six months, they collapse upon themselves, never to be reanimated.
Usage: starvingdead (start|stop)
5.1.112 stripcaged
For dumping items inside cages. Will mark selected items for dumping, then a dwarf may come and actually dump
them (or you can use autodump).
Arguments:
list display the list of all cages and their item content on the console
items dump items in the cage, excluding stuff worn by caged creatures
weapons dump equipped weapons
armor dump everything worn by caged creatures (including armor and clothing)
all dump everything in the cage, on a creature or not
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:
5.1.113 superdwarf
superdwarf add
5.1.114 tame
4 expertly trained
5 exceptionally trained
6 masterfully trained
7 tame
8 wild
9 wild
5.1.115 teleport
Examples:
• prints ID of unit beneath cursor:
teleport -showunitid
teleport -showpos
5.1.116 tidlers
Toggle between all possible positions where the idlers count can be placed (see data/init/d_init.txt for
details).
5.1.117 troubleshoot-item
Print various properties of the selected item. Sometimes useful for troubleshooting issues such as why dwarves won’t
pick up a certain item.
5.1.118 twaterlvl
5.1.119 undump-buildings
5.1.120 unforbid
unforbid all
unforbid help
5.1.121 ungeld
5.1.122 unretire-anyone
This script allows the user to play as any living (or undead) historical figure (except for deities) in adventure mode.
To use, simply enter “unretire-anyone” in the DFHack console at the start of adventure mode character creation. You
will be presented with a searchable list from which you may choose your desired historical figure.
This figure will be added to the ‘Specific Person’ list at the bottom of the creature selection page. They can then be
picked for use as a player character, as if regaining control of a retired adventurer.
5.1.123 unsuspend
Unsuspend construction jobs, on a one-off basis. See autounsuspend for regular use.
5.1.124 view-item-info
A script to extend the item or unit viewscreen with additional information including a custom description of each item
(when available), and properties such as material statistics, weapon attacks, armor effectiveness, and more.
The associated script item-descriptions supplies custom descriptions of items. Individual descriptions can be added or
overridden by a similar script raw/scripts/[Link]. Both work as sparse lists, so
missing items simply go undescribed if not defined in the fallback.
5.1.125 view-unit-reports
5.1.126 warn-starving
If any (live) units are starving, very thirsty, or very drowsy, the game will be paused and a warning shown and logged
to the console. Use with the repeat command for regular checks.
Use warn-starving all to display a list of all problematic units.
5.1.127 weather
Prints a map of the local weather, or with arguments clear, rain, and snow changes the weather.
5.1.128 workorder
workorder is a script to queue work orders as in j-m-q menu. It can automatically count how many creatures can
be milked or sheared.
The most simple and obvious usage is automating shearing and milking of creatures using repeat:
It is also possible to define complete work orders using json. It is very similar to what orders import
filename does, with a few key differences. workorder is a planning tool aiming to provide scripting support
for vanilla manager. As such it will ignore work order state like amount_left or is_active and can optionally
take current orders into account. See description of <json>-parameter for more details.
Examples:
• workorder ShearCreature 10 add an order to “Shear Animal” 10 times.
• workorder ShearCreature same, but calculate amount automatically (can be 0).
• workorder MilkCreature same, but “Milk Animal”.
Advanced examples:
• workorder "{\"job\":\"EncrustWithGems\",\"item_category\":[\"finished_goods\"],\"amount
add an order to EncrustWithGems finished_goods using any material (since not specified).
• workorder "{\"job\":\"MilkCreature\",\"item_conditions\":[{\"condition\":\"AtLeast\",\"
same as workorder MilkCreature but with an item condition (“at least 2 empty buckets”).
Usage:
workorder [ --<command> | <jobtype> [<amount>] | <json> | --file <file> ]
<command> one of help, listtypes, verbose, very-verbose
--help this help.
--listtypes filter print all values for all used DF types (job_type, item_type etc.).
<filter> is optional and is applied to type name (using Lua’s string.
find), f.e. workorder -l "manager" is useful.
<jobtype> number or name from df.job_type.
<amount> optional number; if omitted, the script will try to determine amount automatically for some
jobs. Currently supported are MilkCreature and ShearCreature jobs.
<json> json-representation of a workorder. Must be a valid Lua string literal (see advanced examples:
note usage of \). Use orders export some_file_name to get an idea how does the json-
structure look like.
It’s important to note this script behaves differently compared to orders import
some_file_name: workorder is meant as a planning tool and as such it will ignore some
fields like amount_left, is_active or is_validated.
This script doesn’t need values in all fields:
• id is only used for order conditions;
• frequency is set to OneTime by default;
• amount_total can be missing, a function name from this script (one of
calcAmountFor_MilkCreature or calcAmountFor_ShearCreature) or
Lua code called as load(code)(order, orders). Missing amount_total is
equivalent to calcAmountFor_<[Link]>.
A custom field __reduce_amount can be set if existing open orders should be taken into account
reducing new order’s total_amount (possibly all the way to 0). An empty amount_total
implies "__reduce_amount": true.
--file filename loads the json-representation of a workorder from a file in dfhack-config/
workorder/.
Debugging:
--verbose toggle script’s verbosity.
--very-verbose toggle script’s very verbose mode.
--reset reset script environment for next execution.
devel/* scripts are intended for developer use, but many may be of interest to anyone investigating odd phenomena
or just messing around. They are documented to encourage such inquiry.
Some can PERMANENTLY DAMAGE YOUR SAVE if misused, so please be careful. The warnings are real; if in
doubt make backups before running the command.
Contents
• devel/all-bob
• devel/annc-monitor
• devel/check-other-ids
• devel/check-release
• devel/clear-script-env
• devel/click-monitor
• devel/cmptiles
• devel/dump-offsets
• devel/export-dt-ini
• devel/find-offsets
• devel/find-primitive
• devel/find-twbt
• devel/inject-raws
• devel/inspect-screen
• devel/kill-hf
• devel/light
• devel/list-filters
• devel/lsmem
• devel/lua-example
• devel/modstate-monitor
• devel/nuke-items
• devel/pop-screen
• devel/prepare-save
• devel/print-args
• devel/print-args2
• devel/print-event
• devel/query
• devel/save-version
• devel/sc
• devel/scanitemother
• devel/send-key
• devel/spawn-unit-helper
• devel/test-perlin
• devel/unforbidall
• devel/unit-path
• devel/visualize-structure
• devel/watch-minecarts
5.2.1 devel/all-bob
Changes the first name of all units to “Bob”. Useful for testing modtools/interaction-trigger events.
5.2.2 devel/annc-monitor
5.2.3 devel/check-other-ids
This script runs through all [Link] and [Link] vectors and verifies that the items contained
in them have the expected types.
5.2.4 devel/check-release
5.2.5 devel/clear-script-env
5.2.6 devel/click-monitor
Displays the grid coordinates of mouse clicks in the console. Useful for plugin/script development.
Usage: devel/click-monitor start|stop
5.2.7 devel/cmptiles
5.2.8 devel/dump-offsets
This dumps the contents of the table of global addresses (new in 0.44.01).
Passing global names as arguments calls setAddress() to set those globals’ addresses in-game. Passing “all” does this
for all globals.
5.2.9 devel/export-dt-ini
5.2.10 devel/find-offsets
Finding the first few globals requires this script to be started immediately after loading the game, WITHOUT first
loading a world. The rest expect a loaded save, not a fresh embark. Finding current_weather requires a special save
previously processed with devel/prepare-save on a DF version with working dfhack.
The script expects vanilla game configuration, without any custom tilesets or init file changes. Never unpause the
game unless instructed. When done, quit the game without saving using ‘die’.
Arguments:
• global names to force finding them
• all to force all globals
• nofeed to block automated fake input searches
• nozoom to disable neighboring object heuristics
5.2.11 devel/find-primitive
Finds a primitive variable in DF’s data section, relying on the user to change its value. This is similar to devel/find-
offsets, but useful for new variables whose locations are unknown (i.e. they could be part of an existing global).
Usage:
where data-type is a primitive type (int32_t, uint8_t, long, etc.) and each val is a valid value for that type.
Use devel/find-primitive help for a list of valid data types.
5.2.12 devel/find-twbt
5.2.13 devel/inject-raws
5.2.14 devel/inspect-screen
Read the tiles from the screen and display info about them.
5.2.15 devel/kill-hf
Kills the specified historical figure, even if off-site, or terminates a pregnancy. Useful for working around Bug 11549.
Usage:
Arguments:
histfig_id: the ID of the historical figure to target
-p, --pregnancy: if specified, and if the historical figure is pregnant, terminate the pregnancy instead of killing
the historical figure
-n, --dry-run: if specified, only print the name of the historical figure
5.2.16 devel/light
5.2.17 devel/list-filters
List input items for the building currently being built. This is where the filters in lua/dfhack/[Link] come from.
5.2.18 devel/lsmem
Prints memory ranges of the DF process. Useful for checking whether a pointer is valid, whether a certain li-
brary/plugin is loaded, etc.
5.2.19 devel/lua-example
An example Lua script which reports the number of times it has been called. Useful for testing environment persis-
tence.
5.2.20 devel/modstate-monitor
5.2.21 devel/nuke-items
Deletes ALL items not held by units, buildings or jobs. Intended solely for lag investigation.
5.2.22 devel/pop-screen
Forcibly closes the current screen. This is usually equivalent to pressing Esc (LEAVESCREEN), but will bypass the
screen’s input handling. This is intended primarily for development, if you have created a screen whose input handling
throws an error before it handles Esc (or if you have forgotten to handle Esc entirely).
Warning: If you run this script when the current screen does not have a parent, this will cause DF to exit
immediately. These screens include:
• The main fortress mode screen (viewscreen_dwarfmodest)
• The main adventure mode screen (viewscreen_dungeonmodest)
• The main legends mode screen (viewscreen_legendsst)
• The title screen (viewscreen_titlest)
5.2.23 devel/prepare-save
This script prepares the current savegame to be used with devel/find-offsets. It CHANGES THE GAME STATE to
predefined values, and initiates an immediate quicksave, thus PERMANENTLY MODIFYING the save.
5.2.24 devel/print-args
Prints all the arguments you supply to the script on their own line. Useful for debugging other scripts.
5.2.25 devel/print-args2
Prints all the arguments you supply to the script on their own line with quotes around them.
5.2.26 devel/print-event
5.2.27 devel/query
Query is a script useful for finding and reading values of data structure fields. Purposes will likely be exclusive to
writing lua script code.
Fields: contents of tables Keys: contents below non-table containers
Keys and fields are essentially the same thing. The real difference is what code checks need to be in place for queries
on keys vs fields. This is why they are differentiated.
This is a recursive script which takes your selected data {table,unit,item,tile} and then iterates through it, then iterates
through anything it finds. It does this recursively until it has walked over everything it is allowed. Everything it walks
over it checks against any (optional) string/value queries, and if it finds a match it then prints it to the console.
You can control most aspects of this process, the script is fairly flexible. So much so that you can easily create an
infinitely recursing query and/or potentially crash Dwarf Fortress and DFHack. In previous iterations memory bloat
was even a concern, where RAM would be used up in mere minutes or seconds; you can probably get this to happen
as well if you are careless with the depth settings and don’t print everything walked over (i.e. have a search term). The
kill-lua command may be able to stop this script if it gets out of control.
Before recursing or printing things to the console the script checks several things. A few important ones:
• Is the data structure capable of being iterated?
• Is the data structure pointing to a parent data structure?
• Is the current level of recursion too high, and do we need to unwind it first?
• Is the number of entries too high (eg. 70,000 table entries that would be printed)?
• Is the data going to be usefully readable?
• Does the field or key match the field or key query or queries?
• Is printing fields allowed?
• Is printing keys allowed?
Examples:
Selection options:
These options are used to specify where the query will run, or specifically what key to print inside a unit.
-unit: Selects the highlighted unit
-item: Selects the highlighted item.
-tile: Selects the highlighted tile’s block and then attempts to find the tile, and perform your queries on it.
-table <value>: Selects the specified table (ie. ‘value’).
Must use dot notation to denote sub-tables. (eg. -table [Link])
-getfield <value>: Gets the specified field from the selected unit.
Must use dot notation to denote sub-fields. Useful if there would be several matching fields with the input
as a substring (eg. ‘id’, ‘gui’)
Query options:
-query <value>: Searches the selection for fields with substrings matching the specified value.
-querykeys <value>: Lists only keys matching the specified value.
-listall: Lists both fields and keys, useful if you aren’t running a search.
-listfields: Lists fields. Useful if you aren’t running a search.
-listkeys: Lists keys. Useful. Ya, period.
-depth <value>: Limits the field recursion depth (default: 10)
-keydepth <value>: Limits the key recursion depth (default: 4)
-maxtablelength <value>: Limits the table sizes that will be walked (default: 257)
-includeitall: Removes blacklist filtering, and disregards readability of output.
-safer: Disables walking struct data.
Unlike native Lua types, struct data can sometimes be misaligned, which can cause crashes when access-
ing it. This option may be useful if you’re running an alpha or beta build of DFHack.
-dumb: Disables intelligent checks for things such as reasonable recursion depth (i.e. depth maximums are increased,
not removed) and also checks for recursive data structures (i.e. to avoid walking a child that goes to a parent)
Command options:
-debug <value>: Enables debug log lines equal to or less than the value provided. Some lines are commented out
entirely, and you probably won’t even use this.. but hey, now you know it exists.
-disableprint: Disables printing fields and keys. Might be useful if you are debugging this script. Or to see if a
query will crash (faster) but not sure what else you could use it for.
-help: Prints this help information.
5.2.28 devel/save-version
5.2.29 devel/sc
Size Check: scans structures for invalid vectors, misaligned structures, and unidentified enum values.
Note: This script can take a very long time to complete, and DF may be unresponsive while it is running. You can
use kill-lua to interrupt this script.
Examples:
• scan world:
devel/sc
devel/sc -all
devel/sc [expr]
5.2.30 devel/scanitemother
5.2.31 devel/send-key
Send a key to the current screen or a parent. If you are trying to dismiss a screen, devel/pop-screen may be more
useful, particularly if the screen is unresponsive to Esc.
Usage:
• KEY_NAME is the name of an interface_key - a full list of valid names can be obtained by running lua
@df.interface_key, looking in data/init/[Link], or by checking [Link].
xml in the df-structures repository.
• X (optional) - if specified, the key is sent to the screen X screens above the current screen in the screen stack
(e.g. 1 corresponds to the current screen’s parent)
5.2.32 devel/spawn-unit-helper
5.2.33 devel/test-perlin
5.2.34 devel/unforbidall
5.2.35 devel/unit-path
5.2.36 devel/visualize-structure
Displays the raw memory of a structure, separated by field. Useful for checking if structures are aligned.
5.2.37 devel/watch-minecarts
fix/* scripts fix various bugs and issues, some of them obscure.
Contents
• fix/blood-del
• fix/build-location
• fix/dead-units
• fix/diplomats
• fix/dry-buckets
• fix/fat-dwarves
• fix/feeding-timers
• fix/item-occupancy
• fix/loyaltycascade
• fix/merchants
• fix/population-cap
• fix/retrieve-units
• fix/stable-temp
• fix/stuck-merchants
• fix/stuckdoors
• fix/tile-occupancy
5.3.1 fix/blood-del
Makes it so that future caravans won’t bring barrels full of blood, ichor, or goo.
5.3.2 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.
5.3.3 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.
5.3.4 fix/diplomats
Adds a Diplomat position to all Elven civilizations, allowing them to negotiate tree cutting quotas - and you to violate
them and start wars. This was vanilla behaviour until version 0.31.12, in which the “bug” was “fixed”.
5.3.5 fix/dry-buckets
Removes water from all buckets in your fortress, allowing them to be used for making lye. Skips buckets in buildings
(eg a well), being carried, or currently used by a job.
5.3.6 fix/fat-dwarves
Avoids 5-10% FPS loss due to constant recalculation of insulation for dwarves at maximum fatness, by reducing the
cap from 1,000,000 to 999,999. Recalculation is triggered in steps of 250 units, and very fat dwarves constantly
bounce off the maximum value while eating.
5.3.7 fix/feeding-timers
5.3.8 fix/item-occupancy
Diagnoses and fixes issues with nonexistant ‘items occupying site’, usually caused by autodump bugs or other hacking
mishaps. Checks that:
1. Item has flags.on_ground <=> it is in the correct block item list
2. A tile has items in block item list <=> it has [Link]
3. The block item lists are sorted
5.3.9 fix/loyaltycascade
Aborts loyalty cascades by fixing units whose own civ is the enemy.
5.3.10 fix/merchants
Adds the Guild Representative position to all Human civilizations, allowing them to make trade agreements. This was
the default behaviour in version 0.28.181.40d and earlier.
5.3.11 fix/population-cap
Run this after every migrant wave to ensure your population cap is not exceeded.
The reason for population cap problems is that the population value it is compared against comes from the last dwarven
caravan that successfully left for mountainhomes. This script instantly updates it. Note that a migration wave can still
overshoot the limit by 1-2 dwarves because of the last migrant bringing his family. Likewise, king arrival ignores cap.
5.3.12 fix/retrieve-units
This script forces some units off the map to enter the map, which can fix issues such as the following:
• Stuck [SIEGE] tags due to invisible armies (or parts of armies)
• Forgotten beasts that never appear
• Packs of wildlife that are missing from the surface or caverns
• Caravans that are partially or completely missing.
Note: For caravans that are missing entirely, this script may retrieve the merchants but not the items. Using fix/stuck-
merchants followed by force to create a new caravan may work better.
5.3.13 fix/stable-temp
Instantly sets the temperature of all free-lying items to be in equilibrium with the environment, which stops temperature
updates until something changes. To maintain this efficient state, use tweak fast-heat.
5.3.14 fix/stuck-merchants
Dismisses merchants that haven’t entered the map yet. This can fix Bug 9593. This script should probably not be run
if any merchants are on the map, so using it with repeat is not recommended.
Run fix/stuck-merchants -n or fix/stuck-merchants --dry-run to list all merchants that would
be dismissed but make no changes.
5.3.15 fix/stuckdoors
Fix doors that are stuck open due to incorrect map occupancy flags, eg due to incorrect use of teleport.
5.3.16 fix/tile-occupancy
Clears bad occupancy flags at the selected tile. Useful for getting rid of phantom “building present” messages. Cur-
rently only supports issues with building and unit occupancy. Requires that a tile is selected with the in-game cursor
(k).
Can be used to fix problematic tiles caused by Issue 1047.
Contents
• gui/advfort
• gui/advfort_items
• gui/assign-rack
• gui/autobutcher
• gui/autogems
• gui/choose-weapons
• gui/clone-uniform
• gui/color-schemes
• gui/companion-order
• gui/confirm-opts
• gui/cp437-table
• gui/create-item
• gui/create-tree
• gui/dfstatus
• gui/extended-status
• gui/family-affairs
• gui/gm-editor
• gui/gm-unit
• gui/guide-path
• gui/hack-wish
• gui/hello-world
• gui/liquids
• gui/load-screen
• gui/manager-quantity
• gui/mechanisms
• gui/mod-manager
• gui/no-dfhack-init
• gui/pathable
• gui/power-meter
• gui/prerelease-warning
• gui/quickcmd
• gui/rename
• gui/room-list
• gui/settings-manager
• gui/siege-engine
• gui/stamper
• gui/stockpiles
• gui/teleport
• gui/unit-info-viewer
• gui/workflow
• gui/workshop-job
5.4.1 gui/advfort
This script allows performing jobs in adventure mode. For more complete help press ? while the script is running. It’s
most comfortable to use this as a keybinding (see below for the default binding). Possible arguments:
• -a, --nodfassign: uses a different method to assign job items, instead of relying on DF.
• -i, --inventory: checks inventory for possible items to use in the job.
• -c, --cheat: relaxes item requirements for buildings (e.g. walls from bones). Implies -a
• -e [NAME], --entity [NAME]: uses the given civ to determine available resources (specified as an entity
raw ID). Defaults to MOUNTAIN; if the entity name is omitted, uses the adventurer’s civ
• job: selects the specified job (must be a valid job_type, e.g. Dig or FellTree)
Warning: changes only persist in non-procedural sites, namely player forts, caves, and camps.
5.4.2 gui/advfort_items
5.4.3 gui/assign-rack
This script requires a binpatch, which has not been available since DF 0.34.11
See Bug 1445 for more info about the patches.
Keybinding: P in dwarfmode/QueryBuilding/Some/Weaponrack
5.4.4 gui/autobutcher
An in-game interface for autobutcher. This script must be called from either the overall status screen or the animal list
screen.
Keybinding: ShiftB in pet/List/Unit
5.4.5 gui/autogems
A frontend for the autogems plugin that allows configuring the gem types to be cut.
The following controls apply to the gems currently listed:
• s: Searches for matching gems
• Shift+Enter: Toggles the status of all listed gems
The following controls apply to the gems currently listed, as well as gems listed before the current search with s, if
applicable:
• r: Displays only “rock crystal” gems
• c: Displays only gems whose color matches the selected gem
• m: Displays only gems where at least one rough (uncut) gem is available somewhere on the map
This behavior is intended to allow for things like a search for “lazuli” followed by pressing c to select all gems with
the same color as lapis lazuli (5 blue gems in vanilla DF), rather than further restricting that to gems with “lazuli” in
their name (only 1).
x clears all filters, which is currently the only way to undo filters (besides searching), and is useful to verify the gems
selected.
5.4.6 gui/choose-weapons
5.4.7 gui/clone-uniform
When invoked, the script duplicates the currently selected uniform template, and selects the newly created copy.
Activate in the Uniforms page of the military screen with the cursor in the leftmost list.
Keybinding: CtrlC in layer_military/Uniforms
5.4.8 gui/color-schemes
An in-game interface for color-schemes. This script must be called from either the title screen or the dwarf fortress
default screen.
5.4.9 gui/companion-order
A script to issue orders for companions. Select companions with lower case chars (green when selected), issue orders
with upper case. Must be in look or talk mode to issue command on tile (e.g. move/equip/pick-up).
• 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)
Can be called with ‘-c’ flag to display “cheating” commands.
• patch up - fully heals the companion
• get in - rides e.g. minecart at cursor. Bit buggy as unit will teleport to the item when e.g. pushing it.
Keybinding: ShiftO in dungeonmode
5.4.10 gui/confirm-opts
5.4.11 gui/cp437-table
An in-game CP437 table. Allows typing or selecting characters with the mouse. Input is fed directly to the parent
screen when “enter” is pressed, so there should be a text field selected before running this script.
5.4.12 gui/create-item
5.4.13 gui/create-tree
5.4.14 gui/dfstatus
Show a quick overview of critical stock quantities, including food, drinks, wood, and various bars. Sections can be
enabled/disabled/configured by editing dfhack-config/[Link].
Keybinding: CtrlShiftI in dwarfmode/Default
Keybinding: CtrlShiftI in dfhack/lua/dfstatus
5.4.15 gui/extended-status
gui/extended-status enable|disable|help|subpage_names
enable|disable gui/extended-status
5.4.16 gui/family-affairs
A user-friendly interface to view romantic relationships, with the ability to add, remove, or otherwise change them at
your whim - fantastic for depressed dwarves with a dead spouse (or matchmaking players. . . ).
The target/s must be alive, sane, and in fortress mode.
gui/family-affairs [unitID] shows GUI for the selected unit, or the specified unit ID
gui/family-affairs divorce [unitID] removes all spouse and lover information from the unit and it’s
partner, bypassing almost all checks.
gui/family-affairs [unitID] [unitID] divorces the two specified units and their partners, then ar-
ranges for the two units to marry, bypassing almost all checks. Use with caution.
5.4.17 gui/gm-editor
This editor allows to change and modify almost anything in df. Press ? for in-game help. There are multiple ways to
open this editor:
• Calling gui/gm-editor from a command or keybinding opens the editor on whatever 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 "[Link]" shows all items)
• using gui/gm-editor dialog - shows an in game dialog to input lua command. Works the same as version
above.
• using gui/gm-editor toggle - will hide (if shown) and show (if hidden) editor at the same position you
left it
5.4.18 gui/gm-unit
5.4.19 gui/guide-path
Activate in the Hauling menu with the cursor over a Guide order.
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.
Keybinding: AltP in dwarfmode/Hauling/DefineStop/Cond/Guide
5.4.20 gui/hack-wish
5.4.21 gui/hello-world
5.4.22 gui/liquids
This script is a gui front-end to liquids and works similarly, allowing you to add or remove water & magma, and create
obsidian walls & floors.
Warning: There is no undo support. 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 “perma-
nent 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.
Keybinding: AltL in dwarfmode/LookAround
5.4.23 gui/load-screen
5.4.24 gui/manager-quantity
Sets the quantity of the selected manager job (in the j-m or u-m screens).
Keybinding: AltQ in jobmanagement/Main
5.4.25 gui/mechanisms
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.
ShiftEnter has an effect equivalent to pressing Enter, and then re-entering the mechanisms UI.
Keybinding: CtrlM in dwarfmode/QueryBuilding/Some
5.4.26 gui/mod-manager
A simple way to install and remove small mods, which are not included in DFHack. Examples are available here.
Each mod is a lua script located in <DF>/mods/, which MUST define the following variables:
name a name that is displayed in list
5.4.27 gui/no-dfhack-init
5.4.28 gui/pathable
Highlights each visible map tile to indicate whether it is possible to path to from the tile at the cursor - green if possible,
red if not, similar to gui/siege-engine. A few options are available:
• l: Lock cursor: when enabled, the movement keys move around the map instead of moving the cursor. This is
useful to check whether parts of the map far away from the cursor can be pathed to from the cursor.
• d: Draw: allows temporarily disabling the highlighting entirely.
• u: Skip unrevealed: when enabled, unrevealed tiles will not be highlighed at all. (These would otherwise be
highlighted in red.)
Note: This tool uses a cache used by DF, which currently does not account for climbing. If an area of the map is
only accessible by climbing, this tool may report it as inaccessible. Care should be taken when digging into the upper
levels of caverns, for example.
5.4.29 gui/power-meter
Activate an in-game interface for power-meter after selecting Pressure Plate in the build menu.
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.
Keybinding: CtrlShiftM in dwarfmode/Build/Position/Trap
5.4.30 gui/prerelease-warning
5.4.31 gui/quickcmd
A list of commands which you can edit while in-game, and which you can execute quickly and easily. For stuff you
use often enough to not want to type it, but not often enough to be bothered to find a free keybinding.
5.4.32 gui/rename
Backed by rename, 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.
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.
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.
Keybinding: CtrlShiftN
Keybinding: CtrlShiftT -> "gui/rename unit-profession"
5.4.33 gui/room-list
Activate in q mode, either immediately or after opening the assign owner page.
The script lists other rooms owned by the same owner, or by the unit selected in the assign list, and allows unassigning
them.
Keybinding: AltR in dwarfmode/QueryBuilding/Some
5.4.34 gui/settings-manager
5.4.35 gui/siege-engine
Activate an in-game interface for siege-engine, after selecting a siege engine in q mode.
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 desig-
nations. 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. ShiftEsc retains
the current viewport, and also exits from the q mode to main menu.
Keybinding: AltA in dwarfmode/QueryBuilding/Some/SiegeEngine
5.4.36 gui/stamper
allows manipulation of designations by transforms such as translations, reflections, rotations, and inversion. designa-
tions can also be used as brushes to erase other designations and cancel constructions.
5.4.37 gui/stockpiles
An in-game interface for stockpiles, to load and save stockpile settings from the q menu.
Usage:
5.4.38 gui/teleport
A front-end for the teleport script that allows choosing a unit and destination using the in-game cursor.
5.4.39 gui/unit-info-viewer
Displays age, birth, maxage, shearing, milking, grazing, egg laying, body size, and death info about a unit.
Keybinding: AltI in dwarfmode/ViewUnits|unitlist
5.4.40 gui/workflow
Bind to a key (the example config uses Alt-W), and activate with a job selected in a workshop in q mode.
This script provides a simple interface to constraints managed by workflow. 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 the workflow documentation. In this
manner, this feature can be used for troubleshooting jobs that don’t match the right constraints.
If you select one of the outputs with Enter, the matching constraint is simply added to the list. If you use
ShiftEnter, the interface proceeds to the next dialog, which allows you to edit the suggested constraint param-
eters to suit your need, and set the item count range.
Pressing s (or, with the example config, Alt-W in the z stocks screen) opens the overall status screen:
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).
Keybinding: AltW in dwarfmode/QueryBuilding/Some/Workshop/Job
Keybinding: AltW -> "gui/workflow status" in overallstatus
Keybinding: AltW -> "gui/workflow status" in dfhack/lua/status_overlay
5.4.41 gui/workshop-job
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.
Pressing m, unless the item type does not allow a material, lets you choose a material.
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 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.
Keybinding: AltA in dwarfmode/QueryBuilding/Some/Workshop/Job
modtools/* scripts provide tools for modders, often with changes to the raw files, and are not intended to be called
manually by end-users.
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.
Argument names are preceded with a dash, and supplying the same argument name multiple times will result in an
error.
The -help argument to any modtools script will print a descriptive usage string describing the arguments, similar
to the documentation here.
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.
Contents
• modtools/add-syndrome
• modtools/anonymous-script
• modtools/change-build-menu
• modtools/create-item
• modtools/create-tree
• modtools/create-unit
• modtools/equip-item
• modtools/extra-gamelog
• modtools/force
• modtools/if-entity
• modtools/interaction-trigger
• modtools/invader-item-destroyer
• modtools/item-trigger
• modtools/moddable-gods
• modtools/outside-only
• modtools/pref-edit
• modtools/projectile-trigger
• modtools/random-trigger
• modtools/raw-lint
• modtools/reaction-product-trigger
• modtools/reaction-trigger
• modtools/reaction-trigger-transition
• modtools/set-belief
• modtools/set-need
• modtools/set-personality
• modtools/skill-change
• modtools/spawn-flow
• modtools/spawn-liquid
• modtools/syndrome-trigger
• modtools/transform-unit
5.5.1 modtools/add-syndrome
-syndrome name
the name of the syndrome to operate on
examples:
"gila monster bite"
-resetPolicy policy
specify a policy of what to do if the unit already has an
instance of the syndrome. examples:
NewInstance
default behavior: create a new instance of the syndrome
DoNothing
ResetDuration
AddDuration
-erase
instead of adding an instance of the syndrome, erase one
-eraseAll
erase every instance of the syndrome
-eraseClass SYN_CLASS
erase every instance of every syndrome with the given SYN_CLASS
-target id
the unit id of the target unit
examples:
0
28
-skipImmunities
add the syndrome to the target even if it is immune to the syndrome
5.5.2 modtools/anonymous-script
This allows running a short simple Lua script passed as an argument instead of running a script from a file. This is
useful when you want to do something too complicated to make with the existing modtools, but too simple to be worth
its own script file. Example:
5.5.3 modtools/change-build-menu
• MECHANICS
• SIEGE
• BUTCHERS
• LEATHERWORKS
• TANNERS
• CLOTHIERS
• FISHERY
• STILL
• LOOM
• QUERN
• KENNELS
• ASHERY
• KITCHEN
• DYERS
• TOOL
• MILLSTONE
• WOOD_FURNACE
• SMELTER
• GLASS_FURNACE
• MAGMA_SMELTER
• MAGMA_GLASS_FURNACE
• MAGMA_KILN
• KILN
modtools/change-build-menu remove <ID> <CATEGORY>:
Remove the workshop or furnace with the ID <ID> from <CATEGORY>.
<CATEGORY> and <ID> may have the same values as for the “add” option.
modtools/change-build-menu revert <ID> <CATEGORY>:
Revert an earlier remove or add operation. It is NOT safe to “remove” an “add”ed building or vice versa,
use this option to reverse any changes you no longer want/need.
Module Usage:
To use this script as a module put the following somewhere in your own script:
Then you can call the functions documented here like so:
• Example: Remove the carpenters workshop:
Note that to allow any of your changes to take effect you need to start the ticker. See the “Command Usage” section.
Global Functions:
GetWShopID(btype, bsubtype, bcustom): GetWShopID returns a workshop’s or furnace’s string ID
based on its numeric ID triplet. This string ID should match what is expected by eventful for hardcoded build-
ings.
GetWShopType(id): GetWShopIDs returns a workshop or furnace’s ID numbers as a table. The passed in ID
should be the building’s string identifier, it makes no difference if it is a custom building or a hardcoded one.
The return table is structured like so: {type, subtype, custom}
IsEntityPermitted(id): IsEntityPermitted returns true if DF would normally allow you to build a workshop
or furnace. Use this if you want to change a building, but only if it is permitted in the current entity. You do not
need to specify an entity, the current fortress race is used.
ChangeBuilding(id, category, [add, [key]]):
ChangeBuildingAdv(typ, subtyp, custom, category, [add, [key]]): These two functions
apply changes to the build sidebar menus. If “add” is true then the building is added to the specified category,
else it is removed. When adding you may specify “key”, a string DF hotkey ID.
The first version of this function takes a workshop or furnace ID as a string, the second takes a numeric ID triplet
(which can specify any building, not just workshops or furnaces).
RevertBuildingChanges(id, category):
RevertBuildingChangesAdv(typ, subtyp, custom, category): These two functions revert
changes made by “ChangeBuilding” and “ChangeBuildingAdv”. Like those two functions there are two
versions, a simple one that takes a string ID and one that takes a numeric ID triplet.
5.5.4 modtools/create-item
Replaces the createitem plugin, with standard arguments. The other versions will be phased out in a later version.
Arguments:
-creator id
specify the id of the unit who will create the item,
or \\LAST to indicate the unit with id [Link].unit_next_id-1
examples:
0
2
\\LAST
-material matstring
specify the material of the item to be created
examples:
INORGANIC:IRON
CREATURE_MAT:DWARF:BRAIN
PLANT_MAT:MUSHROOM_HELMET_PLUMP:DRINK
-item itemstr
specify the itemdef of the item to be created
examples:
WEAPON:ITEM_WEAPON_PICK
(continues on next page)
5.5.5 modtools/create-tree
Spawns a tree.
Usage:
-tree treeName
specify the tree to be created
examples:
OAK
NETHER_CAP
-age howOld
set the age of the tree in years (integers only)
defaults to 1 if omitted
-location [ x y z ]
create the tree at the specified coordinates
example:
modtools/create-tree -tree OAK -age 100 -location [ 33 145 137 ]
5.5.6 modtools/create-unit
-caste casteName
Specify the caste of the unit to be created.
If omitted, the caste is randomly selected.
examples:
MALE
FEMALE
DEFAULT
-domesticate
Tames the unit if it lacks the CAN_LEARN and CAN_SPEAK tokens.
-civId id
Make the created unit a member of the specified civilisation
(continues on next page)
-groupId id
Make the created unit a member of the specified group
(or none if id = -1). If id is \\LOCAL, make it a member of the
group associated with the fort; otherwise id must be an integer
-setUnitToFort
Sets the groupId and civId to those of the player in Fortress mode.
Equivalent to -civId \\LOCAL and -groupId \\LOCAL.
-name entityRawName
Set the unit's name to be a random name appropriate for the
given entity. \\LOCAL can be specified instead to automatically
use the fort group entity in fortress mode only.
examples:
MOUNTAIN
EVIL
-nick nickname
This can be included to nickname the unit.
Replace "nickname" with the desired name.
-age howOld
This can be included to specify the unit's age.
Replace "howOld" with a (non-negative) number.
The unit's age is set randomly if this is omitted.
-profession token
This can be included to set the unit's profession.
Replace "token" with a Unit Type Token (check the DF Wiki for a list).
For skill-based professions, it is recommended to give the unit
the appropriate skill set via -skills.
This can also be used to make animals trained for war/hunting.
Note that this will be overridden if the unit has been given the age
of a baby or child, as these have a special "profession" set.
Using this for setting baby/child status is not recommended;
this should be done via -age instead.
examples:
STRAND_EXTRACTOR
MASTER_SWORDSMAN
TRAINED_WAR
-customProfession name
This can be included to give the unit a custom profession name.
Enclose the name in quotation marks if it includes spaces.
example:
-customProfession "Destroyer of Worlds"
-duration ticks
If this is included, the unit will vanish in a puff of smoke
once the specified number of ticks has elapsed.
Replace "ticks" with an integer greater than 0.
Note that the unit's equipment will not vanish.
-quantity howMany
This can be included to create multiple creatures simultaneously.
Replace "howMany" with the desired number of creatures.
Quantity defaults to 1 if this is omitted.
-location [ x y z ]
(obligatory)
Specify the coordinates where you want the unit to appear.
5.5.7 modtools/equip-item
Force a unit to equip an item with a particular body part; useful in conjunction with the create scripts above. See
also forceequip.
5.5.8 modtools/extra-gamelog
This script writes extra information to the gamelog. This is useful for tools like Soundsense.
Usage:
modtools/extra-gamelog enable
modtools/extra-gamelog disable
5.5.9 modtools/force
-eventType event
specify the type of the event to trigger
(continues on next page)
5.5.10 modtools/if-entity
5.5.11 modtools/interaction-trigger
This triggers events when a unit uses an interaction on another. It works by scanning the announcements for the correct
attack verb, so the attack verb must be specified in the interaction. It includes an option to suppress this announcement
after it finds it.
Usage:
-clear
unregisters all triggers
-onAttackStr str
trigger the command when the attack verb is "str". both onAttackStr and
˓→onDefendStr MUST be specified
-onDefendStr str
trigger the command when the defend verb is "str". both onAttackStr and
˓→onDefendStr MUST be specified
-suppressAttack
(continues on next page)
You must specify both an attack string and a defend string to guarantee correct performance. Either will trigger the
script when it happens, but it will not be triggered twice in a row if both happen.
5.5.12 modtools/invader-item-destroyer
This tool configurably destroys invader items to prevent clutter or to prevent the player from getting tools exclusive to
certain races.
Arguments:
-clear
reset all registered data
-allEntities [true/false]
set whether it should delete items from invaders from any civ
-allItems [true/false]
set whether it should delete all invader items regardless of
type when an appropriate invader dies
-item itemdef
set a particular itemdef to be destroyed when an invader
from an appropriate civ dies. examples:
ITEM_WEAPON_PICK
-entity entityName
set a particular entity up so that its invaders destroy their
items shortly after death. examples:
MOUNTAIN
EVIL
5.5.13 modtools/item-trigger
This powerful tool triggers DFHack commands when a unit equips, unequips, or attacks another unit with specified
item types, specified item materials, or specified item contaminants.
Arguments:
-clear
clear all registered triggers
-checkAttackEvery n
check the attack event at least every n ticks
-checkInventoryEvery n
(continues on next page)
5.5.14 modtools/moddable-gods
This is a standardized version of Putnam’s moddableGods script. It allows you to create gods on the command-line.
Arguments:
-name godName
sets the name of the god to godName
if there's already a god of that name, the script halts
-spheres [ sphereList ]
define a space-separated list of spheres of influence of the god
-gender male|female|neuter
sets the gender of the god
-depictedAs str
often depicted as a str
-verbose
if specified, prints details about the created god
5.5.15 modtools/outside-only
This allows you to specify certain custom buildings as outside only, or inside only. If the player attempts to build a
building in an inappropriate location, the building will be destroyed.
Arguments:
-clear
clears the list of registered buildings
-checkEvery n
set how often existing buildings are checked for whether they
are in the appropriate location to n ticks
-type [EITHER, OUTSIDE_ONLY, INSIDE_ONLY]
specify what sort of restriction to put on the building
-building name
specify the id of the building
5.5.16 modtools/pref-edit
Add, remove, or edit the preferences of a unit. Requires a modifier, a unit argument, and filters.
• -unit <UNIT ID>: The given unit will be affected. If not found/provided, the script will try defaulting to
the currently selected unit.
Valid modifiers:
• -add: Add a new preference to the unit. Filters describe the preference’s variables.
• -remove: Remove a preference from the unit. Filters describe what preference to remove.
• -has: Checks if the unit has a preference matching the filters. Prints a message in the console.
• -removeall: Remove all preferences from the unit. Doesn’t require any filters.
Valid filters:
• -id <VALUE>: This is the ID used for all preferences that require an ID. Represents item_type, crea-
ture_id, color_id, shape_id, plant_id, poetic_form_id, musical_form_id, and dance_form_id. Text IDs
(e.g. “TOAD”, “AMBER”) can be used for all but poetic, musical, and dance.
• -item, -creature, -color, -shape, -plant, -poetic, -musical, -dance: Include one of these
to describe what the id argument represents.
• -type <PREFERENCE TYPE>: This describes the type of the preference. Can be entered either using the
numerical ID or text id. Run lua @df.unit_preference.T_type for a full list of valid values.
• -subtype <ID>: The value for an item’s subtype
• -material <ID>: The id of the material. For example “MUSHROOM_HELMET_PLUMP:DRINK” or
“INORGANIC:IRON”.
• -state <STATE ID>: The state of the material. Values can be the numerical or text ID. Run lua @df.
matter_state for a full list of valid values.
• -active <TRUE/FALSE>: Whether the preference is active or not (?)
Other arguments:
• -help: Shows this help page.
Example usage:
• Like drinking dwarf blood:
5.5.17 modtools/projectile-trigger
This triggers dfhack commands when projectiles hit their targets. Usage:
-clear
unregister all triggers
-material
specify a material for projectiles that will trigger the command
examples:
INORGANIC:IRON
CREATURE_MAT:DWARF:BRAIN
PLANT_MAT:MUSHROOM_HELMET_PLUMP:DRINK
-command [ commandList ]
\\LOCATION
\\PROJECTILE_ID
\\FIRER_ID
\\anything -> \anything
anything -> anything
5.5.18 modtools/random-trigger
Trigger random dfhack commands with specified probabilities. Register a few scripts, then tell it to “go” and it will
pick one based on the probability weights you specified.
Events are mutually-exclusive - register a list of scripts along with relative weights, then tell the script to select and
run one with the specified probabilities. The weights must be positive integers, but they do NOT have to sum to any
particular number.
The outcomes are mutually exclusive: only one will be triggered. If you want multiple independent random events,
call the script multiple times.
99% of the time, you won’t need to worry about this, but just in case, you can specify a name of a list of outcomes
to prevent interference from other scripts that call this one. That also permits situations where you don’t know until
runtime what outcomes you want. For example, you could make a modtools/reaction-trigger that registers the worker
as a mayor candidate, then run this script to choose a random mayor from the list of units that did the mayor reaction.
Arguments:
-outcomeListName name
specify the name of this list of outcomes to prevent interference
if two scripts are registering outcomes at the same time. If none
is specified, the default outcome list is selected automatically.
-command [ commandStrs ]
specify the command to be run if this outcome is selected
must be specified unless the -trigger argument is given
-weight n
the relative probability weight of this outcome
n must be a non-negative integer
if not specified, n=1 is used by default
-trigger
selects a random script based on the specified outcomeList
(or the default one if none is specified)
-preserveList
when combined with trigger, preserves the list of outcomes so you
don't have to register them again.
-withProbability p
p is a real number between 0 and 1 inclusive
triggers the command immediately with this probability
-seed s
sets the random seed for debugging purposes
(guarantees the same sequence of random numbers will be produced)
use
-listOutcomes
lists the currently registered list of outcomes of the outcomeList
along with their probability weights, for debugging purposes
-clear
unregister everything
Note: -preserveList is something of a beta feature, which should be avoided by users without a specific reason
to use it.
It is highly recommended that you always specify -outcomeListName when you give this command to prevent
almost certain interference. If you want to trigger one of 5 outcomes three times, you might want this option even
without -outcomeListName.
The list is NOT retained across game save/load, as nobody has yet had a use for this feature. Contact expwnent if you
would use it; it’s not that hard but if nobody wants it he won’t bother.
5.5.19 modtools/raw-lint
Checks for simple issues with raw files. Can be run automatically.
5.5.20 modtools/reaction-product-trigger
This triggers dfhack commands when reaction products are produced, once per product. Usage:
-clear
unregister all reaction hooks
-reactionName name
specify the name of the reaction
-command [ commandStrs ]
specify the command to be run on the target(s)
special args
\\WORKER_ID
\\REACTION
\\BUILDING_ID
\\LOCATION
\\INPUT_ITEMS
\\OUTPUT_ITEMS
\\anything -> \anything
anything -> anything
5.5.21 modtools/reaction-trigger
Triggers dfhack commands when custom reactions complete, regardless of whether it produced anything, once per
completion. Arguments:
-clear
unregister all reaction hooks
-reactionName name
specify the name of the reaction
-syndrome name
specify the name of the syndrome to be applied to valid targets
-allowNonworkerTargets
allow other units to be targeted if the worker is invalid or ignored
-allowMultipleTargets
allow all valid targets within range to be affected
if absent:
if running a script, only one target will be used
if applying a syndrome, then only one target will be infected
-ignoreWorker
ignores the worker when selecting the targets
-dontSkipInactive
when selecting targets in range, include creatures that are inactive
dead creatures count as inactive
-range [ x y z ]
controls how far elligible targets can be from the workshop
defaults to [ 0 0 0 ] (on a workshop tile)
negative numbers can be used to ignore outer squares of the workshop
line of sight is not respected, and the worker is always within range
-resetPolicy policy
the policy in the case that the syndrome is already present
policy
NewInstance (default)
DoNothing
ResetDuration
AddDuration
-command [ commandStrs ]
specify the command to be run on the target(s)
special args
\\WORKER_ID
\\TARGET_ID
(continues on next page)
5.5.22 modtools/reaction-trigger-transition
Prints useful things to the console and a file to help modders transition from autoSyndrome to modtools/reaction-
trigger.
This script is basically an apology for breaking backward compatibility in June 2014, and will be removed eventually.
5.5.23 modtools/set-belief
Changes the beliefs (values) of units. Requires a belief, modifier, and a target.
Valid beliefs:
all Apply the edit to all the target’s beliefs
belief <ID> ID of the belief to edit. For example, 0 or LAW.
Valid modifiers:
set <-50-50> Set belief to given strength.
tier <1-7> Set belief to within the bounds of a strength tier:
Value Strength
1 Lowest
2 Very Low
3 Low
4 Neutral
5 High
6 Very High
7 Highest
modify <amount> Modify current belief strength by given amount. Negative values need a \ before the
negative symbol e.g. \-1
step <amount> Modify current belief tier up/down by given amount. Negative values need a \ before
the negative symbol e.g. \-1
random Use the default probabilities to set the belief to a new random value.
default Belief will be set to cultural default.
Valid targets:
citizens All (sane) citizens of your fort will be affected. Will do nothing in adventure mode.
unit <UNIT ID> The given unit will be affected.
If no target is given, the provided unit can’t be found, or no unit id is given with the unit argument, the script will try
and default to targeting the currently selected unit.
Other arguments:
help Shows this help page.
list Prints a list of all beliefs + their IDs.
noneed By default, unit’s needs will be recalculated to reflect new beliefs after every run. Use this
argument to disable that functionality.
listunit Prints a list of all a unit’s beliefs. Cultural defaults are marked with *.
5.5.24 modtools/set-need
5.5.25 modtools/set-personality
Value Strength
1 Lowest
2 Very Low
3 Low
4 Neutral
5 High
6 Very High
7 Highest
modify <amount> Modify current base trait strength by given amount. Negative values need a \ before
the negative symbol e.g. \-1
step <amount> Modify current trait tier up/down by given amount. Negative values need a \ before the
negative symbol e.g. \-1
random Set the trait to a new random value.
average Sets trait to the creature’s caste’s average value (as defined in the PERSONALITY creature
tokens).
Valid targets:
citizens All (sane) citizens of your fort will be affected. Will do nothing in adventure mode.
unit <UNIT ID> The given unit will be affected.
If no target is given, the provided unit can’t be found, or no unit id is given with the unit argument, the script will try
and default to targeting the currently selected unit.
Other arguments:
help Shows this help page.
list Prints a list of all facets + their IDs.
noneed By default, unit’s needs will be recalculated to reflect new traits after every run. Use this argu-
ment to disable that functionality.
listunit Prints a list of all a unit’s personality traits, with their modified trait value in brackets.
5.5.26 modtools/skill-change
5.5.27 modtools/spawn-flow
-material mat
specify the material of the flow, if applicable
examples:
INORGANIC:IRON
CREATURE_MAT:DWARF:BRAIN
PLANT_MAT:MUSHROOM_HELMET_PLUMP:DRINK
-location [ x y z]
the location to spawn the flow
-flowType type
specify the flow type
examples:
Miasma
Steam
Mist
MaterialDust
MagmaMist
Smoke
Dragonfire
Fire
Web
MaterialGas
MaterialVapor
OceanWave
SeaFoam
-flowSize size
specify how big the flow is
5.5.28 modtools/spawn-liquid
5.5.29 modtools/syndrome-trigger
-syndrome SYN_NAME
specify a syndrome by its SYN_NAME
enclose the name in quotation marks if it includes spaces
example:
-syndrome "gila monster bite"
-synclass SYN_CLASS
any syndrome with the specified SYN_CLASS will act as a trigger
enclose in quotation marks if it includes spaces
example:
-synclass VAMPCURSE
-command [ commandStrs ]
specify the command to be executed after infection
remember to include a space after/before the square brackets!
the following may be added to appropriate commands where relevant:
\\UNIT_ID
inserts the ID of the infected unit
\\LOCATION
inserts the x, y, z coordinates of the infected unit
\\SYNDROME_ID
inserts the ID of the syndrome
note that:
\\anything -> \anything
anything -> anything
examples:
-command [ full-heal -unit \\UNIT_ID ]
heals units when they acquire the specified syndrome
-command [ modtools/spawn-flow -flowType Dragonfire -location [ \\LOCATION ] ]
spawns dragonfire at the location of infected units
5.5.30 modtools/transform-unit
Transforms a unit into another unit type, possibly permanently. Warning: this will crash arena mode if you view the
unit on the same tick that it transforms. If you wait until later, it will be fine.
Arguments:
-clear
clear records of normal races
-unit id
set the target unit
-duration ticks
how long it should last, or "forever"
-setPrevRace
make a record of the previous race so that you can
change it back with -untransform
-keepInventory
(continues on next page)
About DFHack
6.1 Changelog
This file contains changes grouped by the stable release in which they first appeared. See Building the changelogs for
more information.
See Development Changelog for a list of changes grouped by development releases.
Contents
• DFHack future
• DFHack 0.47.04-r2
• DFHack 0.47.04-r1
• DFHack 0.44.12-r3
• DFHack 0.44.12-r2
• DFHack 0.44.12-r1
• DFHack 0.44.10-r2
• DFHack 0.44.10-r1
• DFHack 0.44.09-r1
• DFHack 0.44.05-r2
• DFHack 0.44.05-r1
• Older Changelogs
179
DFHack Documentation, Release 0.47.04-r2
Fixes
Misc Improvements
• unretire-anyone: made undead creature names appear in the historical figure list
New Scripts
New Tweaks
Fixes
• Fixed a segfault when attempting to start a headless session with a graphical PRINT_MODE setting
• Fixed an issue with the macOS launcher failing to un-quarantine some files
• Fixed Units::isEggLayer, Units::isGrazer, Units::isMilkable,
Units::isTrainableHunting, Units::isTrainableWar, and Units::isTamable ignor-
ing the unit’s caste
• Linux: fixed [Link]() (Lua) and Process::getPath() (C++) to always return the DF
root path, even if the working directory has changed
• digfort:
– fixed an issue causing blueprints touching the southern or eastern edges of the map to be rejected (northern
and western edges were already allowed). This allows blueprints that span the entire embark area.
– fixed y-line tracking when .csv files contain lines with only commas
• embark-assistant: fixed a couple of incursion handling bugs.
• embark-skills: fixed an issue with structures causing the points option to do nothing
• exportlegends:
– stopped including some tags with -1 values which don’t provide useful information
– fixed an issue where two different <reason> tags could be included in a <historical_event>
• getplants: fixed issues causing plants to be collected even if they have no growths (or unripe growths)
• gui/advfort: fixed “operate pump” job
• gui/load-screen: fixed an issue causing longer timezones to be cut off
• labormanager:
– fixed an issue preventing custom furnaces from being built
– fixed handling of new jobs in 0.47
• modtools/moddable-gods:
– made -depictedAs argument work
– removed unused -domain and -description arguments
– fixed an error when creating the historical figure
• names:
– fixed an issue causing renamed units to display their old name in legends mode and some other places
– fixed an error preventing the script from working
• pref-adjust: fixed some compatibility issues and a potential crash
• remotefortressreader:
– fixed an issue that could cause block coordinates to be incorrect
– fixed a couple crashes that could result from decoding invalid enum items
(site_realization_building_type and improvement_type)
• rendermax: fixed a hang that could occur when enabling some renderers, notably on Linux
• stonesense:
– fixed some issues that could cause the splash screen to hang
– fixed a crash when launching Stonesense
Misc Improvements
• Linux/macOS: Added console keybindings for deleting words (Alt+Backspace and Alt+d in most terminals)
• add-recipe:
– added a command explanation or error message when entering an invalid command
– added tool recipes (minecarts, wheelbarrows, stepladders, etc.)
• armoks-blessing: added adjustments to values and needs
• blueprint:
– now automatically creates folder trees when organizing blueprints into subfolders (e.g. blueprint 30
30 1 rooms/dining dig will create the file blueprints/rooms/[Link]); previ-
ously it would fail if the blueprints/rooms/ directory didn’t already exist
– now writes blueprints to the blueprints/ subfolder instead of the df root folder
• confirm: added a confirmation dialog for convicting dwarves of crimes
API
• Added Filesystem::mkdir_recursive
• Extended Filesystem::listdir_recursive to optionally make returned filenames relative to the start
directory
• Units: added goal-related functions: getGoalType(), getGoalName(), isGoalAchieved()
Internals
• Added support for splitting scripts into multiple files in the scripts/internal folder without polluting the
output of ls
Lua
• Added a ref_target field to primitive field references, corresponding to the ref-target XML attribute
• Made [Link](), [Link](), and
[Link]() available to Lua
Ruby
• Updated item_find and building_find to use centralized logic that works on more screens
Structures
Documentation
• Added some new dev-facing pages, including dedicated pages about the remote API, memory research, and
documentation
• Expanded the installation guide
• Made a couple theme adjustments
New Scripts
Fixes
Misc Improvements
• deep-embark:
– improved support for using directly from the DFHack console
– added a -clear option to cancel
• devel/export-dt-ini: updated some field names for DT for 0.47
• devel/visualize-structure: added human-readable lengths to containers
• dfhack-run: added color output support
• embark-assistant:
– updated embark aquifer info to show all aquifer kinds present
– added neighbor display, including kobolds (SKULKING) and necro tower count
– updated aquifer search criteria to handle the new variation
– added search criteria for embark initial tree cover
– added search criteria for necro tower count, neighbor civ count, and specific neighbors. Should handle
additional entities, but not tested
• exportlegends:
– added evilness and force IDs to regions
– added profession and weapon info to relevant entities
– added support for many new history events in 0.47
– added historical event relationships and supplementary data
– made interaction export more robust and human-readable
– removed empty <item_subtype> and <claims> tags
– added identity information
– added creature raw names and flags
• full-heal:
– made resurrection produce a historical event viewable in Legends mode
– made error messages more explanatory
• getplants: added switches for designations for farming seeds and for max number designated per plant
• gui/prerelease-warning: updated links and information about nightly builds
• install-info: added DFHack build ID to report
• manipulator: added intrigue to displayed skills
• modtools/create-item: added -matchingGloves and -matchingShoes arguments
• modtools/create-unit:
– added -duration argument to make the unit vanish after some time
– added -locationRange argument to allow spawning in a random position within a defined area
– added -locationType argument to specify the type of location to spawn in
– added -equip option to equip created units
– added -skills option to give skills to units
API
• Added Items::getBookTitle to get titles of books. Catches titles buried in improvements, unlike getDe-
scription.
Internals
Lua
Structures
New Plugins
New Scripts
Fixes
• Fixed a crash in the macOS/Linux console when the prompt was wider than the screen width
• Fixed inconsistent results from Units::isGay for asexual units
• Fixed some cases where Lua filtered lists would not properly intercept keys, potentially triggering other actions
on the same screen
• autofarm:
– fixed biome detection to properly determine crop assignments on surface farms
– reimplemented as a C++ plugin to make proper biome detection possible
• bodyswap: fixed companion list not being updated often enough
• cxxrandom: removed some extraneous debug information
• digfort: now accounts for z-level changes when calculating maximum y dimension
• embark-assistant:
– fixed bug causing crash on worlds without generated metals (as well as pruning vectors as originally
intended).
– fixed bug causing mineral matching to fail to cut off at the magma sea, reporting presence of things that
aren’t (like DF does currently).
– fixed bug causing half of the river tiles not to be recognized.
– added logic to detect some river tiles DF doesn’t generate data for (but are definitely present).
• Eventful: fixed invalid building ID in some building events
• exportlegends: now escapes special characters in names properly
• getplants: fixed designation of plants out of season (note that picked plants are still designated incorrectly)
• gui/autogems: fixed error when no world is loaded
• gui/companion-order:
– fixed error when resetting group leaders
– leave now properly removes companion links
• gui/create-item: fixed module support - can now be used from other scripts
• gui/stamper:
– stopped “invert” from resetting the designation type
– switched to using DF’s designation keybindings instead of custom bindings
– fixed some typos and text overlapping
• modtools/create-unit:
– fixed an error associating historical entities with units
– stopped recalculating health to avoid newly-created citizens triggering a “recover wounded” job
– fixed units created in arena mode having blank names
– fixed units created in arena mode having the wrong race and/or interaction effects applied after creating
units manually in-game
– stopped units from spawning with extra items or skills previously selected in the arena
– stopped setting some unneeded flags that could result in glowing creature tiles
– set units created in adventure mode to have no family, instead of being related to the first creature in the
world
• modtools/reaction-product-trigger:
– fixed an error dealing with reactions in adventure mode
– blocked \\BUILDING_ID for adventure mode reactions
– fixed -clear to work without passing other unneeded arguments
• modtools/reaction-trigger:
– fixed a bug when determining whether a command was run
– fixed handling of -resetPolicy
• mousequery: fixed calculation of map dimensions, which was sometimes preventing scrolling the map with the
mouse when TWBT was enabled
• remotefortressreader: fixed a crash when a unit’s path has a length of 0
Misc Improvements
• Added a note to dfhack-run when called with no arguments (which is usually unintentional)
• On macOS, the launcher now attempts to un-quarantine the rest of DFHack
• bodyswap: added arena mode support
• combine-drinks: added more default output, similar to combine-plants
• createitem: added a list of valid castes to the “invalid caste” error message, for convenience
• devel/export-dt-ini: added more size information needed by newer Dwarf Therapist versions
• dwarfmonitor: enabled widgets to access other scripts and plugins by switching to the core Lua context
• embark-assistant:
– added an in-game option to activate on the embark screen
– changed waterfall detection to look for level drop rather than just presence
– changed matching to take incursions, i.e. parts of other biomes, into consideration when evaluating tiles.
This allows for e.g. finding multiple biomes on single tile embarks.
– changed overlay display to show when incursion surveying is incomplete
– changed overlay display to show evil weather
– added optional parameter “fileresult” for crude external harness automated match support
– improved focus movement logic to go to only required world tiles, increasing speed of subsequent searches
considerably
• exportlegends: added rivers to custom XML export
• exterminate: added support for a special enemy caste
• gui/gm-unit:
– added support for editing:
– added attribute editor
– added orientation editor
– added editor for bodies and body parts
– added color editor
– added belief editor
– added personality editor
• modtools/create-item: documented already-existing -quality option
• modtools/create-unit:
– added the ability to specify \\LOCAL for the fort group entity
– now enables the default labours for adult units with CAN_LEARN.
– now sets historical figure orientation.
API
• Added new plugin_load_data and plugin_save_data events for plugins to load/save persistent data
• Added Maps::GetBiomeType and Maps::GetBiomeTypeByRef to infer biome types properly
• Added Units::getPhysicalDescription (note that this depends on the
unit_get_physical_description offset, which is not yet available for all DF builds)
Internals
Lua
Ruby
Structures
New Plugins
New Scripts
Fixes
Misc Improvements
• full-heal:
– added -all, -all_civ and -all_citizens arguments
– added module support
– now removes historical figure death dates and ghost data
• growcrops: added all argument to grow all crops
• gui/load-screen: improved documentation
• labormanager: now takes nature value into account when assigning jobs
• open-legends: added warning about risk of save corruption and improved related documentation
• points: added support when in viewscreen_setupdwarfgamest and improved error messages
• siren: removed break handling (relevant misc_trait_type was no longer used - see “Structures” section)
API
Internals
• Added a usable unit test framework for basic tests, and a few basic tests
• Added [Link] with intellisense support
• Changed plugins/[Link] to be ignored by git and created (if needed) at build time
instead
• Core: various thread safety and memory management improvements
• Fixed CMake build dependencies for generated header files
• Fixed custom CMAKE_CXX_FLAGS not being passed to plugins
• Linux/macOS: changed recommended build backend from Make to Ninja (Make builds will be significantly
slower now)
Lua
Structures
• incident_sub6_performance:
– named poetic_form_id, musical_form_id, and dance_form_id
– made performance_event an enum
• misc_trait_type: removed LikesOutdoors, Hardened, TimeSinceBreak, OnBreak (all unused
by DF)
• musical_form_instruments: named minimum_required and maximum_permitted
• musical_form: named voices field
• plant_tree_info: identified extent_east, etc.
• plant_tree_tile: gave connection bits more meaningful names (e.g. connection_east instead of
thick_branches_1)
• poetic_form: identified many fields and related enum/bitfield types
• setup_character_info: identified skill_points_remaining (for embark-skills)
• [Link]: identified fortress_site
• [Link]: identified kill_rect_targets_scroll
• ui: fixed alignment of main and squads (fixes tweak hotkey-clear and DF-AI)
• unit_action.attack:
– added lightly_tap and spar_report flags
– identified attack_skill
• unit_flags3: identified marked_for_gelding
• unit_personality: identified stress_drain, stress_boost, likes_outdoors,
combat_hardened
• unit_storage_status: newly identified type, stores noble holdings information (used in
viewscreen_layer_noblelistst)
• unit_thought_type: added new expulsion thoughts from 0.44.12
• viewscreen_layer_arena_creaturest: identified item- and name-related fields
• viewscreen_layer_militaryst: identified [Link].assigned_items
• viewscreen_layer_noblelistst: identified storage_status (see unit_storage_status
type)
• viewscreen_new_regionst:
– changed many int8_t fields to bool
– identified rejection_msg, raw_folder, load_world_params
• viewscreen_setupadventurest: identified some nemesis and personality fields, and page.
ChooseHistfig
• world_data: added mountain_peak_flags type, including is_volcano
• world_history: identified names and/or types of some fields
• world_site: identified names and/or types of some fields
• written_content: named poetic_form
Fixes
Misc Improvements
• Console:
– added support for multibyte characters on Linux/macOS
– made the console exit properly when an interactive command is active (liquids, mode, tiletypes)
• Linux: added automatic support for GCC sanitizers in dfhack script
• Made the DFHACK_PORT environment variable take priority over [Link]
• Reduced time for designation jobs from tools like dig to be assigned workers
• dfhack-run: added support for port specified in [Link], to match DFHack’s behavior
• digfort: added better map bounds checking
• embark-assistant:
– Switched to standard scrolling keys, improved spacing slightly
– Introduced scrolling of Finder search criteria, removing requirement for 46 lines to work properly
(Help/Info still formatted for 46 lines).
– Added Freezing search criterion, allowing searches for NA/Frozen/At_Least_Partial/Partial/At_Most_Partial/Never
Freezing embarks.
• rejuvenate:
– Added -all argument to apply to all citizens
– Added -force to include units under 20 years old
– Clarified documentation
• remove-stress:
– added support for -all as an alternative to the existing all argument for consistency
– sped up significantly
– improved output/error messages
– now removes tantrums, depression, and obliviousness
• ruby: sped up handling of onupdate events
API
Internals
Lua
• Added printall_recurse to print tables and DF references recursively. It can be also used with ^ from
the lua interpreter.
• [Link]: List:setChoices clones choices for internal table changes
Structures
New Plugins
• cxxrandom: exposes some features of the C++11 random number library to Lua
New Scripts
Fixes
• Fixed many tools incorrectly using the dead unit flag (they should generally check [Link] instead)
• Fixed many tools passing incorrect arguments to printf-style functions, including a few possible crashes (change-
layer, follow, forceequip, generated-creature-renamer)
• Fixed several bugs in Lua scripts found by static analysis (df-luacheck)
• Fixed -g flag (GDB) in Linux dfhack script (particularly on x64)
• autochop, autodump, autogems, automelt, autotrade, buildingplan, dwarfmonitor, fix-unit-occupancy, fortplan,
stockflow: fix issues with periodic tasks not working for some time after save/load cycles
• autogems:
– stop running repeatedly when paused
– fixed crash when furnaces are linked to same stockpiles as jeweler’s workshops
• autogems, fix-unit-occupancy: stopped running when a fort isn’t loaded (e.g. while embarking)
• autounsuspend: now skips planned buildings
• ban-cooking: fixed errors introduced by kitchen structure changes in 0.44.10-r1
• buildingplan, fortplan: stopped running before a world has fully loaded
• deramp: fixed deramp to find designations that already have jobs posted
• dig: fixed “Inappropriate dig square” announcements if digging job has been posted
• fixnaked: fixed errors due to emotion changes in 0.44
• remove-stress: fixed an error when running on soul-less units (e.g. with -all)
• reveal: stopped revealing tiles adjacent to tiles above open space inappropriately
• stockpiles: loadstock now sets usable and unusable weapon and armor settings
• stocks: stopped listing carried items under stockpiles where they were picked up from
Misc Improvements
API
Internals
• Added build option to generate symbols for large generated files containing df-structures metadata
• Added fallback for YouCompleteMe database lookup failures (e.g. for newly-created files)
• Improved efficiency and error handling in stl_vsprintf and related functions
• jsoncpp: fixed constructor with long on Linux
Lua
Structures
New Scripts
New Tweaks
• tweak kitchen-prefs-all: adds an option to toggle cook/brew for all visible items in kitchen preferences
• tweak stone-status-all: adds an option to toggle the economic status of all stones
Fixes
Misc Improvements
API
Internals
Structures
Fixes
Misc Improvements
Internals
Structures
New Plugins
New Scripts
• adv-fix-sleepers: fixes units in adventure mode who refuse to wake up (Bug 6798)
• hermit: blocks caravans, migrants, diplomats (for hermit challenge)
New Features
• With PRINT_MODE:TEXT, setting the DFHACK_HEADLESS environment variable will hide DF’s display and
allow the console to be used normally. (Note that this is intended for testing and is not very useful for actual
gameplay.)
Fixes
Misc Improvements
New Scripts
Fixes
• Fixed a crash that could occur if a symbol table in [Link] had no content
• Fixed issues with the console output color affecting the prompt on Windows
• autolabor, autohauler, labormanager: added support for “put item on display” jobs and building/destroying
display furniture
• createitem: stopped items from teleporting away in some forts
• devel/inject-raws:
– now recognizes spaces in reaction names
– now recognizes spaces in reaction names
• dig: added support for designation priorities - fixes issues with designations from digv and related commands
having extremely high priority
• dwarfmonitor:
– fixed display of creatures and poetic/music/dance forms on prefs screen
– added “view unit” option
– now exposes the selected unit to other tools
• exportlegends: fixed an error that could occur when exporting empty lists
• gui/gm-editor: fixed an error when editing primitives in Lua tables
• gui/gm-unit: can now edit mining skill
• gui/quickcmd: stopped error from adding too many commands
• modtools/create-unit: fixed error when domesticating units
• names: fixed many errors
• quicksave: fixed an issue where the “Saving. . . ” indicator often wouldn’t appear
Misc Improvements
Removed
Internals
Lua
Structures
• Added buildings_other_id.DISPLAY_CASE
• Added job_type.PutItemOnDisplay
• Added twbt_render_map code offset on x64
• Fixed an issue preventing enabler from being allocated by DFHack
• Fixed unit alignment
• Fixed viewscreen_titlest.start_savegames alignment
• Found renderer vtable on osx64
• Identified historical_entity.[Link] (deity IDs)
• Located start_dwarf_count offset for all builds except 64-bit Linux; startdwarf should work now
• New globals:
– version
– min_load_version
– movie_version
– basic_seed
– title
– title_spaced
– ui_building_resize_radius
– soul_next_id
• The former announcements global is now a field in d_init
• The ui_menu_width global is now a 2-byte array; the second item is the former ui_area_map_width
global, which is now removed
• adventure_movement_optionst, adventure_movement_hold_tilest,
adventure_movement_climbst: named coordinate fields
• artifact_record: fixed layout (changed in 0.44.04)
• incident: fixed layout (changed in 0.44.01) - note that many fields have moved
• mission: added type
• unit: added 3 new vmethods: getCreatureTile, getCorpseTile, getGlowTile
• viewscreen_assign_display_itemst: fixed layout on x64 and identified many fields
• viewscreen_reportlistst: fixed layout, added mission_id vector
• [Link]: named missions vector
• world fields formerly beginning with job_ are now fields of [Link], e.g. world.job_list is now
[Link]
The following is a list of people who have contributed to DFHack, in alphabetical order.
If you should be here and aren’t, please get in touch on IRC or the forums, or make a pull request!
6.3 Licenses
DFHack is distributed under the Zlib license, with some MIT- and BSD-licensed components. These licenses protect
your right to use DFHack for any purpose, distribute copies, and so on.
The core, plugins, scripts, and other DFHack code all use the ZLib license unless noted otherwise. By contributing to
DFHack, authors release the contributed work under this license.
DFHack also draws on several external packages. Their licenses are summarised here and reproduced below.
See [Link]
See [Link]
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
See [Link]
This page lists tools (plugins or scripts) that were previously included in DFHack but have been removed. It exists
primarily so that internal links still work (e.g. links from the Changelog).
Contents
• warn-stuck-trees
6.4.1 warn-stuck-trees
DFHack has various components; this page provides an overview of some. If you are looking to develop a tool for
DFHack, developing a script or plugin is likely the most straightforward choice.
Other pages that may be relevant include:
• How to contribute to DFHack
• DFHack Documentation System
• Licenses
Contents
• Plugins
• Scripts
• Core
• Modules
• Remote access interface
7.1.1 Plugins
DFHack plugins are written in C++ and located in the plugins folder. Currently, documentation on how to write
plugins is somewhat sparse. There are templates that you can get use to get started in the plugins/skeleton
folder, and the source code of existing plugins can also be helpful.
219
DFHack Documentation, Release 0.47.04-r2
If you want to compile a plugin that you have just added, you will need to add a call to DFHACK_PLUGIN in
plugins/[Link].
Plugins have the ability to make one or more commands available to users of the DFHack console. Examples in-
clude 3dveins (which implements the 3dveins command) and reveal (which implements reveal, unreveal, and
several other commands).
Plugins can also register handlers to run on every tick, and can interface with the built-in enable and enable commands.
For the full plugin API, see the skeleton plugins or [Link].
Installed plugins live in the hack/plugins folder of a DFHack installation, and the load family of commands can
be used to load a recompiled plugin without restarting DF.
See DFHack Plugins for a list of all plugins included in DFHack.
7.1.2 Scripts
DFHack scripts can currently be written in Lua or Ruby. The Lua API is more complete and currently better-
documented, however. Referring to existing scripts as well as the API documentation can be helpful when developing
new scripts.
Scripts included in DFHack live in a separate scripts repository. This can be found in the scripts submodule if you
have cloned DFHack, or the hack/scripts folder of an installed copy of DFHack.
7.1.3 Core
The DFHack core has a variety of low-level functions. It is responsible for hooking into DF (via SDL), providing a
console, and providing an interface for plugins and scripts to interact with DF.
7.1.4 Modules
A lot of shared code to interact with DF in more complicated ways is contained in modules. For example, the Units
module contains functions for checking various traits of units, changing nicknames properly, and more. Generally,
code that is useful to multiple plugins and scripts should go in the appropriate module, if there is one.
Several modules are also exposed to Lua, although some functions (and some entire modules) are currently only
available in C++.
DFHack provides a remote access interface that external tools can connect to and use to interact with DF. See DFHack
Remote Interface for more information.
Contents
• Contributing Code
– Code format
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.
• Pull requests should be based on (and submitted to) the default branch of the relevant repo, which is the branch
you see when you access the repo on GitHub or clone the repo without specifying a branch. As of 0.47.04-r1,
this is develop for the main DFHack repo and master for other repos.
• Use a new branch for each feature or bugfix so that your changes can be merged independently (i.e. not the
master or develop branch of your fork).
– An exception: for a collection of small miscellaneous changes (e.g. structures research), one branch
instead of many small branches is fine. It is still preferred that this branch be dedicated to this purpose, i.e.
not master or develop. Your pull request may be merged at any point unless you indicate that it isn’t
ready (see below), but you can continue to push to the same branch and open new pull requests as needed.
• Try to keep pull requests relatively small so that they are easier to review and merge.
– If you expect to make a large number of related additions or changes (e.g. adding a large new plugin),
multiple PRs are preferred, as they allow more frequent (and easier) feedback. If development of this
feature is expected to take a while, we may create a dedicated branch to merge your pull requests into
instead of the repo’s default branch.
• If you plan to make additional changes to your pull request in the near future, or if it isn’t quite ready to be
merged, mark it as a draft pull request or add “WIP” to the title. Otherwise, your pull request may be reviewed
and/or merged prematurely.
• If convenient, compile on multiple platforms when changing anything that compiles. Our CI should catch
anything that fails to build, but checking in advance can be faster.
• Update documentation when applicable - see Documentation standards for details.
• Update [Link] and docs/[Link] when applicable. See Building the changelogs for more
information on the changelog format.
• Submit ideas and bug reports as issues on GitHub. Posts in the forum thread can easily get missed or forgotten.
• Work on reported problems will take priority over ideas or suggestions.
DFHack is a software project, but there’s a lot more to it than programming. If you’re not comfortable programming,
you can help by:
• reporting bugs and incomplete documentation
• improving the documentation
• finding third-party scripts to add
• writing tutorials for newbies
All those things are crucial, and often under-represented. So if that’s your thing, go get started!
DFHack builds are available for all supported platforms; see Installing DFHack for installation instructions. If you are
a DFHack end-user, modder, or plan on writing scripts (not plugins), it is generally recommended (and easier) to use
these builds instead of compiling DFHack from source.
However, if you are looking to develop plugins, work on the DFHack core, make complex changes to DF-structures,
or anything else that requires compiling DFHack from source, this document will walk you through the build process.
Note that some steps may be unconventional compared to other projects, so be sure to pay close attention if this is
your first time compiling DFHack.
Contents
DFHack uses Git for source control; instructions for installing Git can be found in the platform-specific sections below.
The code is hosted on GitHub, and can be downloaded with:
If your version of Git does not support the --recursive flag, you will need to omit it and run git submodule
update --init after entering the dfhack directory.
This will check out the code on the default branch of the GitHub repo, currently develop, which may be unstable.
If you want code for the latest stable release, you can check out the master branch instead:
In general, a single DFHack clone is suitable for development - most Git operations such as switching branches can
be done on an existing clone. If you find yourself cloning DFHack frequently as part of your development process, or
getting stuck on anything else Git-related, feel free to reach out to us for assistance.
A note on submodules
DFHack uses submodules extensively to manage its subprojects (including the scripts folder and DF-structures in
library/xml). Failing to keep submodules in sync when switching between branches can result in build errors or
scripts that don’t work. In general, you should always update submodules whenever you switch between branches in
the main DFHack repo with git submodule update. (If you are working on bleeding-edge DFHack and have
checked out the master branch of some submodules, running git pull in those submodules is also an option.)
Rarely, we add or remove submodules. If there are any changes to the existence of submodules when you switch
between branches, you should run git submodule update --init instead (adding --init to the above
command).
Some common errors that can arise when failing to update submodules include:
• fatal: <some path> does not exist when performing Git operations
• Build errors, particularly referring to structures in the df:: namespace or the library/include/df folder
• Not a known DF version when starting DF
• Run 'git submodule update --init' when running CMake
Submodules are a particularly confusing feature of Git. The Git Book has a thorough explanation of them (as well as
of many other aspects of Git) and is a recommended resource if you run into any issues. Other DFHack developers are
also able to help with any submodule-related (or Git-related) issues you may encounter.
More notes:
• Note on building DFHack offline - read this if your build machine may not have an internet connection!
• Note on using very old git versions with pre-0.43.03 DFHack versions
To contribute to DFHack on GitHub, you will need a GitHub account. Only some DFHack developers can push
directly to the DFHack repositories; we recommend making a fork of whatever repos you are interested in contributing
to, making changes there, and submitting pull requests. GitHub’s pull request tutorial is a good resource for getting
started with pull requests (some things to note: our work mainly happens on the develop branch, and you will need
to use your own fork, assuming that you don’t have write access to the DFHack repos).
Most development-related discussion happens on IRC or in individual GitHub issues and pull requests, but there are
also other ways to reach out - see Troubleshooting for details.
For more details on contributing to DFHack, including pull requests, code format, and more, please see Contributing
Code.
This section describes build configuration options that apply to all platforms. If you don’t have a working build
environment set up yet, follow the instructions in the platform-specific sections below first, then come back here.
Generator
The Ninja CMake build generator is the preferred build method on Linux and macOS, instead of Unix
Makefiles, which is the default. You can select Ninja by passing -G Ninja to CMake. Incremental builds
using Unix Makefiles can be much slower than Ninja builds. Note that you will probably need to install Ninja; see the
platform-specific sections for details.
cmake .. -G Ninja
Warning: Most other CMake settings can be changed by running cmake again, but the generator cannot be
changed after cmake has been run without creating a new build folder. Do not forget to specify this option.
CMake versions 3.6 and older, and possibly as recent as 3.9, are known to produce project files with depen-
dency cycles that fail to build (see Issue 1369). Obtaining a recent version of CMake is recommended, either
from [Link] or through a package manager. See the sections below for more platform-specific directions for
installing CMake.
Build type
cmake allows you to pick a build type by changing the CMAKE_BUILD_TYPE variable:
cmake .. -DCMAKE_BUILD_TYPE:string=BUILD_TYPE
Valid and useful build types include ‘Release’ and ‘RelWithDebInfo’. The default build type is ‘Release’.
Set DFHACK_BUILD_ARCH to either 32 or 64 to build a 32-bit or 64-bit version of DFHack (respectively). The
default is currently 64, so you will need to specify this explicitly for 32-bit builds. Specifying it is a good idea in any
case.
cmake .. -DDFHACK_BUILD_ARCH=32
or
cmake .. -DDFHACK_BUILD_ARCH=64
Note that the scripts in the “build” folder on Windows will set the architecture automatically.
Other settings
There are a variety of other settings which you can find in [Link] in your build folder or by running ccmake
(or another CMake GUI). Most DFHack-specific settings begin with BUILD_ and control which parts of DFHack are
built.
7.3.4 Linux
On Linux, DFHack acts as a library that shadows parts of the SDL API using LD_PRELOAD.
Dependencies
• On Fedora:
yum install gcc-c++ cmake ninja-build git zlib-devel SDL-devel perl-core perl-XML-
˓→LibXML perl-XML-LibXSLT ruby
Multilib dependencies
If you want to compile 32-bit DFHack on 64-bit distributions, you’ll need the multilib development tools and libraries:
• gcc-multilib and g++-multilib
• If you have installed a non-default version of GCC - for example, GCC 4.8 on a distribution that defaults to 5.x
- you may need to add the version number to the multilib packages.
– For example, gcc-4.8-multilib and g++-4.8-multilib if installing for GCC 4.8 on a system
that uses a later GCC version.
– This is definitely required on Ubuntu/Debian, check if using a different distribution.
• zlib1g-dev:i386 (or a similar i386 zlib-dev package)
Note that installing a 32-bit GCC on 64-bit systems (e.g. gcc:i386 on Debian) will typically not work, as it depends
on several other 32-bit libraries that conflict with system libraries. Alternatively, you might be able to use lxc to create
a virtual 32-bit environment.
Build
Building is fairly straightforward. Enter the build folder (or create an empty folder in the DFHack directory to use
instead) and start the build like this:
cd build
cmake .. -G Ninja -DCMAKE_BUILD_TYPE:string=Release -DCMAKE_INSTALL_PREFIX=<path to
˓→DF>
ninja install # or ninja -jX install to specify the number of cores (X) to use
<path to DF> should be a path to a copy of Dwarf Fortress, of the appropriate version for the DFHack you are building.
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 .. -G Ninja
ninja 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.
Incompatible libstdc++
When compiling DFHack yourself, it builds against your system libstdc++. When Dwarf Fortress runs, it uses a
libstdc++ shipped in the libs folder, which comes from GCC 4.8 and is incompatible with code compiled with
newer GCC versions. As of DFHack 0.42.05-alpha1, the dfhack launcher script attempts to fix this by automatically
removing the DF-provided libstdc++ on startup. In rare cases, this may fail and cause errors such as:
The easiest way to fix this is generally removing the libstdc++ shipped with DF, which causes DF to use your system
libstdc++ instead:
cd /path/to/DF/
rm libs/libstdc++.so.6
Note that distributing binaries compiled with newer GCC versions may result in the opposite compatibily issue: users
with older GCC versions may encounter similar errors. This is why DFHack distributes both GCC 4.8 and GCC 7
builds. If you are planning on distributing binaries to other users, we recommend using an older GCC (but still at least
4.8) version if possible.
7.3.5 macOS
DFHack functions similarly on macOS and Linux, and the majority of the information above regarding the build
process (CMake and Ninja) applies here as well.
DFHack can officially be built on macOS only with GCC 4.8 or 7. Anything newer than 7 will require you to perform
extra steps to get DFHack to run (see Notes for GCC 8+ or OS X 10.10+ users), and your build will likely not be
redistributable.
If none of these situations apply to you, skip to Dependencies and system set-up.
If you have issues building on OS X 10.10 (Yosemite) or above, try definining the following environment variable:
export MACOSX_DEPLOYMENT_TARGET=10.9
If you build with a GCC version newer than 7, DFHack will probably crash immediately on startup, or soon after.
To fix this, you will need to replace hack/libstdc++.[Link] with a symlink to the libstdc++.[Link]
included in your version of GCC:
Note: If you build with a version of GCC that requires this, your DFHack build will not be redistributable. (Even
if you copy the libstdc++.[Link] from your GCC version and distribute that too, it will fail on older OS X
versions.) For this reason, if you plan on distributing DFHack, it is highly recommended to use GCC 4.8 or 7.
xcode-select --install
4. Install dependencies
It is recommended to use Homebrew instead of MacPorts, as it is generally cleaner, quicker, and
smarter. For example, installing MacPort’s GCC will install more than twice as many dependencies
as Homebrew’s will, and all in both 32-bit and 64-bit variants. Homebrew also doesn’t require
constant use of sudo.
Using Homebrew (recommended):
Using MacPorts:
Macports will take some time - maybe hours. At some point it may ask you to install a Java environ-
ment; let it do so.
5. Install Perl dependencies
• Using system Perl
– 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.
If you are running OS X 10.6 (Snow Leopard) or earlier, good luck! You’ll need to open a separate
Terminal window and run:
– install XML::LibXML
– install XML::LibXSLT
• In a separate, local Perl install
Rather than using system Perl, you might also want to consider the Perl manager, Perlbrew.
This manages Perl 5 locally under ~/perl5/, providing an easy way to install Perl and run CPAN against
it without sudo. It can maintain multiple Perl installs and being local has the benefit of easy migration and
insulation from OS issues and upgrades.
See [Link] for more details.
Building
• Get the DFHack source as per section How to get the code, above.
• Set environment variables
Homebrew (if installed elsewhere, replace /usr/local with $(brew --prefix)):
export CC=/usr/local/bin/gcc-7
export CXX=/usr/local/bin/g++-7
Macports:
export CC=/opt/local/bin/gcc-mp-7
export CXX=/opt/local/bin/g++-mp-7
Change the version numbers appropriately if you installed a different version of GCC.
If you are confident that you have GCC in your path, you can omit the absolute paths:
export CC=gcc-7
export CXX=g++-7
mkdir build-osx
cd build-osx
cmake .. -G Ninja -DCMAKE_BUILD_TYPE:string=Release -DCMAKE_INSTALL_PREFIX=<path
˓→to DF>
ninja install # or ninja -jX install to specify the number of cores (X) to use
<path to DF> should be a path to a copy of Dwarf Fortress, of the appropriate version for the DFHack you are
building.
7.3.6 Windows
Dependencies
DFHack has to be compiled with the Microsoft Visual C++ 2015 or 2017 toolchain on Windows; other versions won’t
work against Dwarf Fortress due to ABI and STL incompatibilities.
You can install Visual Studio 2015 or 2017 Community edition for free, which include all the features needed by
DFHack. You can also download just the build tools if you aren’t going to use Visual Studio to edit code.
The remainder of dependencies - Git, CMake, StrawberryPerl, and Python - can be most easily installed using the
Chocolatey Package Manger. Chocolatey is a *nix-style package manager for Windows. It’s fast, small (8-20MB on
disk) and very capable. Think “apt-get for Windows.”
Chocolatey is a recommended way of installing the required dependencies as it’s quicker, requires less effort, and will
install known-good utilities guaranteed to have the correct setup (especially PATH).
To install Chocolatey and the required dependencies:
• Go to [Link] in a web browser
• At the top of the page it will give you the install command to copy
– Copy the first one, which starts @powershell ...
– It won’t be repeated here in case it changes in future Chocolatey releases.
• Open an elevated (Admin) [Link] window
– On Windows 8 and later this can be easily achieved by:
If you prefer to install manually rather than using Chocolatey, details and requirements are as below. If you do install
manually, please ensure you have all PATHs set up correctly.
Git
Some examples:
• Git for Windows (command-line and GUI)
• tortoisegit (GUI and File Explorer integration)
CMake
You can get the win32 installer version from the official site. 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.
For the code generation stage of the build process, you’ll need Perl 5 with XML::LibXML and XML::LibXSLT.
Strawberry Perl is recommended as it includes all of the required packages in a single, easy install.
After install, ensure Perl is in your user’s PATH. This can be edited from Control Panel -> System ->
Advanced System Settings -> Environment Variables.
The following directories must be in your PATH, in this order:
• <path to perl>\c\bin
• <path to perl>\perl\site\bin
• <path to perl>\perl\bin
• <path to perl>\perl\vendor\lib\auto\XML\LibXML (may only be required on some systems)
Be sure to close and re-open any existing [Link] windows after updating your PATH.
If you already have a different version of Perl installed (for example, from Cygwin), you can run into some trouble.
Either remove the other Perl install from PATH, or install XML::LibXML and XML::LibXSLT for it using CPAN.
Build
There are several different batch files in the win32 and win64 subfolders in the build folder, along with a script
that’s used for picking the DF path. Use the subfolder corresponding to the architecture that you want to build for.
First, run set_df_path.vbs and point the dialog that pops up at a suitable DF installation which is of the appro-
priate version for the DFHack you are compiling. The result is the creation of the file DF_PATH.txt in the build
directory. It contains the full path to the destination directory. You could therefore also create this file manually - or
copy in a pre-prepared version - if you prefer.
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 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.
• release will create a solution with everything that should be included in release builds of DFHack. Note that
this includes documentation, which requires Python.
Then you can either open the solution with MSVC or use one of the msbuild scripts:
and extremely limited scrollback. For that reason you may prefer to compile in the IDE which will always show all
build output.
Alternatively (or additionally), consider installing an improved Windows terminal such as Cmder. Easily installed
through Chocolatey with: choco install cmder -y.
Note for Cygwin/msysgit users: It is also possible to compile DFHack from a Bash command line. This has three
potential benefits:
• When you’ve installed Git and are using its Bash, but haven’t added Git to your path:
– You can load Git’s Bash and as long as it can access Perl and CMake, you can use it for compile without
adding Git to your system path.
• When you’ve installed Cygwin and its SSH server:
– You can now SSH in to your Windows install and compile from a remote terminal; very useful if your
Windows installation is a local VM on a *nix host OS.
• In general: you can use Bash as your compilation terminal, meaning you have a decent sized window, scrollback,
etc.
– Whether you’re accessing it locally as with Git’s Bash, or remotely through Cygwin’s SSH server, this is
far superior to using [Link].
You don’t need to do anything special to compile from Bash. As long as your PATHs are set up correctly, you can run
the same generate- and build/install/package- bat files as detailed above.
After running the CMake generate script you will have a new folder called VC2015 or VC2015_32, depending on the
architecture you specified. Open the file [Link] inside that folder. If you have multiple versions of Visual
Studio installed, make sure you open with Visual Studio 2015.
The first thing you must then do is change the build type. It defaults to Debug, but this cannot be used on Windows.
Debug is not binary-compatible with DF. If you try to use a debug build with DF, you’ll only get crashes and for this
reason the Windows “debug” scripts actually do RelWithDebInfo builds. After loading the Solution, change the Build
Type to either Release or RelWithDebInfo.
Then build the INSTALL target listed under CMakePredefinedTargets.
The steps above will not build DFHack’s documentation by default. If you are editing documentation, see DFHack
Documentation System for details on how to build it.
As of 0.43.05, DFHack downloads several files during the build process, depending on your target OS and architecture.
If your build machine’s internet connection is unreliable, or nonexistent, you can download these files in advance.
First, you must locate the files you will need. These can be found in the dfhack-bin repo. Look for the most recent
version number before or equal to the DF version which you are building for. For example, suppose “0.43.05” and
“0.43.07” are listed. You should choose “0.43.05” if you are building for 0.43.05 or 0.43.06, and “0.43.07” if you are
building for 0.43.07 or 0.43.08.
Then, download all of the files you need, and save them to <path to DFHack clone>/CMake/downloads/
<any filename>. The destination filename you choose does not matter, as long as the files end up in the CMake/
downloads folder. You need to download all of the files for the architecture(s) you are building for. For example, if
you are building for 32-bit Linux and 64-bit Windows, download all files starting with linux32 and win64. GitHub
should sort files alphabetically, so all the files you need should be next to each other.
Note:
• Any files containing “allegro” in their filename are only necessary for building stonesense. If you are not
building Stonesense, you don’t have to download these, as they are larger than any other listed files.
It is recommended that you create a build folder and run CMake to verify that you have downloaded everything at
this point, assuming your download machine has CMake installed. This involves running a “generate” batch script on
Windows, or a command starting with cmake .. -G Ninja on Linux and macOS, following the instructions in
the sections above. CMake should automatically locate files that you placed in CMake/downloads, and use them
instead of attempting to download them.
Note on using very old git versions with pre-0.43.03 DFHack versions
If you are using git 1.8.0 or older, and cloned DFHack before commit 85a920d (around DFHack v0.43.03-alpha1),
you may run into fatal git errors when updating submodules after switching branches. This is due to those versions
of git being unable to handle our change from “scripts/3rdparty/name” submodules to a single “scripts” submodule.
This may be fixable by renaming .git/modules/scripts to something else and re-running git submodule update
--init on the branch with the single scripts submodule (and running it again when switching back to the one with
multiple submodules, if necessary), but it is usually much simpler to upgrade your git version.
This file contains changes grouped by the release (stable or development) in which they first appeared. See Building
the changelogs for more information.
See Changelog for a list of changes grouped by stable releases.
Contents
• DFHack future
• DFHack 0.47.04-r2
• DFHack 0.47.04-r1
• DFHack 0.47.04-beta1
• DFHack 0.47.03-beta1
• DFHack 0.44.12-r3
• DFHack 0.44.12-r2
• DFHack 0.44.12-r1
• DFHack 0.44.12-alpha1
• DFHack 0.44.11-beta2.1
• DFHack 0.44.11-beta2
• DFHack 0.44.11-beta1
• DFHack 0.44.11-alpha1
• DFHack 0.44.10-r2
• DFHack 0.44.10-r1
• DFHack 0.44.10-beta1
• DFHack 0.44.10-alpha1
• DFHack 0.44.09-r1
• DFHack 0.44.09-alpha1
• DFHack 0.44.08-alpha1
• DFHack 0.44.07-beta1
• DFHack 0.44.07-alpha1
• DFHack 0.44.05-r2
• DFHack 0.44.05-r1
• DFHack 0.44.05-alpha1
• DFHack 0.44.04-alpha1
• DFHack 0.44.03-beta1
• DFHack 0.44.03-alpha1
• DFHack 0.44.02-beta1
• DFHack 0.44.02-alpha1
Fixes
Misc Improvements
• unretire-anyone: made undead creature names appear in the historical figure list
New Scripts
New Tweaks
Fixes
• Fixed a segfault when attempting to start a headless session with a graphical PRINT_MODE setting
• Fixed an issue with the macOS launcher failing to un-quarantine some files
• Fixed Units::isEggLayer, Units::isGrazer, Units::isMilkable,
Units::isTrainableHunting, Units::isTrainableWar, and Units::isTamable ignor-
ing the unit’s caste
• Linux: fixed [Link]() (Lua) and Process::getPath() (C++) to always return the DF
root path, even if the working directory has changed
• digfort:
– fixed an issue causing blueprints touching the southern or eastern edges of the map to be rejected (northern
and western edges were already allowed). This allows blueprints that span the entire embark area.
– fixed y-line tracking when .csv files contain lines with only commas
• embark-assistant: fixed a couple of incursion handling bugs.
• embark-skills: fixed an issue with structures causing the points option to do nothing
• exportlegends:
– stopped including some tags with -1 values which don’t provide useful information
– fixed an issue where two different <reason> tags could be included in a <historical_event>
• getplants: fixed issues causing plants to be collected even if they have no growths (or unripe growths)
• gui/advfort: fixed “operate pump” job
• gui/load-screen: fixed an issue causing longer timezones to be cut off
• labormanager:
– fixed an issue preventing custom furnaces from being built
– fixed handling of new jobs in 0.47
• modtools/moddable-gods:
– made -depictedAs argument work
– removed unused -domain and -description arguments
– fixed an error when creating the historical figure
• names:
– fixed an issue causing renamed units to display their old name in legends mode and some other places
Misc Improvements
• Linux/macOS: Added console keybindings for deleting words (Alt+Backspace and Alt+d in most terminals)
• add-recipe:
– added a command explanation or error message when entering an invalid command
– added tool recipes (minecarts, wheelbarrows, stepladders, etc.)
• armoks-blessing: added adjustments to values and needs
• blueprint:
– now automatically creates folder trees when organizing blueprints into subfolders (e.g. blueprint 30
30 1 rooms/dining dig will create the file blueprints/rooms/[Link]); previ-
ously it would fail if the blueprints/rooms/ directory didn’t already exist
– now writes blueprints to the blueprints/ subfolder instead of the df root folder
• confirm: added a confirmation dialog for convicting dwarves of crimes
• devel/query: added many new query options
• digfort:
– added a force option to truncate blueprints if the full blueprint would extend off the edge of the map
– documented that removing ramps, cutting trees, and gathering plants are indeed supported
– handled double quotes (“) at the start of a string, allowing .csv files exported from spreadsheets to work
without manual modification
• dwarf-op:
– added ability to protect dwarves based on symbols in their custom professions
– added ability to select dwarves based on migration wave
• exportlegends:
– added ability to save all files to a subfolder, named after the region folder and date by default
– changed some enum values from numbers to their string representations
– changed some flags to be represented by self-closing tags instead of true/false strings (e.g.
<is_volcano/>) - note that this may require changes to other XML-parsing utilities
• gui/advfort: added support for specifying the entity used to determine available resources
• gui/gm-editor: added support for automatically following ref-targets when pressing the i key
• manipulator: added a new column option to display units’ goals
• modtools/moddable-gods: added support for neuter gender
• pref-adjust:
– added a new goth profile
– added support for adjusting just the selected dwarf
• remove-stress: added a -value argument to enable setting stress level directly
• workorder: changed default frequency from “Daily” to “OneTime”
API
• Added Filesystem::mkdir_recursive
• Extended Filesystem::listdir_recursive to optionally make returned filenames relative to the start
directory
• Units: added goal-related functions: getGoalType(), getGoalName(), isGoalAchieved()
Internals
• Added support for splitting scripts into multiple files in the scripts/internal folder without polluting the
output of ls
Lua
• Added a ref_target field to primitive field references, corresponding to the ref-target XML attribute
• Made [Link](), [Link](), and
[Link]() available to Lua
Ruby
• Updated item_find and building_find to use centralized logic that works on more screens
Structures
Documentation
• Added some new dev-facing pages, including dedicated pages about the remote API, memory research, and
documentation
• Expanded the installation guide
• Made a couple theme adjustments
Fixes
Misc Improvements
• exportlegends:
– made interaction export more robust and human-readable
– removed empty <item_subtype> and <claims> tags
• getplants: added switches for designations for farming seeds and for max number designated per plant
• manipulator: added intrigue to displayed skills
• modtools/create-unit:
– added -equip option to equip created units
– added -skills option to give skills to units
– added -profession and -customProfession options to adjust unit professions
• search: added support for the fortress mode justice screen
• [Link]-example: enabled autodump
API
• Added Items::getBookTitle to get titles of books. Catches titles buried in improvements, unlike getDe-
scription.
Lua
Structures
New Scripts
Fixes
Misc Improvements
• exportlegends:
– added evilness and force IDs to regions
– added profession and weapon info to relevant entities
– added support for many new history events in 0.47
– added historical event relationships and supplementary data
• full-heal:
– made resurrection produce a historical event viewable in Legends mode
– made error messages more explanatory
• install-info: added DFHack build ID to report
• modtools/create-item: added -matchingGloves and -matchingShoes arguments
• modtools/create-unit:
– added -duration argument to make the unit vanish after some time
– added -locationRange argument to allow spawning in a random position within a defined area
– added -locationType argument to specify the type of location to spawn in
Internals
Structures
• historical_figure.vague_relationships: identified
• historical_figure_info.known_info: renamed from secret, identified some fields
• historical_figure: renamed unit_id2 to nemesis_id
• history_event_circumstance_info: new struct type (and changed several history_event sub-
classes to use this)
• history_event_reason_info: new struct type (and changed several history_event subclasses to
use this)
• honors_type: identified several fields
• interaction_effect_create_itemst: new struct type
• interaction_effect_summon_unitst: new struct type
• item: identified several vmethods
• layer_type: new enum type
• plant.damage_flags: added is_dead
• plot_role_type: new enum type
• plot_strategy_type: new enum type
• relationship_event_supplement: new struct type
• relationship_event: new struct type
• specific_ref: moved union data to data field
• ui_look_list: moved union fields to data and renamed to match type enum
• ui_sidebar_menus.location: added new profession-related fields, renamed and fixed types of deity-
related fields
• ui_sidebar_mode: added ZonesLocationInfo
• unit_action: rearranged as tagged union with new sub-types; existing code should be compatible
• vague_relationship_type: new enum type
• vermin_flags: identified is_roaming_colony
• viewscreen_justicest: identified interrogation-related fields
• world_data.field_battles: identified and named several fields
New Scripts
Fixes
Misc Improvements
• deep-embark:
– improved support for using directly from the DFHack console
– added a -clear option to cancel
• exportlegends:
– added identity information
– added creature raw names and flags
• gui/prerelease-warning: updated links and information about nightly builds
• modtools/syndrome-trigger: enabled simultaneous use of -synclass and -syndrome
• repeat: added -list option
Structures
New Plugins
New Scripts
Fixes
• Fixed a crash in the macOS/Linux console when the prompt was wider than the screen width
• Fixed inconsistent results from Units::isGay for asexual units
• Fixed some cases where Lua filtered lists would not properly intercept keys, potentially triggering other actions
on the same screen
• autofarm:
– fixed biome detection to properly determine crop assignments on surface farms
– reimplemented as a C++ plugin to make proper biome detection possible
• bodyswap: fixed companion list not being updated often enough
• cxxrandom: removed some extraneous debug information
• digfort: now accounts for z-level changes when calculating maximum y dimension
• embark-assistant:
– fixed bug causing crash on worlds without generated metals (as well as pruning vectors as originally
intended).
– fixed bug causing mineral matching to fail to cut off at the magma sea, reporting presence of things that
aren’t (like DF does currently).
– fixed bug causing half of the river tiles not to be recognized.
– added logic to detect some river tiles DF doesn’t generate data for (but are definitely present).
• Eventful: fixed invalid building ID in some building events
• exportlegends: now escapes special characters in names properly
• getplants: fixed designation of plants out of season (note that picked plants are still designated incorrectly)
• gui/autogems: fixed error when no world is loaded
• gui/companion-order:
– fixed error when resetting group leaders
– leave now properly removes companion links
• gui/create-item: fixed module support - can now be used from other scripts
• gui/stamper:
– stopped “invert” from resetting the designation type
– switched to using DF’s designation keybindings instead of custom bindings
– fixed some typos and text overlapping
• modtools/create-unit:
– fixed an error associating historical entities with units
– stopped recalculating health to avoid newly-created citizens triggering a “recover wounded” job
– fixed units created in arena mode having blank names
– fixed units created in arena mode having the wrong race and/or interaction effects applied after creating
units manually in-game
– stopped units from spawning with extra items or skills previously selected in the arena
– stopped setting some unneeded flags that could result in glowing creature tiles
– set units created in adventure mode to have no family, instead of being related to the first creature in the
world
• modtools/reaction-product-trigger:
– fixed an error dealing with reactions in adventure mode
– blocked \\BUILDING_ID for adventure mode reactions
– fixed -clear to work without passing other unneeded arguments
• modtools/reaction-trigger:
– fixed a bug when determining whether a command was run
– fixed handling of -resetPolicy
• mousequery: fixed calculation of map dimensions, which was sometimes preventing scrolling the map with the
mouse when TWBT was enabled
• remotefortressreader: fixed a crash when a unit’s path has a length of 0
• stonesense: fixed crash due to wagons and other soul-less creatures
• tame: now sets the civ ID of tamed animals (fixes compatibility with autobutcher)
• title-folder: silenced error when PRINT_MODE is set to TEXT
Misc Improvements
• Added a note to dfhack-run when called with no arguments (which is usually unintentional)
• On macOS, the launcher now attempts to un-quarantine the rest of DFHack
• bodyswap: added arena mode support
• combine-drinks: added more default output, similar to combine-plants
• createitem: added a list of valid castes to the “invalid caste” error message, for convenience
• devel/export-dt-ini: added more size information needed by newer Dwarf Therapist versions
• dwarfmonitor: enabled widgets to access other scripts and plugins by switching to the core Lua context
• embark-assistant:
– added an in-game option to activate on the embark screen
– changed waterfall detection to look for level drop rather than just presence
– changed matching to take incursions, i.e. parts of other biomes, into consideration when evaluating tiles.
This allows for e.g. finding multiple biomes on single tile embarks.
– changed overlay display to show when incursion surveying is incomplete
– changed overlay display to show evil weather
– added optional parameter “fileresult” for crude external harness automated match support
– improved focus movement logic to go to only required world tiles, increasing speed of subsequent searches
considerably
• exportlegends: added rivers to custom XML export
• exterminate: added support for a special enemy caste
• gui/gm-unit:
– added support for editing:
– added attribute editor
– added orientation editor
– added editor for bodies and body parts
– added color editor
– added belief editor
– added personality editor
• modtools/create-item: documented already-existing -quality option
• modtools/create-unit:
– added the ability to specify \\LOCAL for the fort group entity
– now enables the default labours for adult units with CAN_LEARN.
– now sets historical figure orientation.
– improved speed of creating multiple units at once
– made the script usable as a module (from other scripts)
• modtools/reaction-trigger:
– added -ignoreWorker: ignores the worker when selecting the targets
– changed the default behavior to skip inactive/dead units; added -dontSkipInactive to include crea-
tures that are inactive
– added -range: controls how far elligible targets can be from the workshop
– syndromes now are applied before commands are run, not after
– if both a command and a syndrome are given, the command only runs if the syndrome could be applied
• mousequery: made it more clear when features are enabled
• remotefortressreader:
– added a basic framework for controlling and reading the menus in DF (currently only supports the building
menu)
– added support for reading item raws
– added a check for whether or not the game is currently saving or loading, for utilities to check if it’s safe
to read from DF
– added unit facing direction estimate and position within tiles
– added unit age
– added unit wounds
– added tree information
– added check for units’ current jobs when calculating the direction they are facing
API
• Added new plugin_load_data and plugin_save_data events for plugins to load/save persistent data
• Added Maps::GetBiomeType and Maps::GetBiomeTypeByRef to infer biome types properly
• Added Units::getPhysicalDescription (note that this depends on the
unit_get_physical_description offset, which is not yet available for all DF builds)
Internals
Lua
Ruby
Structures
New Plugins
New Scripts
Fixes
Misc Improvements
• full-heal:
– added -all, -all_civ and -all_citizens arguments
– added module support
– now removes historical figure death dates and ghost data
• growcrops: added all argument to grow all crops
• gui/load-screen: improved documentation
• labormanager: now takes nature value into account when assigning jobs
• open-legends: added warning about risk of save corruption and improved related documentation
• points: added support when in viewscreen_setupdwarfgamest and improved error messages
• siren: removed break handling (relevant misc_trait_type was no longer used - see “Structures” section)
API
Internals
• Added a usable unit test framework for basic tests, and a few basic tests
• Added [Link] with intellisense support
• Changed plugins/[Link] to be ignored by git and created (if needed) at build time
instead
• Core: various thread safety and memory management improvements
• Fixed CMake build dependencies for generated header files
• Fixed custom CMAKE_CXX_FLAGS not being passed to plugins
• Linux/macOS: changed recommended build backend from Make to Ninja (Make builds will be significantly
slower now)
Lua
Structures
• incident_sub6_performance:
– named poetic_form_id, musical_form_id, and dance_form_id
– made performance_event an enum
• misc_trait_type: removed LikesOutdoors, Hardened, TimeSinceBreak, OnBreak (all unused
by DF)
• musical_form_instruments: named minimum_required and maximum_permitted
• musical_form: named voices field
• plant_tree_info: identified extent_east, etc.
• plant_tree_tile: gave connection bits more meaningful names (e.g. connection_east instead of
thick_branches_1)
• poetic_form: identified many fields and related enum/bitfield types
• setup_character_info: identified skill_points_remaining (for embark-skills)
• [Link]: identified fortress_site
• [Link]: identified kill_rect_targets_scroll
• ui: fixed alignment of main and squads (fixes tweak hotkey-clear and DF-AI)
• unit_action.attack:
– added lightly_tap and spar_report flags
– identified attack_skill
• unit_flags3: identified marked_for_gelding
• unit_personality: identified stress_drain, stress_boost, likes_outdoors,
combat_hardened
• unit_storage_status: newly identified type, stores noble holdings information (used in
viewscreen_layer_noblelistst)
• unit_thought_type: added new expulsion thoughts from 0.44.12
• viewscreen_layer_arena_creaturest: identified item- and name-related fields
• viewscreen_layer_militaryst: identified [Link].assigned_items
• viewscreen_layer_noblelistst: identified storage_status (see unit_storage_status
type)
• viewscreen_new_regionst:
– changed many int8_t fields to bool
– identified rejection_msg, raw_folder, load_world_params
• viewscreen_setupadventurest: identified some nemesis and personality fields, and page.
ChooseHistfig
• world_data: added mountain_peak_flags type, including is_volcano
• world_history: identified names and/or types of some fields
• world_site: identified names and/or types of some fields
• written_content: named poetic_form
Fixes
Misc Improvements
• Reduced time for designation jobs from tools like dig to be assigned workers
• embark-assistant:
– Switched to standard scrolling keys, improved spacing slightly
– Introduced scrolling of Finder search criteria, removing requirement for 46 lines to work properly
(Help/Info still formatted for 46 lines).
– Added Freezing search criterion, allowing searches for NA/Frozen/At_Least_Partial/Partial/At_Most_Partial/Never
Freezing embarks.
• rejuvenate:
– Added -all argument to apply to all citizens
– Added -force to include units under 20 years old
– Clarified documentation
API
Internals
Structures
Fixes
API
Structures
Internals
Fixes
API
Fixes
Misc Improvements
• Console:
– added support for multibyte characters on Linux/macOS
– made the console exit properly when an interactive command is active (liquids, mode, tiletypes)
• Linux: added automatic support for GCC sanitizers in dfhack script
• Made the DFHACK_PORT environment variable take priority over [Link]
• dfhack-run: added support for port specified in [Link], to match DFHack’s behavior
• digfort: added better map bounds checking
• remove-stress:
– added support for -all as an alternative to the existing all argument for consistency
– sped up significantly
– improved output/error messages
– now removes tantrums, depression, and obliviousness
• ruby: sped up handling of onupdate events
API
Internals
Lua
• Added printall_recurse to print tables and DF references recursively. It can be also used with ^ from
the lua interpreter.
• [Link]: List:setChoices clones choices for internal table changes
Structures
Structures
• ui_sidebar_menus:
– unit.in_squad: renamed to unit.squad_list_opened, fixed location
– unit: added expel_error and other unknown fields new in 0.44.11
– hospital: added, new in 0.44.11
– num_speech_tokens, unk_17d8: moved out of command_line to fix layout on x64
• viewscreen_civlistst: added a few new fields (incomplete)
• viewscreen_locationsst: identified edit_input
New Plugins
• cxxrandom: exposes some features of the C++11 random number library to Lua
New Scripts
Fixes
• Fixed many tools incorrectly using the dead unit flag (they should generally check [Link] instead)
• Fixed many tools passing incorrect arguments to printf-style functions, including a few possible crashes (change-
layer, follow, forceequip, generated-creature-renamer)
• Fixed several bugs in Lua scripts found by static analysis (df-luacheck)
• Fixed -g flag (GDB) in Linux dfhack script (particularly on x64)
• autochop, autodump, autogems, automelt, autotrade, buildingplan, dwarfmonitor, fix-unit-occupancy, fortplan,
stockflow: fix issues with periodic tasks not working for some time after save/load cycles
• autogems:
– stop running repeatedly when paused
– fixed crash when furnaces are linked to same stockpiles as jeweler’s workshops
• autogems, fix-unit-occupancy: stopped running when a fort isn’t loaded (e.g. while embarking)
• autounsuspend: now skips planned buildings
• ban-cooking: fixed errors introduced by kitchen structure changes in 0.44.10-r1
• buildingplan, fortplan: stopped running before a world has fully loaded
• deramp: fixed deramp to find designations that already have jobs posted
• dig: fixed “Inappropriate dig square” announcements if digging job has been posted
• fixnaked: fixed errors due to emotion changes in 0.44
• remove-stress: fixed an error when running on soul-less units (e.g. with -all)
• reveal: stopped revealing tiles adjacent to tiles above open space inappropriately
• stockpiles: loadstock now sets usable and unusable weapon and armor settings
• stocks: stopped listing carried items under stockpiles where they were picked up from
Misc Improvements
API
Internals
• Added build option to generate symbols for large generated files containing df-structures metadata
• Added fallback for YouCompleteMe database lookup failures (e.g. for newly-created files)
• Improved efficiency and error handling in stl_vsprintf and related functions
• jsoncpp: fixed constructor with long on Linux
Lua
Structures
New Scripts
New Tweaks
• tweak kitchen-prefs-all: adds an option to toggle cook/brew for all visible items in kitchen preferences
• tweak stone-status-all: adds an option to toggle the economic status of all stones
Fixes
Misc Improvements
API
Internals
Structures
New Scripts
Fixes
• Units::getAnyUnit(): fixed a couple problematic conditions and potential segfaults if global addresses are miss-
ing
• autodump, automelt, autotrade, stocks, stockpiles: fixed conflict with building renaming
• exterminate: fixed documentation of this option
• full-heal:
– units no longer have a tendency to melt after being healed
– healed units are no longer treated as patients by hospital staff
– healed units no longer attempt to clean themselves unsuccessfully
– wounded fliers now regain the ability to fly upon being healing
– now heals suffocation, numbness, infection, spilled guts and gelding
• modtools/create-unit:
– creatures of the appropriate age are now spawned as babies or children where applicable
– fix: civ_id is now properly assigned to historical_figure, resolving several hostility issues (spawned pets
are no longer attacked by fortress military!)
– fix: unnamed creatures are no longer spawned with a string of numbers as a first name
• stockpiles: stopped sidebar option from overlapping with autodump
• tweak block-labors: fixed two causes of crashes related in the v-p-l menu
Misc Improvements
Internals
New Scripts
Fixes
Misc Improvements
Internals
Fixes
Misc Improvements
Internals
Structures
Fixes
Fixes
• fix/dead-units: fixed a bug that could remove some arriving (not dead) units
Misc Improvements
Structures
• Added symbols for Toady’s 0.44.07 Linux test build to fix Bug 10615
• world_site: fixed alignment
Fixes
Misc Improvements
• embark-assistant:
– Added search for adamantine
– Now supports saving/loading profiles
• fillneeds: added -all option to apply to all units
• remotefortressreader: added flows, instruments, tool names, campfires, ocean waves, spiderwebs
Structures
New Plugins
New Scripts
• adv-fix-sleepers: fixes units in adventure mode who refuse to wake up (Bug 6798)
• hermit: blocks caravans, migrants, diplomats (for hermit challenge)
New Features
• With PRINT_MODE:TEXT, setting the DFHACK_HEADLESS environment variable will hide DF’s display and
allow the console to be used normally. (Note that this is intended for testing and is not very useful for actual
gameplay.)
Fixes
Misc Improvements
New Scripts
Fixes
Misc Improvements
Removed
Internals
Structures
Misc Improvements
• gui/liquids: added more keybindings: 0-7 to change liquid level, P/B to cycle backwards
Structures
Fixes
Structures
Fixes
• autolabor, autohauler, labormanager: added support for “put item on display” jobs and building/destroying
display furniture
• gui/gm-editor: fixed an error when editing primitives in Lua tables
Misc Improvements
Structures
• Added job_type.PutItemOnDisplay
• Added twbt_render_map code offset on x64
• Fixed an issue preventing enabler from being allocated by DFHack
• Found renderer vtable on osx64
• New globals:
– version
– min_load_version
– movie_version
– basic_seed
– title
– title_spaced
– ui_building_resize_radius
• adventure_movement_optionst, adventure_movement_hold_tilest,
adventure_movement_climbst: named coordinate fields
• mission: added type
• unit: added 3 new vmethods: getCreatureTile, getCorpseTile, getGlowTile
• viewscreen_assign_display_itemst: fixed layout on x64 and identified many fields
• viewscreen_reportlistst: fixed layout, added mission_id vector
• [Link]: named missions vector
Lua
New Scripts
Fixes
• Fixed issues with the console output color affecting the prompt on Windows
• createitem: stopped items from teleporting away in some forts
• gui/gm-unit: can now edit mining skill
• gui/quickcmd: stopped error from adding too many commands
• modtools/create-unit: fixed error when domesticating units
Misc Improvements
Removed
Lua
• Exposed get_vector() (from C++) for all types that support find(), e.g. [Link].get_vector()
== [Link]
Structures
• Added buildings_other_id.DISPLAY_CASE
• Fixed unit alignment
• Fixed viewscreen_titlest.start_savegames alignment
• Identified historical_entity.[Link] (deity IDs)
• Located start_dwarf_count offset for all builds except 64-bit Linux; startdwarf should work now
New Scripts
Fixes
• Fixed a crash that could occur if a symbol table in [Link] had no content
Lua
Structures
DFHack has extensive support for the Lua scripting language, providing access to:
1. Raw data structures used by the game.
2. Many C++ functions for high-level access to these structures, and interaction with dfhack itself.
3. Some functions exported by C++ plugins.
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 imple-
mented by Lua files located in hack/lua/* (library/lua/* in the git repo).
Contents
– Building-hacks
– Luasocket
– map-render
– cxxrandom
– xlsxreader
• Scripts
– Enabling and disabling scripts
– Save init script
Data structures of the game are defined in XML files located in library/xml (and online, and automatically ex-
ported 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. 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.
3. 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.
4. The global object
[Link] 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.
In addition to the global object and top-level types the df global also contains a few global builtin utility functions.
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 the destructor is not available, returns false. (This
typically only occurs when trying to delete an instance of a DF class with virtual methods whose vtable address
has not been found; it is impossible for delete() to determine the validity of ref.)
Warning: ref must be an object allocated with new, like in C++. Calling [Link]:delete()
where obj was allocated with new will not work. After delete() returns, ref remains as a dangling
pointer, like a raw C++ pointer would. Any accesses to ref after ref:delete() has been called are
undefined behavior.
• 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 a value field of the right type. If the object’s XML definition has a ref-target
attribute, they will also have a read-only ref_target field set to the corresponding type object.
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
Note: In case of inheritance, superclass fields have precedence over the subclass, but fields shadowed in this
way can still be accessed as ref['[Link]'].
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 order, which is the same as declaration order.
Container references
Note that two-dimensional arrays in C++ (ie pointers to pointers) are exposed to lua as one-dimensional. The best way
to handle this is probably array[x].value:_displace(y).
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 [Link](key) function that wraps the
find method provided in C++.
Global functions
• 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 assignment is invoked when a lua table is assigned to a C++ object or field, i.e. one of:
• ref:assign{...}
• [Link] = {...}
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. When a table is assigned to a non-NULL pointer field using the [Link] = {...} syntax, it is applied
to the target of the pointer instead.
If the pointer is NULL, the table is checked for a new field:
a. If it is nil or false, assignment fails with an error.
b. If it is true, the pointer is initialized with a newly allocated object of the declared target type of the pointer.
c. Otherwise, [Link] must be a named type, or an object of a type compatible with the pointer. The
pointer is initialized with the result of calling [Link]:new().
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.
3. If the target of the assignment is a container, a separate rule set is used:
a. 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
b. 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.
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 }
Since nil inside a table is indistinguishable from missing key, it is necessary to use [Link] 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.
• Native utilities
– Input & Output
– Exception handling
– Miscellaneous
– Locking and finalization
– Persistent configuration storage
– Material info lookup
– Random number generation
• C++ function wrappers
– Gui module
* Screens
* General-purpose selections
* Fortress mode
* Announcements
* Other
– Job module
– Units module
– Items module
– Maps module
– Burrows module
– Buildings module
* General
* Low-level
* High-level
– Constructions module
– Kitchen module
– Screen API
– PenArray class
– Filesystem module
– Console API
– Internal API
• Core interpreter context
– Event type
Native utilities
• [Link](args...)
Output tab-separated args as standard lua print would do, but without a newline.
• print(args...), [Link](args...)
A replacement of the standard library print function that works with DFHack output infrastructure.
• [Link](args...)
Same as println; intended for errors. Uses red color and logs to [Link].
• [Link]([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.
• [Link]([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.
• [Link]([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
• [Link](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 [Link]() with verbose being false. Intended to be used for user-caused errors in scripts,
where stack traces are not desirable.
• [Link](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 [Link].
• safecall(f[,args...]), [Link](f[,args...])
Just like pcall, but also prints the error using printerr before returning. Intended as a convenience function.
• [Link](coroutine[,args...])
Compares to [Link] like [Link] vs pcall.
• [Link]
Metatable of error objects used by dfhack. The objects have the following properties:
[Link] The location prefix string, or nil.
[Link] The base message string.
[Link] The stack trace string, or nil.
[Link] A different exception object, or nil.
[Link] The coroutine that has thrown the exception.
[Link] Boolean, or nil; specifies if where and stacktrace should be printed.
tostring(err), or err:tostring([verbose]) Converts the exception to string.
• [Link]
The default value of the verbose argument of err:tostring().
Miscellaneous
• [Link]
DFHack version string constant.
• [Link](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).
• 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 spec-
ifies 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().
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.
• [Link](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.
• [Link](key), entry:delete()
Removes an existing entry. Returns true if succeeded.
• [Link].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.
• [Link]({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.
• [Link]([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).
• Gui module
– Screens
– General-purpose selections
– Fortress mode
– Announcements
– Other
• Job module
• Units module
• Items module
• Maps module
• Burrows module
• Buildings module
– General
– Low-level
– High-level
• Constructions module
• Kitchen module
• Screen API
• PenArray class
• Filesystem module
• Console API
• Internal API
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.
• [Link]()
Returns the OS type string from [Link].
• [Link]()
Returns the DF version string from [Link].
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
• [Link]()
Return information about the DFHack build in use.
• [Link]()
Returns the DF directory path.
• [Link]()
Returns the dfhack directory path, i.e. ".../df/hack/".
• [Link]()
Returns the path to the current save directory, or nil if no save loaded.
• [Link]()
Returns the tick count in ms, exactly as DF ui uses.
• [Link]()
Checks if the world is loaded.
• [Link]()
Checks if the world and map are loaded.
• [Link](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.df2console()
Convert a string from DF’s CP437 encoding to the correct encoding for the DFHack console.
• dfhack.utf2df(string)
Convert a string from UTF-8 to DF’s CP437 encoding.
Note: When printing CP437-encoded text to the console (for example, names returned from TranslateName()), use
print(dfhack.df2console(text) to ensure proper display on all platforms.
Gui module
Screens
• [Link]([skip_dismissed])
Returns the topmost viewscreen. If skip_dismissed is true, ignores screens already marked to be removed.
• [Link](viewscreen)
Returns a string representation of the current focus position in the ui. The string has a “screen/foo/bar/baz. . . ”
format.
• [Link]([skip_dismissed])
Returns the focus string of the current viewscreen.
• [Link](type [, depth])
Returns the topmost viewscreen out of the top depth viewscreens with the specified type (e.g. df.
viewscreen_titlest), or nil if none match. If depth is not specified or is less than 1, all viewscreens
are checked.
General-purpose selections
• [Link]([silent])
When a job is selected in q mode, returns the job, else prints error unless silent and returns nil.
• [Link]([silent])
Returns the job selected in a workshop or unit/jobs screen.
• [Link]([silent])
Returns the unit selected via v, k, unit/jobs, or a full-screen item view of a cage or suchlike.
• [Link]([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.
• [Link]([silent])
Returns the building selected via q, t, k or i.
• [Link]([silent])
Returns the plant selected via k.
• [Link](screen)
• [Link](screen)
• [Link](screen)
• [Link](screen)
Similar to the corresponding getSelected functions, but operate on the screen given instead of the current
screen and always return nil silently on failure.
Fortress mode
• [Link]()
Returns dimensions of the main fortress mode screen. See getPanelLayout() in the [Link]
module for a more Lua-friendly version.
• [Link]([pause])
Resets the fortress mode sidebar menus and cursors to their default state. If pause is true, also pauses the
game.
• [Link](pos)
Centers the view on the given position, which can be a [Link] instance or a table assignable to a [Link]
(see Recursive table assignment), e.g.:
{x = 5, y = 7, z = 11}
getSelectedUnit().pos
xyz2pos(pos2xyz([Link]))
Announcements
• [Link](text)
Writes a string to [Link] without doing an announcement.
• [Link](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 [Link]. The announcement_flags argument provides a custom set of
[Link] options, which specify if the message should actually be displayed in the announce-
ment list, and whether to recenter or show a popup.
Returns the index of the new announcement in [Link], or -1.
• [Link](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.
• [Link](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.
• [Link](text,color[,is_bright])
Adds a regular announcement with given text, color, and brightness. The is_bright boolean actually seems to
invert the brightness.
• [Link](type,pos,text,color[,is_bright])
Like above, but also specifies a position you can zoom to from the announcement menu.
• [Link](text,color[,is_bright])
Pops up a titan-style modal announcement window.
• [Link](type,pos,text,color[,is_bright,unit1,
unit2])
Uses the type to look up options from [Link], and calls the above operations accordingly. The units
are used to call addCombatReportAuto.
Other
• [Link](x, y)
Returns the distance from the z-level of the tile at map coordinates (x, y) to the closest ground z-level below.
Defaults to 0, unless overriden by plugins.
Job module
• [Link](job)
Creates a deep copy of the given job.
• [Link](job)
Prints info about the job.
• [Link](jobitem,idx)
Prints info about the job item.
• [Link](job, type)
Searches for a general_ref with the given type.
• [Link](job, type)
Searches for a specific_ref with the given type.
• [Link](job)
Returns the building holding the job.
• [Link](job)
Returns the unit performing the job.
• [Link](building,worker,cooldown)
Prevent the worker from taking jobs at the specified workshop for the specified cooldown period (in ticks). This
doesn’t decrease the cooldown period in any circumstances.
• [Link](job,cooldown)
Removes the worker from the specified workshop job, and sets the cooldown period (using the same logic as
setJobCooldown). Returns true on success.
• [Link]()
Instructs the game to check buildings for jobs next frame and assign workers.
• [Link]()
Instructs the game to check designations for jobs next frame and assign workers.
• [Link].is_equal(job1,job2)
Compares important fields in the job and nested item structures.
• [Link].is_item_equal(job_item1,job_item2)
Compares important fields in the job item structures.
• [Link](job,new_id)
Adds job into [Link].job_list, and if new_id is true, then also sets its id and increases [Link].
job_next_id
• [Link](first_id)
Returns the current value of [Link].job_next_id, and if there are any jobs with first_id <= id
< job_next_id, a lua list containing them.
• [Link](job_item, item_type, item_subtype)
Does basic sanity checks to verify if the suggested item type matches the flags in the job item.
• [Link](job_item, mat_type, mat_index)
Likewise, if replacing material.
• [Link](job)
Returns the job’s description, as seen in the Units and Jobs screens.
Units module
• [Link](unit)
Returns true x,y,z of the unit, or nil if invalid; may be not equal to [Link] if caged.
• [Link](x1,y1,z1,x2,y2,z2[,filter])
Returns a table of all units within the specified coordinates. If the filter argument is given, only units where
filter(unit) returns true will be included. Note that pos2xyz() cannot currently be used to convert
coordinate objects to the arguments required by this function.
• [Link](unit, type)
Searches for a general_ref with the given type.
• [Link](unit, type)
Searches for a specific_ref with the given type.
• [Link](unit)
Returns the container (cage) item or nil.
• [Link](unit,nick)
Sets the unit’s nickname properly.
• [Link](unit)
Returns the language_name object visible in game, accounting for false identities.
• [Link](unit)
Returns the false identity of the unit if it has one, or nil.
• [Link](unit)
Returns the nemesis record of the unit if it has one, or nil.
• [Link](unit)
Checks if the unit hides improved attributes from its curse.
• [Link](unit, attr_type)
• [Link](unit, attr_type)
Computes the effective attribute value, including curse effect.
• [Link](unit)
• [Link](unit)
• [Link](unit)
• [Link](unit)
Simple checks of caste attributes that can be modified by curses.
• [Link](unit, type[, create])
Finds (or creates if requested) a misc trait object with the given id.
• [Link](unit)
The unit is active (alive and on the map).
• [Link](unit)
The unit isn’t dead or undead.
• [Link](unit)
The unit is completely dead and passive, or a ghost. Equivalent to [Link](unit) or
[Link](unit).
• [Link](unit)
The unit has been killed.
• [Link](unit)
The unit is a ghost.
• [Link](unit)
The unit is capable of rational action, i.e. not dead, insane, zombie, or active werewolf.
• [Link](unit)
The unit is of the correct race of the fortress.
• [Link](unit)
The unit is an alive sane citizen of the fortress; wraps the same checks the game uses to decide game-over by
extinction.
• [Link](unit)
The unit is visible on the map.
• [Link](unit[,true_age])
Returns the age of the unit in years as a floating-point value. If true_age is true, ignores false identities.
• [Link](unit, skill[, use_rust])
Retrieves the nominal skill level for the given unit. If use_rust is true, subtracts the rust penalty.
• [Link](unit, skill)
Computes the effective rating for the given skill, taking into account exhaustion, pain etc.
• [Link](unit, skill[, total])
Returns the experience value for the given skill. If total is true, adds experience implied by the current rating.
• [Link](unit)
Computes number of frames * 100 it takes the unit to move in its current state of mind and body.
• [Link](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.
• [Link](unit)
Returns a list of tables describing noble position assignments, or nil. Every table has fields entity,
assignment and position.
• [Link](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.
• [Link](race,caste,prof_id[,plural])
Retrieves the profession name for the given race/caste using raws.
• [Link](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.
• [Link](race,caste,prof_id)
Retrieves the profession color for the given race/caste using raws.
• [Link](unit[,goalIndex])
Retrieves the goal type of the dream that the given unit has. By default the goal of the first dream is returned.
The goalIndex parameter may be used to retrieve additional dream goals. Currently only one dream per unit is
supported by Dwarf Fortress. Support for multiple dreams may be added in future versions of Dwarf Fortress.
• [Link](unit[,goalIndex])
Retrieves the short name describing the goal of the dream that the given unit has. By default the goal of the first
dream is returned. The goalIndex parameter may be used to retrieve additional dream goals. Currently only one
dream per unit is supported by Dwarf Fortress. Support for multiple dreams may be added in future versions of
Dwarf Fortress.
• [Link](unit[,goalIndex])
Checks if given unit has achieved the goal of the dream. By default the status of the goal of the first dream is
returned. The goalIndex parameter may be used to check additional dream goals. Currently only one dream
per unit is supported by Dwarf Fortress. Support for multiple dreams may be added in future versions of Dwarf
Fortress.
• [Link](unit)
Returns a number from 0-6 indicating stress. 0 is most stressed; 6 is least. Note that 0 is guaranteed to remain
the most stressed but 6 could change in the future.
• [Link](stress_level)
Identical to getStressCategory but takes a raw stress level instead of a unit.
• [Link]()
Returns a table of the cutoffs used by the above stress level functions.
Items module
• [Link](item)
Returns true x,y,z of the item, or nil if invalid; may be not equal to [Link] if in inventory.
• [Link](item)
Returns the title of the “book” item, or an empty string if the item isn’t a “book” or it doesn’t have a title. A
“book” is a codex or a tool item that has page or writings improvements, such as scrolls and quires.
• [Link](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.
• [Link](item, type)
Searches for a general_ref with the given type.
• [Link](item, type)
Searches for a specific_ref with the given type.
• [Link](item)
Returns the owner unit or nil.
• [Link](item,unit)
Replaces the owner of the item. If unit is nil, removes ownership. Returns false in case of error.
• [Link](item)
Returns the container item or nil.
• [Link](item)
Returns a list of items contained in this one.
• [Link](item)
Returns the holder building or nil.
• [Link](item)
Returns the holder unit or nil.
• [Link](item,pos)
Move the item to the ground at position. Returns false if impossible.
• [Link](item,container)
Move the item to the container. Returns false if impossible.
• [Link](item,building[,use_mode[,force_in_building])
Move the item to the building. Returns false if impossible.
use_mode defaults to 0. If set to 2, the item will be treated as part of the building.
If force_in_building is true, the item will be considered to be stored by the building (used for items
temporarily used in traps in vanilla DF)
• [Link](item,unit,use_mode,body_part)
Move the item to the unit inventory. Returns false if impossible.
• [Link](item[, no_uncat])
Removes the item, and marks it for garbage collection unless no_uncat is true.
• [Link](item)
Turns the item into a projectile, and returns the new object, or nil if impossible.
• [Link](item_type)
Returns true if this item type uses a creature/caste pair as its material.
• [Link](item_type)
Returns the number of raw-defined subtypes of the given item type, or -1 if not applicable.
• [Link](item_type, subtype)
Returns the raw definition for the given item type and subtype, or nil if invalid.
Maps module
• [Link]()
Returns map size in blocks: x, y, z
• [Link]()
Returns map size in tiles: x, y, z
• [Link](x,y,z)
Returns a map block object for given x,y,z in local block coordinates.
• [Link](coords), or isValidTilePos(x,y,z)
Checks if the given df::coord or x,y,z in local tile coordinates are valid.
• [Link](coords), or isTileVisible(x,y,z)
Checks if the given df::coord or x,y,z in local tile coordinates is visible.
• [Link](coords), or getTileBlock(x,y,z)
Returns a map block object for given df::coord or x,y,z in local tile coordinates.
• [Link](coords), or ensureTileBlock(x,y,z)
Like getTileBlock, but if the block is not allocated, try creating it.
• [Link](coords), or getTileType(x,y,z)
Returns the tile type at the given coordinates, or nil if invalid.
• [Link](coords), or getTileFlags(x,y,z)
Returns designation and occupancy references for the given coordinates, or nil, nil if invalid.
• [Link](region_coord2d), or getRegionBiome(x,y)
Returns the biome info struct for the given global map region.
• [Link](block[,flow,temperature])
Enables updates for liquid flow or temperature, unless already active.
• [Link](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.
• [Link](index)
Returns the global feature object with the given index.
• [Link](region_coord2d,index)
Returns the local feature object with the given region coords and index.
• [Link](coords), or getTileBiomeRgn(x,y,z)
Returns x, y for use with getRegionBiome.
• [Link](pos1, pos2)
Checks if a dwarf may be able to walk between the two tiles, using a pathfinding cache maintained by the game.
Note: 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.
• [Link](tilemask)
Checks if the tile_bitmask object is not nil and contains any set bits; returns true or false.
• [Link](tilemask,x,y)
Checks if the tile_bitmask object is not nil and has the relevant bit set; returns true or false.
• [Link](tilemask,x,y,enable)
Sets the relevant bit in the tile_bitmask object to the enable argument.
• [Link](tilemask[,enable])
Sets all bits in the mask to the enable argument.
Burrows module
• [Link](name)
Returns the burrow pointer or nil.
• [Link](burrow)
Removes all units from the burrow.
• [Link](burrow,unit)
Checks if the unit is in the burrow.
• [Link](burrow,unit,enable)
Adds or removes the unit from the burrow.
• [Link](burrow)
Removes all tiles from the burrow.
• [Link](burrow)
Returns a table of map block pointers.
• [Link](burrow,tile_coord)
Checks if the tile is in burrow.
• [Link](burrow,tile_coord,enable)
Adds or removes the tile from the burrow. Returns false if invalid coords.
• [Link](burrow,block,x,y)
Checks if the tile within the block is in burrow.
• [Link](burrow,block,x,y,enable)
Adds or removes the tile from the burrow. Returns false if invalid coords.
Buildings module
General
• [Link](building, type)
Searches for a general_ref with the given type.
• [Link](building, type)
Searches for a specific_ref with the given type.
• [Link](item,unit)
Replaces the owner of the building. If unit is nil, removes ownership. Returns false in case of error.
• [Link](building)
Returns width, height, centerx, centery.
• [Link](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.
• [Link](pos), or findCivzonesAt(x,y,z)
Scans civzones, and returns a lua sequence of those that touch the given tile, or nil if none.
• [Link](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.
• [Link](pos,size[,extents,change_extents,
allow_occupied,allow_wall])
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. Set allow_wall to true if the building is unhindered by walls (such as an activity zone).
• [Link](extents,defval)
Returns the number of tiles included by extents, or defval.
• [Link](building, x, y[, room])
Checks if the building contains the specified tile, either directly, or as room.
• [Link](pos,size)
Checks if a bridge constructed at specified position would have support from terrain, and thus won’t collapse if
retracted.
• [Link](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.
• [Link](cage)
Returns a list of units in the given built cage. Note that this is different from the list of units assigned to the cage,
which can be accessed with cage.assigned_units.
Low-level
• [Link](building)
Destroys the building, or queues a deconstruction job. Returns true if the building was destroyed and deallocated
immediately.
• [Link](building)
Returns true if the building is marked for removal (with x), false otherwise.
• [Link](building[, unit])
If the building is a room, returns a description including quality modifiers, e.g. “Royal Bedroom”. Otherwise,
returns an empty string.
The unit argument is passed through to DF and may modify the room’s value depending on the unit given.
High-level
More high-level functions are implemented in lua and can be loaded by require('[Link]'). See
hack/lua/dfhack/[Link].
Among them are:
• [Link](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 [Link].
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.
• [Link]{...}
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.
– 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 civ-
zones; 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
• [Link](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.
• [Link](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.
Kitchen module
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:
• [Link]()
Returns width, height of the screen.
• [Link]()
Returns x,y of the tile the mouse is over.
• [Link]()
Checks if [GRAPHICS:YES] was specified in init.
• [Link](pen,x,y[,char,tile,map])
Paints a tile using given parameters. See below for a description of pen.
Returns false if coordinates out of bounds, or other error.
• [Link](x,y[,map])
Retrieves the contents of the specified tile from the screen buffers. Returns a pen object, or nil if invalid or
TrueType.
• [Link](pen,x,y,text[,map])
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.
• [Link](pen,x1,y1,x2,y2[,map])
Fills the rectangle specified by the coordinates with the given pen. Returns true if painting at least one character
succeeded.
• [Link](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.
• [Link]()
Fills the screen with blank background.
• [Link]()
Requests repaint of the screen by setting a flag. Unlike other functions in this section, this may be used at any
time.
• [Link](key)
Returns the string that should be used to represent the given logical keybinding on the screen in texts like “press
Key to . . . ”.
• [Link](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.
• [Link](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 [Link].
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:
• [Link](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. If the pen_or_fg argument is specified as a table or object, it completely replaces the base, and is
returned instead of it.
3. 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.
This function always returns a new pre-parsed pen, or nil.
• [Link](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.
• [Link], [Link] = 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.
Warning: As a matter of policy, in order to avoid user confusion, all interface screens added by dfhack should
bear the “DFHack” signature.
• [Link](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.
• function screen:onGetSelectedJob()
• function screen:onGetSelectedBuilding()
Implement these to provide a return value for the matching [Link]... function.
PenArray class
Screens that require significant computation in their onRender() method can use a [Link] instance to
cache their output.
• [Link](w, h)
Creates a new penarray instance with an internal buffer of w * h tiles. These dimensions currently cannot be
changed after a penarray is instantiated.
• penarray:clear()
Clears the internal buffer, similar to [Link]().
• penarray:get_dims()
Returns the x and y dimensions of the internal buffer.
• penarray:get_tile(x, y)
Returns a pen corresponding to the tile at (x, y) in the internal buffer. Note that indices are 0-based.
• penarray:set_tile(x, y, pen)
Sets the tile at (x, y) in the internal buffer to the pen given.
• penarray:draw(x, y, w, h, bufferx, buffery)
Draws the contents of the internal buffer, beginning at (bufferx, buffery) and spanning w columns and h
rows, to the screen starting at (x, y). Any invalid screen and buffer coordinates are skipped.
bufferx and buffery default to 0.
Filesystem module
Most of these functions return true on success and false on failure, unless otherwise noted.
• [Link](path)
Returns true if path exists.
• [Link](path)
Returns true if path exists and is a file.
• [Link](path)
Returns true if path exists and is a directory.
• [Link]()
Returns the current working directory. To retrieve the DF path, use [Link]() instead.
• [Link](path)
Changes the current directory to path. Use with caution.
• [Link](path)
Creates a new directory. Returns false if unsuccessful, including if path already exists.
• [Link].mkdir_recursive(path)
Creates a new directory, including any intermediate directories that don’t exist yet. Returns true if the folder
was created or already existed, or false if unsuccessful.
• [Link](path)
Removes a directory. Only works if the directory is already empty.
• [Link](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.
• [Link](path)
• [Link](path)
Return values vary across operating systems - return the st_atime and st_ctime fields of a C++ stat struct,
respectively.
• [Link](path)
Lists files/directories in a directory. Returns {} if path does not exist. Set include_prefix to false if you don’t
want the path string prepended to the returned filenames.
• [Link].listdir_recursive(path [, depth = 10[, include_prefix =
true]])
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:
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.
Console API
• [Link]()
Clears the console; equivalent to the cls built-in command.
• [Link]()
Flushes all output to the console. This can be useful when printing text that does not end in a newline but should
still be displayed.
Internal API
These functions are intended for the use by dfhack developers, and are only documented here for completeness:
• [Link]
The table used by dfhack.run_script() to give every script its own global environment, persistent be-
tween calls to the script.
• [Link]()
Returns the PE timestamp of the DF executable (only on Windows)
• [Link].getMD5()
Returns the MD5 of the DF executable (only on OS X and Linux)
• [Link](name)
Returns the global address name, or nil.
• [Link](name, value)
Sets the global address name. Returns the value of getAddress before the change.
• [Link](name)
Returns the pre-extracted vtable address name, or nil.
• [Link]()
Returns the mmap base of the executable.
• [Link]()
Returns the ASLR rebase offset of the DF executable.
• [Link](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.
• [Link]()
Returns a sequence of tables describing virtual memory ranges of the process.
• [Link](dest,src,count)
Like memmove below, but works even if dest is read-only memory, e.g. code. If destination overlaps a com-
pletely invalid memory region, or another error occurs, returns false.
• [Link](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.
• [Link](dest,src,count)
Wraps the standard memmove function. Accepts both numbers and refs as pointers.
• [Link](ptr1,ptr2,count)
Wraps the standard memcmp function.
• [Link](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.
Note: This requires an extension to be specified (.lua or .rb) - use [Link]() to include
the .lua extension automatically.
• [Link].md5(string)
Returns the MD5 hash of the given string.
• [Link].md5File(filename[,first_kb])
Computes the MD5 hash of the given file. Returns hash, length on success (where length is the number
of bytes read from the file), or nil, error on failure.
If the parameter first_kb is specified and evaluates to true, and the hash was computed successfully, a
table containing the first 1024 bytes of the file is returned as the third return value.
• [Link]()
Returns a numeric identifier of the current thread.
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.
• [Link](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.
• [Link] = 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:
• [Link]()
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 [Link] 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 [Link].
• Global environment
• utils
• dumper
• profiler
– Examples
• class
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:
• mkmodule(name)
Creates an environment table for the module. Intended to be used as:
If called the second time, returns the same table; thus providing reload support.
• reload(name)
Reloads a previously require-d module “name” from the file. Intended as a help for module development.
• dfhack.BASE_G
This variable contains the root global environment table, which is used as a base for all module and script
environments. Its contents should be kept limited to the standard Lua library and API described in this document.
Global environment
A number of variables and functions are provided in the base global environment by the mandatory init file [Link]:
• Color constants
These are applicable both for [Link]() and color fields in DF functions or structures:
• printall(obj)
If the argument is a lua table or DF object reference, prints all fields.
• printall_recurse(obj)
If the argument is a lua table or DF object reference, prints all fields recursively.
• 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
• [Link](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:
[Link] = 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.
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 [Link](list)
Iterates a df-list structure, for example [Link].job_list.
• [Link](tgt, src)
Does a recursive assignment of src into tgt. Uses [Link] if tgt is a native object ref; otherwise recurses
into lua tables.
• [Link](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 [Link]. 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 uninterest-
ing. 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.
• [Link](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:
dumper
A third-party lua table dumper module from [Link] Defines one function:
• [Link](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.
profiler
A third-party lua profiler module from [Link] Module defines one function to
create profiler objects which can be used to profile and generate report.
• [Link]([variant[, sampling_frequency]])
Returns an profile object with variant either 'time' or 'call'. 'time' variant takes optional
sampling_frequency parameter to select lua instruction counts between samples. Default is 'time'
variant with 10*1000 frequency.
'call' variant has much higher runtime cost which will increase the runtime of profiled code by factor of ten.
For the extreme costs it provides accurate function call counts that can help locate code which takes much time
in native calls.
• obj:start()
Resets collected statistics. Then it starts collecting new statistics.
• obj:stop()
Stops profile collection.
• obj:report(outfile[, sort_by_total_time])
Write a report from previous statistics collection to outfile. outfile should be writeable io file object
([Link] or [Link]). Passing true as second parameter sort_by_total_time switches sorting
order to use total time instead of default self time order.
• obj:prevent(function)
Adds an ignore filter for a function. It will ignore the pointed function and all of it children.
Examples
profiledCode()
prof:stop()
class
• [Link]
This class field is set by defclass to the parent class, and allows a readable [Link](self,
...) syntax for calling superclass methods.
• [Link] { 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 [Link](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. 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.
3. Declared ATTRS are initialized from the argument table or their default values.
4. The init methods are called via invoke_after with the argument table. This is the main constructor
method.
5. 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.
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:
• 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 implement-
ing similar protocols for certain things. The class library itself uses them for constructors.
To avoid confusion, these methods cannot be redefined.
• gui
– Misc
– ViewRect class
– Painter class
– View class
– Screen class
– FramedScreen class
• [Link]
– Widget class
– Panel class
– Pages class
– EditField class
– Label class
– List class
– FilteredList class
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 [Link](), 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 [Link] 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 coor-
dinates; 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 [Link] 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:
– [Link](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 [Link](old_pen,...), and returns self.
• painter:key_pen(...)
Sets the current keybinding pen to [Link](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 [Link](cur_pen,...), and returns self.
• painter:char([char[, ...]])
Paints one character using char and [Link](cur_pen,...); returns self. The char argu-
ment, 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 [Link](cur_pen,...); returns self.
• painter:key(keycode[, ...])
Paints the description of the keycode using [Link](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 imple-
mentation 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.
self:addviews{
Panel{
view_id = 'panel',
subviews = {
Label{ view_id = 'label' }
}
}
}
• 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 [Link], calls self:onAboutToShow(parent).
• screen:onAboutToShow(parent) (for overriding)
Called when [Link] is about to be called.
• screen:onShow()
Called by [Link] 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 [Link]().
• 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.
[Link]
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.
Panel class
Pages class
• 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
Label class
• [Link] = ...
Specifies the number of character positions to advance on the line before rendering the token.
• [Link] = pen
Specifies a pen to paint as one tile before the main part of the token.
• [Link] = ...
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.
• [Link] = '...'
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 [Link], 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.
• [Link], [Link]
Same as the attributes of the label itself, but applies only to the token.
• [Link], [Link]
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 [Link] 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.
• [Link]
Specifies a unique identifier for the token.
• [Link], 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
• 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.
edit_key If specified, the edit field is disabled until this key is pressed.
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. This is required for any entries
where text is not a string.
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:getVisibleChoices()
Returns the filtered list of 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.
7.5.5 Plugins
• blueprint
• buildingplan
• burrows
• sort
• Eventful
– List of events
– Events from EventManager
– Functions
– Examples
• Building-hacks
– Functions
– Examples
• Luasocket
– Socket class
– Client class
– Server class
– Tcp class
• map-render
– Functions
• cxxrandom
– Native functions (exported to Lua)
– Lua plugin functions
– Lua plugin classes
* crng
* normal_distribution
* real_distribution
* int_distribution
* bool_distribution
* num_sequence
• xlsxreader
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.
blueprint
Native functions:
• dig(start, end, name)
• build(start, end, name)
• place(start, end, name)
• query(start, end, name)
start and end are tables containing positions (see xyz2pos). name is used as the basis for the filename.
buildingplan
Native functions:
• bool isPlannableBuilding(df::building_type type) returns whether the building type is
handled by buildingplan
• void addPlannedBuilding(df::building *bld) suspends the building jobs and adds the building
to the monitor list
• void doCycle() runs a check for whether buildlings in the monitor list can be assigned items and unsus-
pended. This method runs automatically twice a game day, so you only need to call it directly if you want
buildingplan to do a check right now.
burrows
• 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 [Link].
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,reaction_product,unit,input_items,
input_reagents,output_items,call_native)
Auto activates if detects reactions starting with LUA_HOOK_. Is called when reaction finishes.
2. onItemContaminateWound(item,unit,wound,number1,number2)
Is called when item tries to contaminate wound (e.g. stuck in).
3. onProjItemCheckMovement(projectile)
Is called when projectile moves.
4. onProjItemCheckImpact(projectile,somebool)
Is called when projectile hits something.
5. onProjUnitCheckMovement(projectile)
Is called when projectile moves.
6. onProjUnitCheckImpact(projectile,somebool)
Is called when projectile hits something.
7. onWorkshopFillSidebarMenu(workshop,callnative)
Is called when viewing a workshop in ‘q’ mode, to populate reactions, useful for custom viewscreens for shops.
8. postWorkshopFillSidebarMenu(workshop)
Is called after calling (or not) native fillSidebarMenu(). Useful for job button tweaking (e.g. adding custom
reactions)
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. onConstructionCreatedDestroyed(building_id)
Gets called when construction is created or destroyed.
3. onJobInitiated(job)
Gets called when job is issued.
4. 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.
5. onUnitDeath(unit_id)
Gets called on unit death.
6. onItemCreated(item_id)
Gets called when item is created (except due to traders, migrants, invaders and spider webs).
7. onSyndrome(unit_id,syndrome_index)
Gets called when new syndrome appears on a unit.
8. onInvasion(invasion_id)
Gets called when new invasion happens.
9. 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.
10. 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.
11. onUnitAttack(attackerId, defenderId, woundId)
Called when a unit wounds another with a weapon. Is NOT called if blocked, dodged, deflected, or parried.
12. onUnload()
A convenience event in case you don’t want to register for every onStateChange event.
13. onInteraction(attackVerb, defendVerb, attackerId, defenderId,
attackReportId, defendReportId)
Called when a unit uses an interaction on another.
Functions
1. registerReaction(reaction_name,callback)
Simplified way of using onReactionComplete; the callback is function (same params as event).
2. removeNative(shop_name)
Removes native choice list from the building.
3. addReactionToShop(reaction_name,shop_name)
Add a custom reaction to the building.
4. 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.
5. registerSidebar(shop_name,callback)
Enable callback when sidebar for shop_name is drawn. Usefull for custom workshop views e.g. using
[Link] lib. Also accepts a class instead of function as callback. Best used with [Link]
class WorkshopOverlay.
Examples
b=require "[Link]"
[Link]=function(item,unit,un_wound,x,y)
local flw=[Link]([Link],6,0,0,50000)
end
b=require "[Link]"
[Link]("LUA_HOOK_LAY_BOMB",function(reaction,unit,in_items,in_reag,out_
˓→items,call_native)
local pos=copyall([Link])
-- spawn dragonbreath after 100 ticks
[Link](100,"ticks",function() [Link](pos,6,0,0,50000) end)
--do not call real item creation code
call_native.value=false
end)
Grenade example:
b=require "[Link]"
[Link]=function(projectile)
-- you can check if [Link] e.g. has correct material
[Link](projectile.cur_pos,6,0,0,50000)
end
Integrated tannery:
b=require "[Link]"
[Link]("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:
name custom workshop id e.g. SOAPMAKER
Examples
require('[Link]-hacks').registerBuilding{name="BONE_GRINDER",
consume=15,
gears={x=0,y=0}, --connection point
animate={
isMechanical=true, --animate the same conn. 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
(continues on next page)
Or with auto_gears:
require('[Link]-hacks').registerBuilding{name="BONE_GRINDER",
consume=15,
auto_gears=true
}
Luasocket
A way to access csocket from lua. The usage is made similar to luasocket in vanilla lua distributions. Currently only
subset of functions exist and only tcp mode is implemented.
Socket class
This is a base class for client and server sockets. You can not create it - it’s like a virtual base class in c++.
• socket:close()
Closes the connection.
• socket:setTimeout(sec,msec)
Sets the operation timeout for this socket. It’s possible to set timeout to 0. Then it performs like a non-blocking
socket.
Client class
Client is a connection socket to a server. You can get this object either from tcp:connect(address,port) or
from server:accept(). It’s a subclass of socket.
• client:receive(pattern)
Receives data. Pattern is one of:
*l read one line (default, if pattern is nil)
<number> read specified number of bytes
*a read all available data
• client:send(data)
Sends data. Data is a string.
Server class
Server is a socket that is waiting for clients. You can get this object from tcp:bind(address,port).
• server:accept()
Accepts an incoming connection if it exists. Returns a client object representing that socket.
Tcp class
map-render
A way to ask df to render a slice of map. This uses native df rendering function so it’s highly dependant on df settings
(e.g. used tileset, colors, if using graphics or not and so on. . . )
Functions
• render_map_rect(x,y,z,w,h)
returns a table with w*h*4 entries of rendered tiles. The format is same as [Link]
(tile,foreground,bright,background).
cxxrandom
• GenerateEngine(seed)
returns engine id
• DestroyEngine(rngID)
destroys corresponding engine
• NewSeed(rngID, seed)
re-seeds engine
• rollInt(rngID, min, max)
generates random integer
• rollDouble(rngID, min, max)
generates random double
• rollNormal(rngID, avg, stddev)
generates random normal[gaus.]
• rollBool(rngID, chance)
generates random boolean
• MakeNumSequence(start, end)
returns sequence id
• AddToSequence(seqID, num)
adds a number to the sequence
• ShuffleSequence(rngID, seqID)
shuffles the number sequence
• NextInSequence(seqID)
returns the next number in sequence
• MakeNewEngine(seed)
returns engine id
crng
normal_distribution
real_distribution
int_distribution
bool_distribution
num_sequence
xlsxreader
Utility functions to facilitate reading .xlsx spreadsheets. It provides the following API methods:
• file_handle open_xlsx_file(filename)
• close_xlsx_file(file_handle)
• sheet_names list_sheets(file_handle)
• sheet_handle open_sheet(file_handle, sheet_name)
• close_sheet(sheet_handle)
• cell_strings get_row(sheet_handle)
Example:
local xlsxreader = require('[Link]')
7.5.6 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. Such a comment
is required for every script in the official DFHack repository.
Note: Scripts placed in subdirectories still can be accessed, but do not clutter the ls command list (unless ls -a;
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:
• dfhack.run_script(name[,args...])
Run a lua script in hack/scripts/, as if it was started from dfhack command-line. The name argument should be
the name stem, as would be used on the command line.
Note that this function lets errors propagate to the caller.
• dfhack.script_environment(name)
Run an Lua script and return its environment. This command allows you to use scripts like modules for increased
portability. It is highly recommended that if you are a modder you put your custom modules in raw/scripts
and use script_environment instead of require so that saves with your mod installed will be self-
contained and can be transferred to people who do have DFHack but do not have your mod installed.
This is intended to only allow scripts that take appropriate action when used as a module to be loaded.
• dfhack.script_help([name, [extension]])
Returns the contents of the embedded documentation of the specified script. extension defaults to “lua”, and
name defaults to the name of the script where this function was called.
Scripts can choose to recognize the built-in enable and disable commands by including the following line any-
where in their file:
When the enable and disable commands are invoked, a dfhack_flags table will be passed to the script with
the following fields set:
• enable: Always true if the script is being enabled or disabled
• enable_state: True if the script is being enabled, false otherwise
If a save directory contains a file called raw/[Link], 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 [Link] 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.
DFHack provides a remote access interface that external tools can connect to and use to interact with DF. This is
implemented with Google protobuf messages exchanged over a TCP socket. Both the core and plugins can define
remotely-accessible methods, or RPC methods. The RPC methods currently available are not comprehensive, but can
be extended with plugins.
Contents
• Server configuration
• Developing with the remote API
– Examples
– Client libraries
• Protocol description
– Built-in messages
– Conversation flow
– Raw message types
* handshake request
* handshake reply
* header
* request
* text
* result
* failure
* quit
DFHack attempts to start a TCP server to listen for remote connections on startup. If this fails (due to the port being
in use, for example), an error message will be logged to [Link].
The server can be configured by setting options in dfhack-config/[Link]:
• allow_remote (default: false): if true, allows connections from hosts other than the local machine. This
is insecure and may allow arbitrary code execution on your machine, so it is disabled by default.
• port (default: 5000): the port that the remote server listens on. Overriding this will allow the server to work
if you have multiple instances of DF running, or if you have something else running on port 5000. Note that the
DFHACK_PORT environment variable takes precedence over this setting and may be more useful for overriding
the port temporarily.
At a high level, the core and plugins define RPC methods, and external clients can call these methods. Each method
is assigned an ID internally, which clients use to call it. These method IDs can be obtained using the special
BindMethod method, which has an ID of 0.
Examples
The dfhack-run command uses the RPC interface to invoke DFHack commands (or Lua functions) externally.
Plugins that implement RPC methods include:
• rename
• remotefortressreader
• isoworldremote
Plugins that use the RPC API include:
• stonesense
Third-party tools that use the RPC API include:
• Armok Vision (Bay12 forums thread)
Client libraries
Some external libraries are available for interacting with the remote interface from other (non-C++) languages, includ-
ing:
• RemoteClientDF-Net for C#
• dfhackrpc for Go
• dfhack-remote for JavaScript
This is a low-level description of the RPC protocol, which may be useful when developing custom clients.
A WireShark dissector for this protocol is available in the df_misc repo.
Built-in messages
These messages have hardcoded IDs; all others must be obtained through BindMethod.
Conversation flow
handshake request
handshake reply
header
Note: the two fields of this message are sometimes repurposed. Uses of this message are represented as header(x,
y), where x corresponds to the id field and y corresponds to size.
Type Name
int16_t id
int16_t (padding - unused)
int32_t size
request
Type Description
header header(id, size)
buffer Protobuf-encoded payload of the input message type of the method specified by id;
length of size bytes
text
Type Description
header header(RPC_REPLY_TEXT, size)
buffer Protobuf-encoded payload of type [Link]; length
of size bytes
result
Type Description
header header(RPC_REPLY_RESULT, size)
buffer Protobuf-encoded payload of the output message type of the oldest incomplete
method call; when received, that method call is considered completed. Length of
size bytes.
failure
Type Description
header header(RPC_REPLY_FAIL, command_result)
command_result return code of the command (a constant starting with CR_; see RemoteClient.h)
quit
Note: the server closes the connection after receiving this message.
Type Description
header header(RPC_REQUEST_QUIT, 0)
• All languages: the map field of the world global contains raw map data when the world is loaded.
Note: This page will eventually go into more detail about the available APIs. For now, it is just an overview of how
DF map data is structured.
Contents
• Tiles
Tiles
DFHack documentation, like the file you are reading now, is created as .rst files, which are in reStructuredText
(reST) format. This is a documentation format common in the Python community. It is very similar in concept - and
in syntax - to Markdown, as found on GitHub and many other places. However it is more advanced than Markdown,
with more features available when compiled to HTML, such as automatic tables of contents, cross-linking, special
external links (forum, wiki, etc) and more. The documentation is compiled by a Python tool, Sphinx.
The DFHack build process will compile the documentation, but this is disabled by default due to the additional Python
and Sphinx requirements. You typically only need to build the docs if you’re changing them, or perhaps if you want a
local HTML copy; otherwise, you can read an online version hosted by ReadTheDocs.
(Note that even if you do want a local copy, it is certainly not necessary to compile the documentation in order to read
it. Like Markdown, reST documents are designed to be just as readable in a plain-text editor as they are in HTML
format. The main thing you lose in plain text format is hyperlinking.)
Contents
• Documentation standards
• Building the documentation
– Required dependencies
* Linux
* macOS
* Windows
– Using CMake
– Running Sphinx manually
– Building a PDF version
• Building the changelogs
– Changelog syntax
Whether you’re adding new code or just fixing old documentation (and there’s plenty), there are a few important stan-
dards for completeness and consistent style. Treat this section as a guide rather than iron law, match the surrounding
text, and you’ll be fine.
Each command should have a short (~54 character) help string, which is shown by the ls command. For scripts, this is
a comment on the first line (the comment marker and whitespace is stripped). For plugins it’s the second argument to
PluginCommand. Please make this brief but descriptive!
Everything should be documented! If it’s not clear where a particular thing should be documented, ask on IRC or in
the DFHack thread on Bay12 - as well as getting help, you’ll be providing valuable feedback that makes it easier for
future readers!
Scripts can use a custom autodoc function, based on the Sphinx include directive - anything between the tokens
is copied into the appropriate scripts documentation page. For Ruby, we follow the built-in docstring convention
(=begin and =end). For Lua, the tokens are [====[ and ]====] - ordinary multi-line strings. It is highly
encouraged to reuse this string as the in-console documentation by (e.g.) printing it when a -help argument is given.
The docs must have a heading which exactly matches the command, underlined with ===== to the same length. For
example, a lua file would have:
add-thought
===========
Adds a thought or emotion to the selected unit. Can be used by other scripts,
(continues on next page)
]====]
Where the heading for a section is also the name of a command, the spelling and case should exactly match the
command to enter in the DFHack command line.
Try to keep lines within 80-100 characters, so it’s readable in plain text in the terminal - Sphinx (our documentation
system) will make sure paragraphs flow.
If there aren’t many options or examples to show, they can go in a paragraph of text. Use double-backticks to put
commands in monospaced font, like this:
You can use ``cleanowned scattered x`` to dump tattered or abandoned items.
If the command takes more than three arguments, format the list as a table called Usage. The table only lists arguments,
not full commands. Input values are specified in angle brackets. Example:
Usage:
To demonstrate usage - useful mainly when the syntax is complicated, list the full command with arguments in
monospaced font, then indent the next line and describe the effect:
``resume all``
Resumes all suspended constructions.
If it would be helpful to mention another DFHack command, don’t just type the name - add a hyperlink! Specify
the link target in backticks, and it will be replaced with the corresponding title and linked: e.g. `autolabor` =>
autolabor. Link targets should be equivalent to the command described (without file extension), and placed above the
heading of that section like this:
.. _autolabor:
autolabor
=========
Add link targets if you need them, but otherwise plain headings are preferred. Scripts have link targets created auto-
matically.
Required dependencies
In order to build the documentation, you must have Python with Sphinx version 1.8 or later. Both Python 2.x and 3.x
are supported.
When installing Sphinx from OS package managers, be aware that there is another program called Sphinx, com-
pletely unrelated to documentation management. Be sure you are installing the right Sphinx; it may be called
python-sphinx, for example. To avoid doubt, pip can be used instead as detailed below.
Once you have installed Sphinx, sphinx-build --version should report the version of Sphinx that you have
installed. If this works, CMake should also be able to find Sphinx.
For more detailed platform-specific instructions, see the sections below:
• Linux
• macOS
• Windows
Linux
Most Linux distributions will include Python by default. If not, start by installing Python (preferably Python 3). On
Debian-based distros:
Check your package manager to see if Sphinx 1.8 or later is available. On Debian-based distros, this package is named
python3-sphinx. If this package is new enough, you can install it directly. If not, or if you want to use a newer
Sphinx version (which may result in faster builds), you can install Sphinx through the pip package manager instead.
On Debian-based distros, you can install pip with:
If you run this as an unprivileged user, it may install a local copy of Sphinx for your user only. The sphinx-build
executable will typically end up in ~/.local/bin/ in this case. Alternatively, you can install Sphinx system-wide
by running pip with sudo. In any case, you will need the folder containing sphinx-build to be in your $PATH.
macOS
macOS has Python 2.7 installed by default, but it does not have the pip package manager.
You can install Homebrew’s Python 3, which includes pip, and then install the latest Sphinx using pip:
This will install Sphinx for macOS’s system Python 2.7, without needing pip.
Either method works; if you plan to use Python for other purposes, it might best to install Homebrew’s Python 3 so
that you have the latest Python as well as pip. If not, just installing sphinx-doc for macOS’s system Python 2.7 is fine.
Windows
Python for Windows can be downloaded from [Link]. The latest version of Python 3 is recommended, as it
includes pip already.
You can also install Python and pip through the Chocolatey package manager. After installing Chocolatey as outlined
in the Windows compilation instructions, run the following command from an elevated (admin) command prompt (e.g.
[Link]):
Once you have pip available, you can install Sphinx with the following command:
Note that this may require opening a new (admin) command prompt if you just installed pip from the same command
prompt.
Using CMake
Enabling the BUILD_DOCS CMake option will cause the documentation to be built whenever it changes as part of the
normal DFHack build process. There are several ways to do this:
• When initially running CMake, add -DBUILD_DOCS:bool=ON to your cmake command. For example:
• If you have already run CMake, you can simply run it again from your build folder to update your configuration:
cmake .. -DBUILD_DOCS:bool=ON
You can also build the documentation without going through CMake, which may be faster. There is a docs/build.
sh script provided for Linux and macOS that will run essentially the same command that CMake runs - see the script
for additional options.
To build the documentation with default options, run the following command from the root DFHack folder:
sphinx-build . docs/html
Sphinx has many options to enable clean builds, parallel builds, logging, and more - run sphinx-build --help
for details.
ReadTheDocs automatically builds a PDF version of the documentation (available under the “Downloads” section
when clicking on the release selector). If you want to build a PDF version locally, you will need pdflatex, which is
part of a TeX distribution. The following command will then build a PDF, located in docs/pdf/latex/DFHack.
pdf, with default options:
sphinx-build -M latexpdf . ./docs/pdf
There is a docs/[Link] script provided for Linux and macOS that runs this command for convenience -
see the script for additional options.
If you have Python installed, but do not want to build all of the documentation, you can build the changelogs with
the docs/gen_changelog.py script. This script provides additional options, including one to build individual
changelogs for all DFHack versions - run python docs/gen_changelog.py --help for details.
Changelog entries are obtained from [Link] files in multiple repos. This allows changes to be listed in
the same repo where they were made. These changelogs are combined as part of the changelog build process:
• docs/[Link] for changes in the main dfhack repo
• scripts/[Link] for changes made to scripts in the scripts repo
• library/xml/[Link] for changes made in the df-structures repo
Building the changelogs generates two files: docs/_auto/[Link] and docs/_auto/[Link].
These correspond to Changelog and Development Changelog and contain changes organized by stable and devel-
opment DFHack releases, respectively. For example, an entry listed under “0.44.05-alpha1” in [Link] will be
listed under that version in the development changelog as well, but under “0.44.05-r1” in the stable changelog (assum-
ing that is the closest stable release after 0.44.05-alpha1). An entry listed under a stable release like “0.44.05-r1” in
[Link] will be listed under that release in both the stable changelog and the development changelog.
Changelog syntax
DFHack’s information about DF’s data structures is stored in XML files in the df-structures repository. If you have
obtained a local copy of the DFHack source, DF-structures is included as a submodule in library/xml.
Data structure layouts are described in files named with the df.*.xml pattern. This information is transformed
by a Perl script ([Link]) into C++ headers, as well as metadata for the Lua wrapper. This ultimately allows
DFHack code to access DF data directly, with the same speed and capabilities as DF itself, which is an advantage over
the older out-of-process approach (used by debuggers and utilities like Dwarf Therapist). The main disadvantage of
this approach is that any compiled code relying on these layouts will break when DF’s layout changes, and will need
to be recompiled for every new DF version.
Addresses of DF global objects and vtables are stored in a separate file, [Link]. Since these are only absolute
addresses, they do not need to be compiled in to DFHack code, and are instead loaded at runtime. This makes fixes
and additions to global addresses possible without recompiling DFHack. In an installed copy of DFHack, this file can
be found at the root of the hack folder.
The following pages contain more detailed information about various aspects of DF-structures:
Contents
• General Background
• XML file format
– Enum type definition
* Dereference syntax
* Basic properties
– Reference objects
* Primitive types
* Enums
* Pointers
* Compounds
* Sequences
– Code helpers
– Examples
This document documents the XML syntax used to define DF data structures for use in dfhack.
General Background
Originally dfhack used a file called [Link] to describe data structures of the game. It explicitly listed addresses
of known global variables, and offsets within structures to fields, not unlike the ini files used by Dwarf Therapist.
This format is a good choice when only a small number of fields and objects need to be accessed, and allows a program
to work with many different versions of DF, provided that the relevant fields and objects work in the same way.
However, as the number of known fields and objects grow, maintaining the explicit offset lists quickly becomes difficult
and error prone. Also, even when almost all fields of a structure become known, the format fails to represent and exploit
their relative position, which in practice is actually more stable than the specific offset values.
This format instead represents data structure layout purely via listing all fields in the correct order, exactly like a
structure definition does in the C++ language itself; in fact, these XML definitions are translated into C++ headers in a
mostly straightforward way (the more tricky bits are things like correctly processing circular references, or generating
metadata for lua). There is still a file with numeric data, but it only contains absolute addresses of global objects.
As a downside, dfhack now needs to be recompiled every time layout of some data structure changes; on the other
hand, accessing DF structures from C++ plugins now has no overhead compared with DF’s own code. Also, practice
shows that the more fields are known in a structure, the easier it is to spot what exactly has changed, and fix the exact
area.
Excluding content of tags like <comment> or <code-helper>, all plain text inside tag bodies is ignored and may
be freely used instead of XML comments.
NOTE: Using XML tags and/or attributes not defined in this document is not allowed.
Every enum has an integer base type, which defaults to int32_t if omitted.
Like in C++, enum items may either explicitly specify an integer value, or rely on auto-increment behavior.
As in most cases, the name attribute may be omitted if unknown; the code generator would produce a random identifier
to satisfy C++ language requirements.
The XML syntax allows associating attributes with enum items, thus embedding lookup tables for use in C++ or lua
code.
Every attribute must be declared at the top level of the enum:
<enum-attr name='attr'
[type-name='primitive-or-enum']
[default-value='...']
[use-key-name='true/false']
[is-list='true/false']/>
The declaration allows specifying a numeric, or other enum type for the attribute, overriding the default const
char* string type.
An explicit default value may also be specified; otherwise the attribute defaults to NULL or 0. If use-key-name is
true, the corresponding enum-item’s name is used as the default value.
Alternatively, an attribute may be declared to be a list, instead of a scalar. In this case, the default is an empty list.
NOTE: Attribute name 'key' is reserved for a built-in string attribute representing the enum item key.
For every declared attribute, every enum-item tag may contain an attribute value definition:
<enum-item name='key'>
<item-attr name='attr' value='...'/>
...
</enum-item>
For list attributes, multiple item-attr entries may be used to define the list contents.
Like enums, bitfields have an integer base type, which defaults to uint32_t. The total number of bits in the bitfield
must not exceed the base type size.
A bitfield item may be defined to occupy multiple bits via the count attribute. It also may have an enum type; due to
compiler limitations, the base-type of the enum must be exactly the same as the bitfield itself.
<struct-type type-name='name'
[is-union='true/false']
[inherits-from='struct_type']
[instance-vector='expr']
[key-field='identifier']>
...
fields
...
</struct-type>
The instance-vector attribute may be used to specify a global vector that canonically contains all instances of the
structure. Code generation uses it to produce a find static method. If key-field is specified, this method uses binary
search by the referred field; otherwise it just indexes the vector with its integer argument.
Primitive fields
<int32_t name='id'.../>
Supported number types are: int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t,
int64_t, uint64_t, s-float (single float), d-float (double float).
3) Boolean:
<bool name='id'.../>
4) String:
<stl-fstream name='id'/>
This is not really a primitive type, but classified as such since it is treated as a predefined opaque object (a-la
padding).
Primitives support the following attributes:
refers-to='expr'
Specifies a GUI hyperlink to an object returned by an arbitrary expression.
The expression receives the value of the field as $, and the reference to the field as $$.
ref-target='type'
Specifies a hyperlink to an instance of type, identified by the value of the field. The instance is retrieved
via instance-vector and key-field, or a <code-helper name='find-instance'> in the target
type definition.
aux-value='expr'
Specifies an additional value for use in the find-instance code helper.
Unlike refers-to, the expression receives the reference to the field as $, and a reference to the containing
structure as $$; i.e. the arguments are shifted one step toward parent. This is because the value of the
field is already implicitly passed to find-instance.
The find-instance helper receives the field value as $, and aux-value as $$.
Substructure fields
As seen above, a nested structure may either use a global type defined elsewhere, or define an ad-hoc structure in-place.
In the in-place case, omitting name has a special meaning of defining an anonymous nested struct or union.
Tagged unions
Union compounds and vectors of union compounds can additionally have union-tag-field and
union-tag-attr attributes.
union-tag-field sets the name of the field that holds the tag for the union. Union compounds must have tags
that are enumeration fields, while vectors of union compounds can have tags that are vectors of an enumeration type,
or in the case of a union with exactly 2 members, a bit vector.
union-tag-attr overrides the name used to find the union member. By default, the field with a name equal to the
enum key is chosen. When this attribute is set, the specified enum attr will be used instead.
Enum fields
Like with substructures, enums may be either referenced globals, or ad-hoc definitions.
In the former case, when base-type of the field and the enum differ, a special wrapper is added to coerce the size, or,
if impossible, the enum type is completely replaced with the base-type. The net effect is that the field always has the
expected size and alignment.
If no base-type is specified on the field, the one in the global type definition has complete precedence. This is not
recommended.
Nested bitfields
Container fields
A number of tags fall under the ‘container’ abstraction. The common element is that the fields they define reference
objects of another type. This includes things like pointers, arrays or vectors.
Abstract container
The basic syntactic property of a container is that it requires exactly one nested field tag in order to specify the
contained item:
<container>
<field .../>
</container>
NOTE: The container tag is used here as a placeholder for any real tag following the container syntax.
For convenience, the following automatic rewrite rules are applied:
1) The type-name attribute:
<container type-name='foo' .../>
is rewritten into:
<container ...>
<compound type-name='foo' .../>
</container>
is rewritten into:
<container ...>
<pointer type-name='foo' .../>
</container>
<container ...>
<compound ...>
<field1 .../>
<field2 .../>
</compound>
</container>
<container>
<padding size='4'/>
</container>
NOTE: These rules are mutually exclusive, and it is an error to specify both of the attributes (unless it is
type-name='pointer'), or combine nested fields with any of them.
When the above rewrites are applied and result in creation of a new tag, the following attributes are copied to it from
the container tag, if applicable: key-field, refers-to, ref-target, aux-value. They otherwise have no
effect on the container itself.
This means that:
Pointer fields
Abstract sequence
Containers that actually contain a sequence of objects support these additional attributes:
index-refers-to='expr'
Specifies a GUI hyperlink from any item in the container to the object returned by the expression.
The expression receives the index of the item in the container as $, and a reference to the container as $$.
index-enum='enum_type'
Associates an enum with the indices of the container. The GUI tries to use enum item names instead of
numbers when displaying the items, and lua may allow using strings as indices.
Standard containers
DF-specific containers
<compound type-name='foo_link'/>
<struct-type type-name='foo_link'>
<pointer name='item' type-name='foo'/>
<pointer name='prev' type-name='foo_link'/>
<pointer name='next' type-name='foo_link'/>
</struct-type>
In the context of these XML definitions, class denotes types with virtual methods:
<class-type type-name='name'
[inherits-from='class_type']
[original-name='vtable_name']
...>
...
fields
...
<virtual-methods>
...
vmethods
...
</virtual-methods>
</class-type>
Classes are generally the same as <struct-type>, including support for instance-vector. Unlike
<struct-type> however, they don’t allow is-union='true'.
There may only be one table of virtual methods per class-type. In subclasses it should only contain items added to the
table of the superclass.
Virtual method definitions are placed within the <virtual-methods> section of a class type. No other tag may
be placed within that section, including comment.
A virtual destructor is defined as follows:
<vmethod is-destructor='true'/>
The return type may be specified either as an attribute, or via a ret-type sub-tag. The subtag syntax follows the
abstract container model outlined above. The attribute is exactly equivalent to <ret-type type-name='type'/
> as subtag. If the return type is completely omitted, it is taken to be void.
Ordinary field definition tags within the vmethod tag are treated as method parameters.
If the name attribute is omitted, the vmethod is named randomly and made protected, so that calling it is impossible.
This is the intended way of providing placeholders for completely unknown slots in the vtable.
Global objects are global pointers that are initialized from [Link] at runtime. Therefore, the tag itself is identical
in syntax to <pointer>, except that it doesn’t allow is-array:
<global-object name='id'>
<field.../>
</global-object>
Symbol tables are defined in [Link] and loaded at runtime. They define locations of global objects and virtual
tables.
The definition syntax is as follows:
The name attribute specifies an unique name of the symbol table. os-type specifies the applicable OS type, and must
be one of windows, linux, darwin.
The <md5-hash> tag specifies the MD5 hash that is used to match the executable on Linux and OS/X. It will be
ignored if used in a windows symbol table. Likewise, <binary-timestamp> is valid only for matching EXE files.
A symbol table may contain multiple tags in order to match several executables; this is especially useful with MD5
hashes, which change with patching.
Global object addresses are specified with <global-address> tags. Virtual method table addresses may be pre-
initialized with <vtable-address> tags.
It is allowed to specify addresses for objects and vtables that are otherwise not defined. Obviously, such values can
only be used by directly quering the VersionInfo object in dfhack.
Lisp Integration
This XML file format was designed together with the cl-linux-debug Lisp tool, and has a number of aspects that
closely integrate with its internals.
For instance, when loaded by that tool, all XML tags are converted directly into instances of classes that exactly match
the name of the tag, and when the documentation above mentions expressions, that refers to Lisp expressions within
the context of that library.
Reference expressions
In order to facilitate compact representation for long chains of dereferences that are commonly required when dealing
with the data structures, cl-linux-debug defines a reader macro (i.e. basically a parser plugin) that adds a custom
syntax for them. This syntax is triggered by special characters $ and @.
Expressions written in that syntax expand into nested chains of calls to two generic functions named $ and @, which
implement correspondingly r-value and l-value dereference of their first argument using the second.
Dereference syntax
• $foo[expr], @foo[expr]
These expressions expand to correspondingly ($ foo expr) and (@ foo expr), and are useful for ac-
cessing array elements.
• $[Link][yyy].zzz
When dereference clauses are chained, they expand into nested calls to $ and @, with the outermost depending
on the first character, and all the inner ones being @.
This example expands to: ($ (@ (@ foo '$xxx) yyy) '$zzz).
• @$$[Link], $$$[Link]
When the expression contains multiple initial $ characters, all but the first one are prepended to the initial
variable name.
These examples expand to (@ $$foo '$bar) and ($ $$foo '$bar)
NOTE: Only the $ character may be used in this way; $@@[Link] is invalid.
• $.foo, @$[bar], . . .
If the expression contains no initial identifier, the initial $ sequence is used as one instead (after replacing @
with $ if necessary).
These examples expand to: ($ $ '$foo), (@ $$ bar).
NOTE: Unlike the previous syntax pattern, this one uses all of the initial $ and @ characters.
• $(func arg arg...).bar
If one initial $ or @ is immediately followed by parentheses, the contents of said parentheses are parsed as
ordinary lisp code and used instead of the initial variable.
The example expands to: ($ (func arg arg...) '$bar)
• @$(foo bar baz)
If an initial @ is followed by one or more $ characters and then parentheses, it is parsed as a lambda expression
(anonymous function) with one argument consisting of those $ characters.
This example expands to: (lambda ($) (foo bar baz))
NOTE: it is an error to use multiple initial $ characters without @ like this: $$$(...)...
Basic properties
As described above, dereference is actually implemented by two generic functions, @ and $, which implement l-value
and r-value dereference.
They are defined as such:
Generally, l-value dereference returns an object that can be dereferenced further. R-value dereference with the same
arguments may return the same object as l-value, or a simple scalar value, depending on the context.
Perhaps oppositely to the used terms, only the r-value dereference function may be used as the syntactic target of
assignment; this is because you can’t actually change the (conceptual) address of an object, only its contents; and
l-value dereference returns an address. I.e. in C++ you can write *a = ..., but can’t do &a = ....
Any of the dereference functions may return a list to represent multiple possible values. Array objects often define (@
foo '*) to return all of the elements.
If either the obj or key argument of any of the functions is a list (including NIL as empty list), the functions loop over
the list, and return a concatenation of the resulting return value lists. This allows using $array.*.field to get a
list of all values of a field within array elements.
($ obj t) is defined as the natural value of an object; e.g. if obj is a reference to a numeric field, this will be its
value. By default it is equal to the object itself. ($ obj key) for any other key would fall back to ($ (@ obj
key) t) if no special handler for $ with that key and object was defined.
Reference objects
The cl-linux-debug library represents typed pointers to objects in memory as objects of the
memory-object-ref type.
Along with the expected address and type of the pointer, these objects also retain a history of dereferences that have
led to this particular pointer, and define virtual fields to access this information. This history is similar to what the
Back button in a browser uses.
All references by default have the following properties:
• @[Link]
By default returns ref itself. May be hidden by struct fields and index-enum keys.
• @ref[integer]
Returns a reference to address + size*int, i.e. offsets the pointer.
• @ref.*
Returns a list of contained collection elements. By default empty.
• @ref.@
Returns a list of subfields. By default empty.
• @ref._parent
Returns the previous reference in the “back” chain.
• @ref._global
Returns the nearest reference in the “back” chain that has a globally named type, i.e. one defined by a
struct-type, class-type etc, and not by any nested substructures. This may return the ref itself.
• @ref._upglobal
Exactly equivalent to @ref._parent._global.
• $ref._address
Returns the numeric address embedded in the ref.
• $ref._size
Returns the size of the object pointed to.
• $ref._key
Returns the key that was used to get this ref from the parent. This is not guaranteed to be precisely accurate, but
e.g. for array elements this will be the array index.
• $ref._type
For globally named types, returns their type name.
Primitive types
Enums
Enum fields return their value as symbols, and allow access to attributes:
• $ref[t]
Returns the symbol matching the value, unless there is none. May be assigned both as symbol or number.
• $[Link]
If the enum has an attribute with that name, retrieves its value for the current value of the field.
Pointers
Compounds
• @[Link], @ref._fields.field
Returns a reference to the given field.
• @ref.*, @ref.@
Returns a list of references to all fields. Note that if the object is both an implicit compound and a sequence,
@ref.* will returns the sequence items as described below.
Sequences
• @ref[int]
Returns a reference to the Nth item of the sequence.
• @ref[symbol]
If the sequence has an index-enum, its items can be accessed by symbolic names.
• @ref.*
Returns a list of all items of the sequence.
• @ref._items
Returns the items of the sequence as a special lazy object, intended to optimize some things in the GUI.
• @[Link]-refers-to[int]
If the sequence has the relevant attribute, returns the target for the given index.
• $[Link]
Returns the number of items in the sequence.
• $[Link]-items
Checks if the sequence has any items, and returns T or NIL.
Code helpers
The <code-helper> tag may be used to add lisp code fragments to the objects defined in the xml. The
refers-to, index-refers-to and ref-target tags are also converted to code helpers internally, and you
can use e.g. <code-helper name='refers-to'>...</code-helper> instead of the attribute if your ex-
pression is too long for it.
There are two features that can only be implemented via explicit <code-helper> tags:
• <code-helper name='describe'> ... </code-helper>
This specifies a piece of code that is called to supply additional informational items for the rightmost column of
the table in the GUI tool. The code should return a string, or a list of strings.
As with refers-to, the code receives the value of the object as $, and the reference to the object in $$ (i.e.
$ is equal to $$[t]).
The (describe-obj object) function can be used to call the same describe mechanism on another object,
e.g.:
<code-helper name='describe'> (describe-obj $.name) </code-helper>
This finds an instance of the art_image_chunk type using the aux-value $$, and then returns an element of
its images sub-array using the main value $.
Examples
• @global.*
The global variable ‘global’ contains a special compound that contains all known global objects. This expres-
sions retrieves a list of refs to all of them.
Using $global.* would return values for the primitive ones instead of refs, and is not that useful.
• $[Link][0].id
This expression is syntactically parsed into the following sequence:
tmp = global
tmp = @[Link] ; the world global ref
tmp = @[Link] ; the units field ref
tmp = @[Link] ; the all vector ref
tmp = @tmp[0] ; the first unit object pointer ref
$[Link]
The only non-trivial step here is the last one. The last value of tmp is a reference to a pointer, and as described
above, it delegates anything it does not directly understand to its target, adding an implicit step at runtime:
unit = @tmp._target
$[Link]
A unit object does not define $[Link] directly either, so the final step falls back to:
idref = @[Link]
($ idref t)
which retrieves a reference to the id field, and then evaluates its natural value.
The result is that the expression returns the id value of the first unit in the vector as would be naturally expected.
Using @[Link][0].id would have used @[Link] as the last step, which would
have skipped the ($ idref t) call and returned a reference to the field.
• A simple index-refers-to example:
<compound name='burrows'>
<stl-vector name='list' pointer-type='burrow'/>
<int32_t name='sel_index' refers-to='$$._parent.list[$]'/>
</compound>
This fragment of XML defines a compound with two fields, a vector and an int, which has a refers-to
attribute. When that field is displayed in the GUI, it evaluates the expression in the attribute, giving it the integer
value as $, and a reference to the integer field as $$.
The expression parses as:
Since the only way the GUI could get a reference to the field was to evaluate @ref-to-burrows.
sel_index, that previous reference is stored in its “back” list, and @tmp._parent retrieves it. After that
everything is simple.
• An example of ref-target with aux-value:
The race field just specifies a type as ref-target, so the reference simply evaluates the find-instance
helper of the creature_raw, passing it the race value as $.
In order to find the caste however, you need to first find a creature, which requires a race value. This value is
supplied via the aux-value attribute into the $$ argument to find-instance.
Since the value of the caste field will be passed through to the helper anyway, when evaluating aux-value
the $ argument is set to a reference to the holding field, and $$ is set to its _parent. This means that $$.race
in the context of aux-value is equivalent to $$._parent.race in the context of refers-to.
• A complex example of cross-references between arrays:
<struct-type type-name='caste_raw'>
<compound name='body_info'>
<stl-vector name='body_parts' pointer-type='body_part_raw'/>
</compound>
<compound name='bp_appearance'>
<stl-vector name='modifiers' pointer-type='bp_appearance_modifier'/>
index-refers-to='$$._parent.part_idx[$].refers-to'/>
</compound>
</struct-type>
In order to understand this example it is first necessary to understand that refers-to specified on a vector is
actually transplanted onto the implicitly constructed element tag:
<stl-vector name='part_idx'>
<int16_t refers-to='$$._global.body_info.body_parts[$]'/>
</stl-vector>
Therefore, $$ is a reference to the <int16_t> field, $$._parent is a reference to the vector, $$.
_parent._parent is a reference to the bp_appearance compound, etc.
The $$._global... works as an abbreviation that applies _parent until it reaches a globally defined type,
which in this case is the current instance of the caste_raw struct.
NOTE: $$._global._global is the same as $$._global, i.e. repeated _global is a no-op. The latest
version supports _upglobal, which is equivalent to _parent._global.
Thus, the refers-to link on the part_idx vector evaluates to the element of the body_parts vector,
indexed by the value of the current part_idx vector item.
Likewise, the refers-to link on the modifier_idx vector goes back to the bp_appearance compound,
and descends into the modifiers vector, using the value of the current item.
The index-refers-to link on the same modifier_idx vector highlights the shared indexing relation be-
tween the bottom vectors by linking to the part_idx vector via the current item index. Since this attribute is hosted
by the vector itself, $$ points at the vector, and only one _parent is needed to reach bp_appearance.
This link also demonstrates how the defined relations can be reused in other expressions by accessing the tar-
get of the refers-to link inside part_idx. When the part_idx vector is accessed simply as $xxx.
part_idx[foo], it evaluates as:
tmp = @xxx.part_idx
tmp = @tmp[foo]
($ tmp t)
thus returning just an integer value. However, if an additional dereference step is added, it turns to:
tmp = @xxx.part_idx
tmp = @tmp[foo]
obj = @[Link]-to
($ obj t)
refers-to='$$._parent._parent.part_idx[$$._key].[Link][$]'
Note how this link has to use two _parent steps again due to being attached to the element of the vector
instead of the vector itself. It also has to use the _key attribute of the vector element to retrieve the current
index in the vector, because here $ holds the element value.
Contents
• General Process
• Running Dwarf Fortress
• Available Scripts
• STAGE 1. Linux compound globals
• STAGE 2. Old way to find Linux compound globals
• STAGE 3. Linux primitive globals
• STAGE 4. Primary windows compound globals
• STAGE 5. Secondary windows compound globals
• STAGE 6. Windows primitive globals
General Process
Download the new versions. The scripts expect the following directory layout:
~userhome/
Games/
DF/
df_linux/ - Current DF for linux
df_windows/ - Current DF for windows
df_osx/ - Current DF for osx
• Use “[Link] v0.??.??” to automatically perform a number of steps. If you get a mismatch error from
[Link], see “STAGE 1”.
• Start the linux DF version, and launch the tool.
• Execute (reset-state-annotation)
• Commit.
• Use the tool to verify that the layout of the compound globals on linux is correct, and update xml as necessary.
Check that unit seems reasonable, etc. Compare the changes in g_src between releases. Delete redundant entries
for some linux & osx globals in [Link].
• Compile DFHack without plugins for windows and run devel/find-offsets to find globals there.
• With the windows version in wine, run (check-struct-sizes) to see if any objects changed their size. If nothing is
obviously wrong, use (check-struct-sizes :annotate? t) to mark correctly sized objects ALIGNED.
• Check the rest of the document for info on finding still missing globals.
• Commit.
• Run [Link] to update CSV files and verify vtable size and argument counts.
• Commit.
The lisp tool expects that the game is started in a mode where all allocated memory is automatically filled with a
certain byte value.
MALLOC_PERTURB_=45 ./df
Available Scripts
[Link]
[Link]
Runs ruby and perl scripts to extract data from the executables, and writes the output to txt files in subdirectories.
[Link]
Uses the lisp tool and some scripts to produce csv files with offsets for linux and windows. These are useful for manual
lookup and some scripts.
[Link]
Starts the lisp tool. You may pass the process ID as a parameter to avoid the prompt.
[Link]
Used by make-scans to extract the keybinding enum from g_src in form of [Link]
[Link]
Used by make-scans to compare the extracted addresses of the compound linux/osx globals with a saved copy from a
previous version and thus determine their names.
[Link]
Used by [Link] to produce a file listing the addresses of all virtual methods in a compact form. Relies on csv
files and data from [Link]
look at values in bss, there will be cur_year_tick, and cur_year is 32 bytes before that.
2. process_jobs
Designate a building for construction. Look after process_dig for an enabled boolean.
3. process_dig
Step the game one step. Designate a tile for digging. Look after cur_year and before process_jobs.
Note: this order because designating sometimes sets process_jobs too.
4. job_next_id / ui_workshop_job_cursor
Find a workshop without jobs; (find-changes); add job; Enter; add job; +; add job; +; done Finds job_next_id
and ui_workshop_job_cursor, the distinction is obvious.
The ui_workshop_job_cursor is expected to be after cur_year_tick.
5. ui_workshop_in_add, ui_building_in_resize, ui_building_in_assign
Expected to be in the area after ui_workshop_job_cursor, in this order. Change the relevant state in game and
F5.
6. ui_building_item_cursor
Find a cluttered workshop, t; (find-changes); move cursor down; Enter; cursor down; +; cursor down; +; done
Expected to be right after ui_workshop_job_cursor.
7. current_weather
Subtract 0x1c from cur_year address. Obviously, a big hack.
It is best to use a save where the contents are non-zero and known to you.
1. announcements
Immediately follows d_init; starts 25 25 31 31 24 . . .
1. world
Set a nickname, search for it; the unit will have it at offset 0x1C. Then trace back to the unit vector, and subtract its
offset.
2. ui
Open the ‘s’quad sidebar page. Navigate to a squad in [Link], then backtrace and subtract the offset of
[Link].
3. ui_build_selector
Start creating a building, up to the point of material selection. Find the material item through world and backtrack
references until .bss.
4. ui_sidebar_menus
Select a unit in ‘v’, open inventory page, backtrack from unit_inventory_item, subtract offset of unit.inv_items.
5. ui_look_list
Put a ‘k’ cursor over a unit, backtrack to a 0x10 bytes object with pointer at offset 0xC, then to the global vector.
6. ui_advmode
In adventure mode, open the ‘c’ompanions menu, then backtrack from [Link][0] (i.e. the player) via
ui_advmode.[Link]
Alternatively, look before ui_look_list for “0, 15” coming from the string.
7. enabler
(find-changes), resize the window, enter; resize width by +1 char, +; repeat until few candidates left; then done, select
the renderer heap object and backtrack to [Link].
Alternatively, look before ui for clocks changing every frame.
8. map_renderer
Put a ‘v’ cursor exactly above a unit; backtrack from the unit object.
Alternatively, look before ui_advmode for the unit pointer list.
9. texture
Load the game with [GRAPHICS:YES] in [Link], and example set. Then search for string “example/[Link]”
and backtrack.
Alternatively, look between ui_build_selector and init.
These are too difficult to find by backtracking or search, so try looking in the expected area first:
1. timed_events
2. ui_building_assign_*
2a. ui_building_assign_is_marked
Assign to zone, (find-changes), toggle 1st unit, enter; toggle 1st, 0; toggle 1st, 1; toggle 2nd, new; done
The vector is expected to be just before ui.
2b. ui_building_assign_items
Expected to be immediately before ui_building_assign_is_marked.
2c. ui_building_assign_units
Start assigning units to a pasture, backtrack from one of the units.
The vector is expected to be immediately before world.
2d. ui_building_assign_type
3. gview
4. Init files
4a. d_init
Follows world after a small gap (starts with flagarray).
4b. init
Follows ui_build_selector after a small gap.
5. gps
6. created_item_*
6a. created_item_type
Expected to be at around -0x40 before world.
6b. created_item_subtype
The first vector immediately after ui_look_list.
6c. created_item_mattype
Immediately before ui_sidebar_menus.
6d. created_item_matindex
Before ui, after timed_events.
6e. created_item_count
Immediately before timed_events.
[D] crime_next_id
Followed by, in this order (but with some gaps):
• ui_workshop_job_cursor
• current_weather (immediately after ui_workshop_job_cursor)
• process_dig
• process_jobs
• ui_building_in_resize
• ui_building_in_assign
• pause_state
[E] Random positions.
1. cur_year_tick
Look immediately before artifact_next_id.
2. window_z
Look before proj_next_id.
3. ui_selected_unit
Look just after squad_next_id.
4. ui_unit_view_mode
Look just before hist_event_collection_next_id.
5. announcements
Immediately follows d_init; starts 25 25 31 31 24 . . .
There are a variety of tools that can be used to analyze DF memory - some are listed here. Note that some of these
may be old and unmaintained. If you aren’t sure what tool would be best for your purposes, feel free to ask for advice
(on IRC, Bay12, etc.).
Contents
• Cross-platform tools
– Ghidra
– IDA Freeware 7.0
– Hopper
– DFHack tools
* Plugins
* Scripts
* Sizecheck
* Legacy tools
• Linux-specific tools
– GDB
– Other analysis tools
– df-structures GUI
– EDB (Evan’s debugger)
• Windows-specific tools
Ghidra
Available from Hex-Rays. Supports analyzing both 32-bit and 64-bit executables for all supported DF platforms.
Some .idc scripts for IDA are available in the df_misc repo.
Hopper
Runs on macOS and some Linux distributions; available from [Link] TWBT uses this to
produce some patches.
DFHack tools
Plugins
There are a few development plugins useful for low-level memory research. They are not built by default, but can be
built by setting the BUILD_DEVEL CMake option. These include:
• check-structures-sanity, which performs sanity checks on the given DF object. Note that this will
crash in several cases, some intentional, so using this with GDB is recommended.
• memview, which produces a hex dump of a given memory range. It also highlights valid pointers, and can be
configured to work with Sizecheck to auto-detect object sizes.
• vectors, which can identify instances of std::vector in a given memory range.
Scripts
Several development scripts can be useful for memory research. These include (but are not limited to):
• devel/dump-offsets
• devel/find-offsets
• devel/lsmem
• devel/sc (requires Sizecheck)
• devel/visualize-structure
• Generally, any script starting with devel/find
Sizecheck
Sizecheck is a custom tool that hooks into the memory allocator and inserts a header indicating the size of every object.
The corresponding logic to check for this header when freeing memory usually works, but is inherently not foolproof.
You should not count on DF being stable when using this.
DFHack’s implementation of sizecheck is currently only tested on Linux, although it probably also works on macOS.
It can be built with the BUILD_SIZECHECK CMake option, which produces a libsizecheck library installed in
the hack folder. On Linux, passing --sc as the first argument to the dfhack launcher script will load this library on
startup. On other platforms, or when passing a different argument to the launcher (such as for GDB), you will need to
preload this library manually, by setting PRELOAD_LIB on Linux (or LD_PRELOAD if editing the dfhack launcher
script directly), or by editing the dfhack launcher script and adding the library to DYLD_INSERT_LIBRARIES on
macOS.
There is also an older sizecheck implementation by Mifki available on GitHub ([Link] is the main sizecheck library,
and win_patch.cpp is used for Windows support). To use this with other DFHack tools, you will likely need to
edit the header’s magic number to match what is used in devel/sc (search for a hexadecimal constant starting with 0x).
Legacy tools
Some very old DFHack tools are available in the legacy branch on GitHub. No attempt is made to support these.
GDB
GDB is technically cross-platform, but tends to work best on Linux, and DFHack currently only offers support for
using GDB on 64-bit Linux. To start with GDB, pass -g to the DFHack launcher script:
./dfhack -g
The dfhack launcher script on Linux has support for launching several other tools alongside DFHack, including
Valgrind (as well as Callgrind and Helgrind) and strace. See the script for the exact command-line option to specify.
Note that currently only one tool at a time is supported, and must be specified with the first argument to the script.
df-structures GUI
This is a tool written by Angavrilov and available on GitHub. It only supports 32-bit DF. Some assistance may be
available on IRC.
Available on GitHub.
Some people have used Cheat Engine for research in the past.
Writing scripts and plugins for DFHack is not the only way to modify Dwarf Fortress. Before DFHack, it was common
for tools to manually patch the binary to change behaviour, and DFHack still contains tools to do this via the binpatch
command.
Warning: We recommend using a script or plugin instead of a raw patch if at all possible - that way your work
will work for many versions across multiple operating systems.
Contents
• Getting a patch
• Using a patch
– Patching at runtime
– Patching on disk
• Tools reliant on binpatches
– fix-armory
– gui/assign-rack
There are no binary patches available for Dwarf Fortress versions after 0.34.11.
This system is kept for the chance that someone will find it useful, so some hints on how to write your own follow.
This will require disassembly and decent skill in memory research.
• The patches are expected to be encoded in text format used by IDA.
• See the patches folder in commit b0e1b51 for examples.
• Issue 546 is about the future of the binpatches, and may be useful reading.
If you want to write a patch, the armory patches discussed here and documented below would probably be the best
place to start.
Patching at runtime
The binpatch script checks, applies or removes binary patches directly in memory at runtime:
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.
This is the preferred method; it’s easier to debug, does not cause persistent problems, and leaves file checksums alone.
As with many other commands, users can simply add it to dfhack*.init to reapply the patch every time DF is run.
Patching on disk
Warning: This method of patching is deprecated, and may be removed without notice. You should use the
runtime patching option above.
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 [Link]" [Link] Checks and prints if the patch is currently ap-
plied.
binpatch apply "Dwarf [Link]" [Link] Applies the patch, unless it is already applied or
in conflict.
binpatch remove "Dwarf [Link]" [Link] Removes the patch, unless it is already re-
moved.
If you use a permanent patch under OSX or Linux, you must update [Link] with the new checksum of the
executable. Find the relevant section, and add a new line:
<md5-hash value='????????????????????????????????'/>
In order to find the correct value of the hash, look into [Link]; DFHack prints an error there if it does not recognize
the hash.
Some DFHack tools require the game to be patched to work. As no patches are currently available, the full description
of each is included here.
fix-armory
Note: In order to actually be used, weapon racks have to be patched and manually assigned to a squad. See gui/assign-
rack.
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.
gui/assign-rack
Bind to a key (the example config uses P), and activate when viewing a weapon rack in the q mode.
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 has not been updated since 0.34.11. See Bug 1445 for more info.
• Haulers still take equipment stored in the armory away to the stockpiles, unless fix-armory 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.
The 'create-items' script spawns items under the cursor, facilitating the initial setup of a fortress by providing resources like boulders, plants, and bars. It allows specifying item categories and materials, defaulting to creating 20 items unless otherwise specified. However, it does not enforce realistic combinations, permitting creation of unusual items like boulders of toad blood. The list mode provides a selection of 'normal' materials, highlighting its limitation in guiding realistic setups .
The Lua API's handling of struct references in DFHack is significant as it provides controlled access to game objects' data fields, allowing scripting to modify or interact with game mechanics directly. Access to fields via ref.field and complex objects via lua tables enables sophisticated script development, supporting in-game automation or enhancements, and fostering robust interaction with the game's internal data structures .
DFHack mitigates programming pitfalls like null pointer access by detecting them. However, risks remain, akin to C++ pointer dangers, such as dangling pointers after deletions, which can lead to undefined behavior if accessed. Developers must carefully manage memory, utilizing DFHack's type-safe methods while being vigilant of the API’s limitations, to avoid game crashes and ensure stability .
The 'fix-ster' script is used to manage animal populations by fixing infertility in creatures that should not breed or undoing sterility in desired breeding candidates. Using arguments like 'fert' or 'ster', alongside target specifications, users can precisely control reproductive capabilities of animals, thereby affecting population dynamics and resource management within the game. This precision is crucial for maintaining ecological balance and optimizing fortress resources .
Integration of DFHack into the game's structure facilitates development by enabling modifications through plugins and scripts, which can enhance usability or functionality. It's significant for development as it allows building new features or adjusting existing ones without altering the core game code directly. Moreover, updates to plugins or scripts require careful synchronization with DFHack's API changes or internal updates to maintain compatibility and leverage new functionalities effectively .
The 'tame' script impacts animal training levels by allowing specification of taming levels from 0 (semi-wild) to 7 (tame). By using arguments like -read or -set <level>, operators can manage the domestication status of animals, influencing their utility and behavior within the game. This script enables efficient control over wildlife integration into the player's fortress operations .
The 'deep-embark' script modifies traditional game starts by relocating starting units and equipment to an underground region upon embarking. This alters gameplay by challenging players to adapt to subterranean conditions from the outset, adding complexity and necessitating new strategies for survival and expansion. It is particularly useful for modders aiming to create unique scenarios by default .
The 'stripcaged' script aids inventory management by marking items inside cages for dumping, which a dwarf can perform or automate via the autodump feature. Capabilities include dumping specific types of items like weapons or armor, either globally across all cages or selectively using cage IDs or through an in-game cursor selection, offering nuanced control over resources and inventory organization .
The 'combat-harden' script sets the combat-hardened value on units, affecting their sensitivity to seeing corpses. It requires specifying a target (such as all units, citizens, or a specific unit by ID) and a value or tier of hardenedness. Values range from 0 to 100, with higher values indicating more resilience, while tier options from 1 to 4 adjust psychological resilience from 'no hardenedness' to 'doesn't care about anything anymore'. This allows for customization of units' emotional responses in-game .
Using the 'feature' script involves enabling management of map features which includes discovering magma features to allow construction of magma workshops and furnaces, or discovering cavern layers to enable vegetation growth within the fortress. Key considerations include deciding whether to list, show, or hide map features as discovered, which affects gameplay by altering the availability of resources. This requires strategic planning to harness the environment effectively .