diff options
137 files changed, 18280 insertions, 2661 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt index f77a6c3b..dfb13cd5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -111,6 +111,9 @@ IF(UNIX) SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-g -Wall -Wno-unused-variable") SET(CMAKE_CXX_FLAGS "-fvisibility=hidden -m32 -march=i686 -mtune=generic -std=c++0x") SET(CMAKE_C_FLAGS "-fvisibility=hidden -m32 -march=i686 -mtune=generic") +ELSEIF(MSVC) + # for msvc, tell it to always use 8-byte pointers to member functions to avoid confusion + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /vmg /vmm") ENDIF() # use shared libraries for protobuf diff --git a/LUA_API.rst b/LUA_API.rst index 2bb2c949..f532d221 100644 --- a/LUA_API.rst +++ b/LUA_API.rst @@ -488,7 +488,7 @@ Input & Output lock. Using an explicit ``dfhack.with_suspend`` will prevent this, forcing the function to block on input with lock held. -* ``dfhack.interpreter([prompt[,env[,history_filename]]])`` +* ``dfhack.interpreter([prompt[,history_filename[,env]]])`` Starts an interactive lua interpreter, using the specified prompt string, global environment and command-line history file. @@ -550,6 +550,20 @@ Exception handling The default value of the ``verbose`` argument of ``err:tostring()``. +Miscellaneous +------------- + +* ``dfhack.VERSION`` + + DFHack version string constant. + +* ``dfhack.curry(func,args...)``, or ``curry(func,args...)`` + + Returns a closure that invokes the function with args combined + both from the curry call and the closure call itself. I.e. + ``curry(func,a,b)(c,d)`` equals ``func(a,b,c,d)``. + + Locking and finalization ------------------------ @@ -709,6 +723,10 @@ can be omitted. Returns the dfhack directory path, i.e. ``".../df/hack/"``. +* ``dfhack.getTickCount()`` + + Returns the tick count in ms, exactly as DF ui uses. + * ``dfhack.isWorldLoaded()`` Checks if the world is loaded. @@ -724,15 +742,20 @@ can be omitted. Gui module ---------- -* ``dfhack.gui.getCurViewscreen()`` +* ``dfhack.gui.getCurViewscreen([skip_dismissed])`` - Returns the viewscreen that is current in the core. + Returns the topmost viewscreen. If ``skip_dismissed`` is *true*, + ignores screens already marked to be removed. * ``dfhack.gui.getFocusString(viewscreen)`` Returns a string representation of the current focus position in the ui. The string has a "screen/foo/bar/baz..." format. +* ``dfhack.gui.getCurFocus([skip_dismissed])`` + + Returns the focus string of the current viewscreen. + * ``dfhack.gui.getSelectedWorkshopJob([silent])`` When a job is selected in *'q'* mode, returns the job, else @@ -754,15 +777,29 @@ Gui module last case, the highlighted *contained item* is returned, not the container itself. +* ``dfhack.gui.getSelectedBuilding([silent])`` + + Returns the building selected via *'q'*, *'t'*, *'k'* or *'i'*. + * ``dfhack.gui.showAnnouncement(text,color[,is_bright])`` Adds a regular announcement with given text, color, and brightness. The is_bright boolean actually seems to invert the brightness. +* ``dfhack.gui.showZoomAnnouncement(type,pos,text,color[,is_bright])`` + + Like above, but also specifies a position you can zoom to from the announcement menu. + * ``dfhack.gui.showPopupAnnouncement(text,color[,is_bright])`` Pops up a titan-style modal announcement window. +* ``dfhack.gui.showAutoAnnouncement(type,pos,text,color[,is_bright])`` + + Uses the type to look up options from announcements.txt, and calls the + above operations accordingly. If enabled, pauses and zooms to position. + + Job module ---------- @@ -835,6 +872,26 @@ Units module Returns the nemesis record of the unit if it has one, or *nil*. +* ``dfhack.units.isHidingCurse(unit)`` + + Checks if the unit hides improved attributes from its curse. + +* ``dfhack.units.getPhysicalAttrValue(unit, attr_type)`` +* ``dfhack.units.getMentalAttrValue(unit, attr_type)`` + + Computes the effective attribute value, including curse effect. + +* ``dfhack.units.isCrazed(unit)`` +* ``dfhack.units.isOpposedToLife(unit)`` +* ``dfhack.units.hasExtravision(unit)`` +* ``dfhack.units.isBloodsucker(unit)`` + + Simple checks of caste attributes that can be modified by curses. + +* ``dfhack.units.getMiscTrait(unit, type[, create])`` + + Finds (or creates if requested) a misc trait object with the given id. + * ``dfhack.units.isDead(unit)`` The unit is completely dead and passive, or a ghost. @@ -861,6 +918,14 @@ Units module Returns the age of the unit in years as a floating-point value. If ``true_age`` is true, ignores false identities. +* ``dfhack.units.getEffectiveSkill(unit, skill)`` + + Computes the effective rating for the given skill, taking into account exhaustion, pain etc. + +* ``dfhack.units.computeMovementSpeed(unit)`` + + Computes number of frames * 100 it takes the unit to move in its current state of mind and body. + * ``dfhack.units.getNoblePositions(unit)`` Returns a list of tables describing noble position assignments, or *nil*. @@ -875,6 +940,15 @@ Units module Retrieves the profession name for the given race/caste using raws. +* ``dfhack.units.getProfessionColor(unit[,ignore_noble])`` + + Retrieves the color associated with the profession, using noble assignments + or raws. The ``ignore_noble`` boolean disables the use of noble positions. + +* ``dfhack.units.getCasteProfessionColor(race,caste,prof_id)`` + + Retrieves the profession color for the given race/caste using raws. + Items module ------------ @@ -929,6 +1003,14 @@ Items module Move the item to the unit inventory. Returns *false* if impossible. +* ``dfhack.items.remove(item[, no_uncat])`` + + Removes the item, and marks it for garbage collection unless ``no_uncat`` is true. + +* ``dfhack.items.makeProjectile(item)`` + + Turns the item into a projectile, and returns the new object, or *nil* if impossible. + Maps module ----------- @@ -945,10 +1027,18 @@ Maps module Returns a map block object for given x,y,z in local block coordinates. +* ``dfhack.maps.isValidTilePos(coords)``, or isValidTilePos(x,y,z)`` + + Checks if the given df::coord or x,y,z in local tile coordinates are valid. + * ``dfhack.maps.getTileBlock(coords)``, or ``getTileBlock(x,y,z)`` Returns a map block object for given df::coord or x,y,z in local tile coordinates. +* ``dfhack.maps.ensureTileBlock(coords)``, or ``ensureTileBlock(x,y,z)`` + + Like ``getTileBlock``, but if the block is not allocated, try creating it. + * ``dfhack.maps.getRegionBiome(region_coord2d)``, or ``getRegionBiome(x,y)`` Returns the biome info struct for the given global map region. @@ -957,6 +1047,11 @@ Maps module Enables updates for liquid flow or temperature, unless already active. +* ``dfhack.maps.spawnFlow(pos,type,mat_type,mat_index,dimension)`` + + Spawns a new flow (i.e. steam/mist/dust/etc) at the given pos, and with + the given parameters. Returns it, or *nil* if unsuccessful. + * ``dfhack.maps.getGlobalInitFeature(index)`` Returns the global feature object with the given index. @@ -1027,6 +1122,11 @@ Burrows module Buildings module ---------------- +* ``dfhack.buildings.setOwner(item,unit)`` + + Replaces the owner of the building. If unit is *nil*, removes ownership. + Returns *false* in case of error. + * ``dfhack.buildings.getSize(building)`` Returns *width, height, centerx, centery*. @@ -1204,6 +1304,178 @@ Constructions module Returns *true, was_only_planned* if removed; or *false* if none found. +Screen API +---------- + +The screen module implements support for drawing to the tiled screen of the game. +Note that drawing only has any effect when done from callbacks, so it can only +be feasibly used in the core context. + +Basic painting functions: + +* ``dfhack.screen.getWindowSize()`` + + Returns *width, height* of the screen. + +* ``dfhack.screen.getMousePos()`` + + Returns *x,y* of the tile the mouse is over. + +* ``dfhack.screen.inGraphicsMode()`` + + Checks if [GRAPHICS:YES] was specified in init. + +* ``dfhack.screen.paintTile(pen,x,y[,char,tile])`` + + Paints a tile using given parameters. Pen is a table with following possible fields: + + ``ch`` + Provides the ordinary tile character, as either a 1-character string or a number. + Can be overridden with the ``char`` function parameter. + ``fg`` + Foreground color for the ordinary tile. Defaults to COLOR_GREY (7). + ``bg`` + Background color for the ordinary tile. Defaults to COLOR_BLACK (0). + ``bold`` + Bright/bold text flag. If *nil*, computed based on (fg & 8); fg is masked to 3 bits. + Otherwise should be *true/false*. + ``tile`` + Graphical tile id. Ignored unless [GRAPHICS:YES] was in init.txt. + ``tile_color = true`` + Specifies that the tile should be shaded with *fg/bg*. + ``tile_fg, tile_bg`` + If specified, overrides *tile_color* and supplies shading colors directly. + + Returns *false* if coordinates out of bounds, or other error. + +* ``dfhack.screen.readTile(x,y)`` + + Retrieves the contents of the specified tile from the screen buffers. + Returns a pen, or *nil* if invalid or TrueType. + +* ``dfhack.screen.paintString(pen,x,y,text)`` + + Paints the string starting at *x,y*. Uses the string characters + in sequence to override the ``ch`` field of pen. + + Returns *true* if painting at least one character succeeded. + +* ``dfhack.screen.fillRect(pen,x1,y1,x2,y2)`` + + Fills the rectangle specified by the coordinates with the given pen. + Returns *true* if painting at least one character succeeded. + +* ``dfhack.screen.findGraphicsTile(pagename,x,y)`` + + Finds a tile from a graphics set (i.e. the raws used for creatures), + if in graphics mode and loaded. + + Returns: *tile, tile_grayscale*, or *nil* if not found. + The values can then be used for the *tile* field of *pen* structures. + +* ``dfhack.screen.clear()`` + + Fills the screen with blank background. + +* ``dfhack.screen.invalidate()`` + + Requests repaint of the screen by setting a flag. Unlike other + functions in this section, this may be used at any time. + +In order to actually be able to paint to the screen, it is necessary +to create and register a viewscreen (basically a modal dialog) with +the game. + +**NOTE**: As a matter of policy, in order to avoid user confusion, all +interface screens added by dfhack should bear the "DFHack" signature. + +Screens are managed with the following functions: + +* ``dfhack.screen.show(screen[,below])`` + + Displays the given screen, possibly placing it below a different one. + The screen must not be already shown. Returns *true* if success. + +* ``dfhack.screen.dismiss(screen[,to_first])`` + + Marks the screen to be removed when the game enters its event loop. + If ``to_first`` is *true*, all screens up to the first one will be deleted. + +* ``dfhack.screen.isDismissed(screen)`` + + Checks if the screen is already marked for removal. + +Apart from a native viewscreen object, these functions accept a table +as a screen. In this case, ``show`` creates a new native viewscreen +that delegates all processing to methods stored in that table. + +**NOTE**: Lua-implemented screens are only supported in the core context. + +Supported callbacks and fields are: + +* ``screen._native`` + + Initialized by ``show`` with a reference to the backing viewscreen + object, and removed again when the object is deleted. + +* ``function screen:onShow()`` + + Called by ``dfhack.screen.show`` if successful. + +* ``function screen:onDismiss()`` + + Called by ``dfhack.screen.dismiss`` if successful. + +* ``function screen:onDestroy()`` + + Called from the destructor when the viewscreen is deleted. + +* ``function screen:onResize(w, h)`` + + Called before ``onRender`` or ``onIdle`` when the window size has changed. + +* ``function screen:onRender()`` + + Called when the viewscreen should paint itself. This is the only context + where the above painting functions work correctly. + + If omitted, the screen is cleared; otherwise it should do that itself. + In order to make a see-through dialog, call ``self._native.parent:render()``. + +* ``function screen:onIdle()`` + + Called every frame when the screen is on top of the stack. + +* ``function screen:onHelp()`` + + Called when the help keybinding is activated (usually '?'). + +* ``function screen:onInput(keys)`` + + Called when keyboard or mouse events are available. + If any keys are pressed, the keys argument is a table mapping them to *true*. + Note that this refers to logical keybingings computed from real keys via + options; if multiple interpretations exist, the table will contain multiple keys. + + The table also may contain special keys: + + ``_STRING`` + Maps to an integer in range 0-255. Duplicates a separate "STRING_A???" code for convenience. + + ``_MOUSE_L, _MOUSE_R`` + If the left or right mouse button is pressed. + + If this method is omitted, the screen is dismissed on receival of the ``LEAVESCREEN`` key. + +* ``function screen:onGetSelectedUnit()`` +* ``function screen:onGetSelectedItem()`` +* ``function screen:onGetSelectedJob()`` +* ``function screen:onGetSelectedBuilding()`` + + Implement these to provide a return value for the matching + ``dfhack.gui.getSelected...`` function. + + Internal API ------------ @@ -1235,6 +1507,12 @@ and are only documented here for completeness: Returns a sequence of tables describing virtual memory ranges of the process. +* ``dfhack.internal.patchMemory(dest,src,count)`` + + Like memmove below, but works even if dest is read-only memory, e.g. code. + If destination overlaps a completely invalid memory region, or another error + occurs, returns false. + * ``dfhack.internal.memmove(dest,src,count)`` Wraps the standard memmove function. Accepts both numbers and refs as pointers. @@ -1296,8 +1574,8 @@ Core context specific functions: Event type ---------- -An event is just a lua table with a predefined metatable that -contains a __call metamethod. When it is invoked, it loops +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. @@ -1312,10 +1590,18 @@ Features: * ``event[key] = function`` - Sets the function as one of the listeners. + Sets the function as one of the listeners. Assign *nil* to remove it. **NOTE**: The ``df.NULL`` key is reserved for the use by - the C++ owner of the event, and has some special semantics. + 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...)`` @@ -1545,6 +1831,86 @@ function: argument specifies the indentation step size in spaces. For the other arguments see the original documentation link above. +class +===== + +Implements a trivial single-inheritance class system. + +* ``Foo = defclass(Foo[, ParentClass])`` + + Defines or updates class Foo. The ``Foo = defclass(Foo)`` syntax + is needed so that when the module or script is reloaded, the + class identity will be preserved through the preservation of + global variable values. + + The ``defclass`` function is defined as a stub in the global + namespace, and using it will auto-load the class module. + +* ``Class.super`` + + This class field is set by defclass to the parent class, and + allows a readable ``Class.super.method(self, ...)`` syntax for + calling superclass methods. + +* ``Class.ATTRS { foo = xxx, bar = yyy }`` + + Declares certain instance fields to be attributes, i.e. auto-initialized + from fields in the table used as the constructor argument. If omitted, + they are initialized with the default values specified in this declaration. + + If the default value should be *nil*, use ``ATTRS { foo = DEFAULT_NIL }``. + +* ``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`` method is called via ``invoke_before`` (see below) + with the table used as argument to the class. This method is intended + for validating and tweaking that argument table. + 3. Declared ATTRS are initialized from the argument table or their default values. + 4. The ``init`` method is called via ``invoke_after`` with the argument table. + This is the main constructor method. + 5. The ``postinit`` method is 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:invoke_before(method_name, args...)`` + + Navigates the inheritance chain of the instance starting from the most specific + class, and invokes the specified method with the arguments if it is defined in + that specific class. Equivalent to the following definition in every class:: + + function Class:invoke_before(method, ...) + if rawget(Class, method) then + rawget(Class, method)(self, ...) + end + Class.super.invoke_before(method, ...) + end + +* ``instance:invoke_after(method_name, args...)`` + + Like invoke_before, only the method is called after the recursive call to super, + i.e. invocations happen in the parent to child order. + + These two methods are inspired by the Common Lisp before and after methods, and + are intended for implementing similar protocols for certain things. The class + library itself uses them for constructors. + +To avoid confusion, these methods cannot be redefined. + ======= Plugins diff --git a/Lua API.html b/Lua API.html index 2c9a6a8d..36be1ba4 100644 --- a/Lua API.html +++ b/Lua API.html @@ -3,7 +3,7 @@ <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> -<meta name="generator" content="Docutils 0.9: http://docutils.sourceforge.net/" /> +<meta name="generator" content="Docutils 0.8.1: http://docutils.sourceforge.net/" /> <title>DFHack Lua API</title> <style type="text/css"> @@ -337,41 +337,44 @@ ul.auto-toc { <li><a class="reference internal" href="#native-utilities" id="id11">Native utilities</a><ul> <li><a class="reference internal" href="#input-output" id="id12">Input & Output</a></li> <li><a class="reference internal" href="#exception-handling" id="id13">Exception handling</a></li> -<li><a class="reference internal" href="#locking-and-finalization" id="id14">Locking and finalization</a></li> -<li><a class="reference internal" href="#persistent-configuration-storage" id="id15">Persistent configuration storage</a></li> -<li><a class="reference internal" href="#material-info-lookup" id="id16">Material info lookup</a></li> +<li><a class="reference internal" href="#miscellaneous" id="id14">Miscellaneous</a></li> +<li><a class="reference internal" href="#locking-and-finalization" id="id15">Locking and finalization</a></li> +<li><a class="reference internal" href="#persistent-configuration-storage" id="id16">Persistent configuration storage</a></li> +<li><a class="reference internal" href="#material-info-lookup" id="id17">Material info lookup</a></li> </ul> </li> -<li><a class="reference internal" href="#c-function-wrappers" id="id17">C++ function wrappers</a><ul> -<li><a class="reference internal" href="#gui-module" id="id18">Gui module</a></li> -<li><a class="reference internal" href="#job-module" id="id19">Job module</a></li> -<li><a class="reference internal" href="#units-module" id="id20">Units module</a></li> -<li><a class="reference internal" href="#items-module" id="id21">Items module</a></li> -<li><a class="reference internal" href="#maps-module" id="id22">Maps module</a></li> -<li><a class="reference internal" href="#burrows-module" id="id23">Burrows module</a></li> -<li><a class="reference internal" href="#buildings-module" id="id24">Buildings module</a></li> -<li><a class="reference internal" href="#constructions-module" id="id25">Constructions module</a></li> -<li><a class="reference internal" href="#internal-api" id="id26">Internal API</a></li> +<li><a class="reference internal" href="#c-function-wrappers" id="id18">C++ function wrappers</a><ul> +<li><a class="reference internal" href="#gui-module" id="id19">Gui module</a></li> +<li><a class="reference internal" href="#job-module" id="id20">Job module</a></li> +<li><a class="reference internal" href="#units-module" id="id21">Units module</a></li> +<li><a class="reference internal" href="#items-module" id="id22">Items module</a></li> +<li><a class="reference internal" href="#maps-module" id="id23">Maps module</a></li> +<li><a class="reference internal" href="#burrows-module" id="id24">Burrows module</a></li> +<li><a class="reference internal" href="#buildings-module" id="id25">Buildings module</a></li> +<li><a class="reference internal" href="#constructions-module" id="id26">Constructions module</a></li> +<li><a class="reference internal" href="#screen-api" id="id27">Screen API</a></li> +<li><a class="reference internal" href="#internal-api" id="id28">Internal API</a></li> </ul> </li> -<li><a class="reference internal" href="#core-interpreter-context" id="id27">Core interpreter context</a><ul> -<li><a class="reference internal" href="#event-type" id="id28">Event type</a></li> +<li><a class="reference internal" href="#core-interpreter-context" id="id29">Core interpreter context</a><ul> +<li><a class="reference internal" href="#event-type" id="id30">Event type</a></li> </ul> </li> </ul> </li> -<li><a class="reference internal" href="#lua-modules" id="id29">Lua Modules</a><ul> -<li><a class="reference internal" href="#global-environment" id="id30">Global environment</a></li> -<li><a class="reference internal" href="#utils" id="id31">utils</a></li> -<li><a class="reference internal" href="#dumper" id="id32">dumper</a></li> +<li><a class="reference internal" href="#lua-modules" id="id31">Lua Modules</a><ul> +<li><a class="reference internal" href="#global-environment" id="id32">Global environment</a></li> +<li><a class="reference internal" href="#utils" id="id33">utils</a></li> +<li><a class="reference internal" href="#dumper" id="id34">dumper</a></li> +<li><a class="reference internal" href="#class" id="id35">class</a></li> </ul> </li> -<li><a class="reference internal" href="#plugins" id="id33">Plugins</a><ul> -<li><a class="reference internal" href="#burrows" id="id34">burrows</a></li> -<li><a class="reference internal" href="#sort" id="id35">sort</a></li> +<li><a class="reference internal" href="#plugins" id="id36">Plugins</a><ul> +<li><a class="reference internal" href="#burrows" id="id37">burrows</a></li> +<li><a class="reference internal" href="#sort" id="id38">sort</a></li> </ul> </li> -<li><a class="reference internal" href="#scripts" id="id36">Scripts</a></li> +<li><a class="reference internal" href="#scripts" id="id39">Scripts</a></li> </ul> </div> <p>The current version of DFHack has extensive support for @@ -778,7 +781,7 @@ running coroutine and let the C++ code release the core suspend lock. Using an explicit <tt class="docutils literal">dfhack.with_suspend</tt> will prevent this, forcing the function to block on input with lock held.</p> </li> -<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.interpreter([prompt[,env[,history_filename]]])</span></tt></p> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.interpreter([prompt[,history_filename[,env]]])</span></tt></p> <p>Starts an interactive lua interpreter, using the specified prompt string, global environment and command-line history file.</p> <p>If the interactive console is not accessible, returns <em>nil, error</em>.</p> @@ -841,8 +844,21 @@ following properties:</p> </li> </ul> </div> +<div class="section" id="miscellaneous"> +<h3><a class="toc-backref" href="#id14">Miscellaneous</a></h3> +<ul> +<li><p class="first"><tt class="docutils literal">dfhack.VERSION</tt></p> +<p>DFHack version string constant.</p> +</li> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.curry(func,args...)</span></tt>, or <tt class="docutils literal"><span class="pre">curry(func,args...)</span></tt></p> +<p>Returns a closure that invokes the function with args combined +both from the curry call and the closure call itself. I.e. +<tt class="docutils literal"><span class="pre">curry(func,a,b)(c,d)</span></tt> equals <tt class="docutils literal">func(a,b,c,d)</tt>.</p> +</li> +</ul> +</div> <div class="section" id="locking-and-finalization"> -<h3><a class="toc-backref" href="#id14">Locking and finalization</a></h3> +<h3><a class="toc-backref" href="#id15">Locking and finalization</a></h3> <ul> <li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.with_suspend(f[,args...])</span></tt></p> <p>Calls <tt class="docutils literal">f</tt> with arguments after grabbing the DF core suspend lock. @@ -875,7 +891,7 @@ Implemented using <tt class="docutils literal"><span class="pre">call_with_final </ul> </div> <div class="section" id="persistent-configuration-storage"> -<h3><a class="toc-backref" href="#id15">Persistent configuration storage</a></h3> +<h3><a class="toc-backref" href="#id16">Persistent configuration storage</a></h3> <p>This api is intended for storing configuration options in the world itself. It probably should be restricted to data that is world-dependent.</p> <p>Entries are identified by a string <tt class="docutils literal">key</tt>, but it is also possible to manage @@ -910,7 +926,7 @@ functions can just copy values in memory without doing any actual I/O. However, currently every entry has a 180+-byte dead-weight overhead.</p> </div> <div class="section" id="material-info-lookup"> -<h3><a class="toc-backref" href="#id16">Material info lookup</a></h3> +<h3><a class="toc-backref" href="#id17">Material info lookup</a></h3> <p>A material info record has fields:</p> <ul> <li><p class="first"><tt class="docutils literal">type</tt>, <tt class="docutils literal">index</tt>, <tt class="docutils literal">material</tt></p> @@ -955,7 +971,7 @@ Accept dfhack_material_category auto-assign table.</p> </div> </div> <div class="section" id="c-function-wrappers"> -<h2><a class="toc-backref" href="#id17">C++ function wrappers</a></h2> +<h2><a class="toc-backref" href="#id18">C++ function wrappers</a></h2> <p>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 @@ -973,6 +989,9 @@ can be omitted.</p> <li><p class="first"><tt class="docutils literal">dfhack.getHackPath()</tt></p> <p>Returns the dfhack directory path, i.e. <tt class="docutils literal"><span class="pre">".../df/hack/"</span></tt>.</p> </li> +<li><p class="first"><tt class="docutils literal">dfhack.getTickCount()</tt></p> +<p>Returns the tick count in ms, exactly as DF ui uses.</p> +</li> <li><p class="first"><tt class="docutils literal">dfhack.isWorldLoaded()</tt></p> <p>Checks if the world is loaded.</p> </li> @@ -984,15 +1003,19 @@ can be omitted.</p> </li> </ul> <div class="section" id="gui-module"> -<h3><a class="toc-backref" href="#id18">Gui module</a></h3> +<h3><a class="toc-backref" href="#id19">Gui module</a></h3> <ul> -<li><p class="first"><tt class="docutils literal">dfhack.gui.getCurViewscreen()</tt></p> -<p>Returns the viewscreen that is current in the core.</p> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.getCurViewscreen([skip_dismissed])</span></tt></p> +<p>Returns the topmost viewscreen. If <tt class="docutils literal">skip_dismissed</tt> is <em>true</em>, +ignores screens already marked to be removed.</p> </li> <li><p class="first"><tt class="docutils literal">dfhack.gui.getFocusString(viewscreen)</tt></p> <p>Returns a string representation of the current focus position in the ui. The string has a "screen/foo/bar/baz..." format.</p> </li> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.getCurFocus([skip_dismissed])</span></tt></p> +<p>Returns the focus string of the current viewscreen.</p> +</li> <li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.getSelectedWorkshopJob([silent])</span></tt></p> <p>When a job is selected in <em>'q'</em> mode, returns the job, else prints error unless silent and returns <em>nil</em>.</p> @@ -1010,17 +1033,27 @@ a full-screen item view of a container. Note that in the last case, the highlighted <em>contained item</em> is returned, not the container itself.</p> </li> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.getSelectedBuilding([silent])</span></tt></p> +<p>Returns the building selected via <em>'q'</em>, <em>'t'</em>, <em>'k'</em> or <em>'i'</em>.</p> +</li> <li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.showAnnouncement(text,color[,is_bright])</span></tt></p> <p>Adds a regular announcement with given text, color, and brightness. The is_bright boolean actually seems to invert the brightness.</p> </li> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.showZoomAnnouncement(type,pos,text,color[,is_bright])</span></tt></p> +<p>Like above, but also specifies a position you can zoom to from the announcement menu.</p> +</li> <li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.showPopupAnnouncement(text,color[,is_bright])</span></tt></p> <p>Pops up a titan-style modal announcement window.</p> </li> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.showAutoAnnouncement(type,pos,text,color[,is_bright])</span></tt></p> +<p>Uses the type to look up options from announcements.txt, and calls the +above operations accordingly. If enabled, pauses and zooms to position.</p> +</li> </ul> </div> <div class="section" id="job-module"> -<h3><a class="toc-backref" href="#id19">Job module</a></h3> +<h3><a class="toc-backref" href="#id20">Job module</a></h3> <ul> <li><p class="first"><tt class="docutils literal">dfhack.job.cloneJobStruct(job)</tt></p> <p>Creates a deep copy of the given job.</p> @@ -1057,7 +1090,7 @@ a lua list containing them.</p> </ul> </div> <div class="section" id="units-module"> -<h3><a class="toc-backref" href="#id20">Units module</a></h3> +<h3><a class="toc-backref" href="#id21">Units module</a></h3> <ul> <li><p class="first"><tt class="docutils literal">dfhack.units.getPosition(unit)</tt></p> <p>Returns true <em>x,y,z</em> of the unit, or <em>nil</em> if invalid; may be not equal to unit.pos if caged.</p> @@ -1077,6 +1110,26 @@ a lua list containing them.</p> <li><p class="first"><tt class="docutils literal">dfhack.units.getNemesis(unit)</tt></p> <p>Returns the nemesis record of the unit if it has one, or <em>nil</em>.</p> </li> +<li><p class="first"><tt class="docutils literal">dfhack.units.isHidingCurse(unit)</tt></p> +<p>Checks if the unit hides improved attributes from its curse.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.units.getPhysicalAttrValue(unit, attr_type)</tt></p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.units.getMentalAttrValue(unit, attr_type)</tt></p> +<p>Computes the effective attribute value, including curse effect.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.units.isCrazed(unit)</tt></p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.units.isOpposedToLife(unit)</tt></p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.units.hasExtravision(unit)</tt></p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.units.isBloodsucker(unit)</tt></p> +<p>Simple checks of caste attributes that can be modified by curses.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.units.getMiscTrait(unit, type[, create])</tt></p> +<p>Finds (or creates if requested) a misc trait object with the given id.</p> +</li> <li><p class="first"><tt class="docutils literal">dfhack.units.isDead(unit)</tt></p> <p>The unit is completely dead and passive, or a ghost.</p> </li> @@ -1097,6 +1150,12 @@ same checks the game uses to decide game-over by extinction.</p> <p>Returns the age of the unit in years as a floating-point value. If <tt class="docutils literal">true_age</tt> is true, ignores false identities.</p> </li> +<li><p class="first"><tt class="docutils literal">dfhack.units.getEffectiveSkill(unit, skill)</tt></p> +<p>Computes the effective rating for the given skill, taking into account exhaustion, pain etc.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.units.computeMovementSpeed(unit)</tt></p> +<p>Computes number of frames * 100 it takes the unit to move in its current state of mind and body.</p> +</li> <li><p class="first"><tt class="docutils literal">dfhack.units.getNoblePositions(unit)</tt></p> <p>Returns a list of tables describing noble position assignments, or <em>nil</em>. Every table has fields <tt class="docutils literal">entity</tt>, <tt class="docutils literal">assignment</tt> and <tt class="docutils literal">position</tt>.</p> @@ -1108,10 +1167,17 @@ or raws. The <tt class="docutils literal">ignore_noble</tt> boolean disables the <li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.units.getCasteProfessionName(race,caste,prof_id[,plural])</span></tt></p> <p>Retrieves the profession name for the given race/caste using raws.</p> </li> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.units.getProfessionColor(unit[,ignore_noble])</span></tt></p> +<p>Retrieves the color associated with the profession, using noble assignments +or raws. The <tt class="docutils literal">ignore_noble</tt> boolean disables the use of noble positions.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.units.getCasteProfessionColor(race,caste,prof_id)</tt></p> +<p>Retrieves the profession color for the given race/caste using raws.</p> +</li> </ul> </div> <div class="section" id="items-module"> -<h3><a class="toc-backref" href="#id21">Items module</a></h3> +<h3><a class="toc-backref" href="#id22">Items module</a></h3> <ul> <li><p class="first"><tt class="docutils literal">dfhack.items.getPosition(item)</tt></p> <p>Returns true <em>x,y,z</em> of the item, or <em>nil</em> if invalid; may be not equal to item.pos if in inventory.</p> @@ -1151,10 +1217,16 @@ Returns <em>false</em> in case of error.</p> <li><p class="first"><tt class="docutils literal">dfhack.items.moveToInventory(item,unit,use_mode,body_part)</tt></p> <p>Move the item to the unit inventory. Returns <em>false</em> if impossible.</p> </li> +<li><p class="first"><tt class="docutils literal">dfhack.items.remove(item[, no_uncat])</tt></p> +<p>Removes the item, and marks it for garbage collection unless <tt class="docutils literal">no_uncat</tt> is true.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.items.makeProjectile(item)</tt></p> +<p>Turns the item into a projectile, and returns the new object, or <em>nil</em> if impossible.</p> +</li> </ul> </div> <div class="section" id="maps-module"> -<h3><a class="toc-backref" href="#id22">Maps module</a></h3> +<h3><a class="toc-backref" href="#id23">Maps module</a></h3> <ul> <li><p class="first"><tt class="docutils literal">dfhack.maps.getSize()</tt></p> <p>Returns map size in blocks: <em>x, y, z</em></p> @@ -1165,15 +1237,25 @@ Returns <em>false</em> in case of error.</p> <li><p class="first"><tt class="docutils literal">dfhack.maps.getBlock(x,y,z)</tt></p> <p>Returns a map block object for given x,y,z in local block coordinates.</p> </li> +<li><p class="first"><tt class="docutils literal">dfhack.maps.isValidTilePos(coords)</tt>, or isValidTilePos(x,y,z)``</p> +<p>Checks if the given df::coord or x,y,z in local tile coordinates are valid.</p> +</li> <li><p class="first"><tt class="docutils literal">dfhack.maps.getTileBlock(coords)</tt>, or <tt class="docutils literal">getTileBlock(x,y,z)</tt></p> <p>Returns a map block object for given df::coord or x,y,z in local tile coordinates.</p> </li> +<li><p class="first"><tt class="docutils literal">dfhack.maps.ensureTileBlock(coords)</tt>, or <tt class="docutils literal">ensureTileBlock(x,y,z)</tt></p> +<p>Like <tt class="docutils literal">getTileBlock</tt>, but if the block is not allocated, try creating it.</p> +</li> <li><p class="first"><tt class="docutils literal">dfhack.maps.getRegionBiome(region_coord2d)</tt>, or <tt class="docutils literal">getRegionBiome(x,y)</tt></p> <p>Returns the biome info struct for the given global map region.</p> </li> <li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.maps.enableBlockUpdates(block[,flow,temperature])</span></tt></p> <p>Enables updates for liquid flow or temperature, unless already active.</p> </li> +<li><p class="first"><tt class="docutils literal">dfhack.maps.spawnFlow(pos,type,mat_type,mat_index,dimension)</tt></p> +<p>Spawns a new flow (i.e. steam/mist/dust/etc) at the given pos, and with +the given parameters. Returns it, or <em>nil</em> if unsuccessful.</p> +</li> <li><p class="first"><tt class="docutils literal">dfhack.maps.getGlobalInitFeature(index)</tt></p> <p>Returns the global feature object with the given index.</p> </li> @@ -1195,7 +1277,7 @@ burrows, or the presence of invaders.</p> </ul> </div> <div class="section" id="burrows-module"> -<h3><a class="toc-backref" href="#id23">Burrows module</a></h3> +<h3><a class="toc-backref" href="#id24">Burrows module</a></h3> <ul> <li><p class="first"><tt class="docutils literal">dfhack.burrows.findByName(name)</tt></p> <p>Returns the burrow pointer or <em>nil</em>.</p> @@ -1230,8 +1312,12 @@ burrows, or the presence of invaders.</p> </ul> </div> <div class="section" id="buildings-module"> -<h3><a class="toc-backref" href="#id24">Buildings module</a></h3> +<h3><a class="toc-backref" href="#id25">Buildings module</a></h3> <ul> +<li><p class="first"><tt class="docutils literal">dfhack.buildings.setOwner(item,unit)</tt></p> +<p>Replaces the owner of the building. If unit is <em>nil</em>, removes ownership. +Returns <em>false</em> in case of error.</p> +</li> <li><p class="first"><tt class="docutils literal">dfhack.buildings.getSize(building)</tt></p> <p>Returns <em>width, height, centerx, centery</em>.</p> </li> @@ -1370,7 +1456,7 @@ can be determined this way, <tt class="docutils literal">constructBuilding</tt> </ul> </div> <div class="section" id="constructions-module"> -<h3><a class="toc-backref" href="#id25">Constructions module</a></h3> +<h3><a class="toc-backref" href="#id26">Constructions module</a></h3> <ul> <li><p class="first"><tt class="docutils literal">dfhack.constructions.designateNew(pos,type,item_type,mat_index)</tt></p> <p>Designates a new construction at given position. If there already is @@ -1385,8 +1471,161 @@ Returns <em>true, was_only_planned</em> if removed; or <em>false</em> if none fo </li> </ul> </div> +<div class="section" id="screen-api"> +<h3><a class="toc-backref" href="#id27">Screen API</a></h3> +<p>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.</p> +<p>Basic painting functions:</p> +<ul> +<li><p class="first"><tt class="docutils literal">dfhack.screen.getWindowSize()</tt></p> +<p>Returns <em>width, height</em> of the screen.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.screen.getMousePos()</tt></p> +<p>Returns <em>x,y</em> of the tile the mouse is over.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.screen.inGraphicsMode()</tt></p> +<p>Checks if [GRAPHICS:YES] was specified in init.</p> +</li> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.screen.paintTile(pen,x,y[,char,tile])</span></tt></p> +<p>Paints a tile using given parameters. Pen is a table with following possible fields:</p> +<dl class="docutils"> +<dt><tt class="docutils literal">ch</tt></dt> +<dd><p class="first last">Provides the ordinary tile character, as either a 1-character string or a number. +Can be overridden with the <tt class="docutils literal">char</tt> function parameter.</p> +</dd> +<dt><tt class="docutils literal">fg</tt></dt> +<dd><p class="first last">Foreground color for the ordinary tile. Defaults to COLOR_GREY (7).</p> +</dd> +<dt><tt class="docutils literal">bg</tt></dt> +<dd><p class="first last">Background color for the ordinary tile. Defaults to COLOR_BLACK (0).</p> +</dd> +<dt><tt class="docutils literal">bold</tt></dt> +<dd><p class="first last">Bright/bold text flag. If <em>nil</em>, computed based on (fg & 8); fg is masked to 3 bits. +Otherwise should be <em>true/false</em>.</p> +</dd> +<dt><tt class="docutils literal">tile</tt></dt> +<dd><p class="first last">Graphical tile id. Ignored unless [GRAPHICS:YES] was in init.txt.</p> +</dd> +<dt><tt class="docutils literal">tile_color = true</tt></dt> +<dd><p class="first last">Specifies that the tile should be shaded with <em>fg/bg</em>.</p> +</dd> +<dt><tt class="docutils literal">tile_fg, tile_bg</tt></dt> +<dd><p class="first last">If specified, overrides <em>tile_color</em> and supplies shading colors directly.</p> +</dd> +</dl> +<p>Returns <em>false</em> if coordinates out of bounds, or other error.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.screen.readTile(x,y)</tt></p> +<p>Retrieves the contents of the specified tile from the screen buffers. +Returns a pen, or <em>nil</em> if invalid or TrueType.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.screen.paintString(pen,x,y,text)</tt></p> +<p>Paints the string starting at <em>x,y</em>. Uses the string characters +in sequence to override the <tt class="docutils literal">ch</tt> field of pen.</p> +<p>Returns <em>true</em> if painting at least one character succeeded.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.screen.fillRect(pen,x1,y1,x2,y2)</tt></p> +<p>Fills the rectangle specified by the coordinates with the given pen. +Returns <em>true</em> if painting at least one character succeeded.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.screen.findGraphicsTile(pagename,x,y)</tt></p> +<p>Finds a tile from a graphics set (i.e. the raws used for creatures), +if in graphics mode and loaded.</p> +<p>Returns: <em>tile, tile_grayscale</em>, or <em>nil</em> if not found. +The values can then be used for the <em>tile</em> field of <em>pen</em> structures.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.screen.clear()</tt></p> +<p>Fills the screen with blank background.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.screen.invalidate()</tt></p> +<p>Requests repaint of the screen by setting a flag. Unlike other +functions in this section, this may be used at any time.</p> +</li> +</ul> +<p>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.</p> +<p><strong>NOTE</strong>: As a matter of policy, in order to avoid user confusion, all +interface screens added by dfhack should bear the "DFHack" signature.</p> +<p>Screens are managed with the following functions:</p> +<ul> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.screen.show(screen[,below])</span></tt></p> +<p>Displays the given screen, possibly placing it below a different one. +The screen must not be already shown. Returns <em>true</em> if success.</p> +</li> +<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.screen.dismiss(screen[,to_first])</span></tt></p> +<p>Marks the screen to be removed when the game enters its event loop. +If <tt class="docutils literal">to_first</tt> is <em>true</em>, all screens up to the first one will be deleted.</p> +</li> +<li><p class="first"><tt class="docutils literal">dfhack.screen.isDismissed(screen)</tt></p> +<p>Checks if the screen is already marked for removal.</p> +</li> +</ul> +<p>Apart from a native viewscreen object, these functions accept a table +as a screen. In this case, <tt class="docutils literal">show</tt> creates a new native viewscreen +that delegates all processing to methods stored in that table.</p> +<p><strong>NOTE</strong>: Lua-implemented screens are only supported in the core context.</p> +<p>Supported callbacks and fields are:</p> +<ul> +<li><p class="first"><tt class="docutils literal">screen._native</tt></p> +<p>Initialized by <tt class="docutils literal">show</tt> with a reference to the backing viewscreen +object, and removed again when the object is deleted.</p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onShow()</tt></p> +<p>Called by <tt class="docutils literal">dfhack.screen.show</tt> if successful.</p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onDismiss()</tt></p> +<p>Called by <tt class="docutils literal">dfhack.screen.dismiss</tt> if successful.</p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onDestroy()</tt></p> +<p>Called from the destructor when the viewscreen is deleted.</p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onResize(w, h)</tt></p> +<p>Called before <tt class="docutils literal">onRender</tt> or <tt class="docutils literal">onIdle</tt> when the window size has changed.</p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onRender()</tt></p> +<p>Called when the viewscreen should paint itself. This is the only context +where the above painting functions work correctly.</p> +<p>If omitted, the screen is cleared; otherwise it should do that itself. +In order to make a see-through dialog, call <tt class="docutils literal">self._native.parent:render()</tt>.</p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onIdle()</tt></p> +<p>Called every frame when the screen is on top of the stack.</p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onHelp()</tt></p> +<p>Called when the help keybinding is activated (usually '?').</p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onInput(keys)</tt></p> +<p>Called when keyboard or mouse events are available. +If any keys are pressed, the keys argument is a table mapping them to <em>true</em>. +Note that this refers to logical keybingings computed from real keys via +options; if multiple interpretations exist, the table will contain multiple keys.</p> +<p>The table also may contain special keys:</p> +<dl class="docutils"> +<dt><tt class="docutils literal">_STRING</tt></dt> +<dd><p class="first last">Maps to an integer in range 0-255. Duplicates a separate "STRING_A???" code for convenience.</p> +</dd> +<dt><tt class="docutils literal">_MOUSE_L, _MOUSE_R</tt></dt> +<dd><p class="first last">If the left or right mouse button is pressed.</p> +</dd> +</dl> +<p>If this method is omitted, the screen is dismissed on receival of the <tt class="docutils literal">LEAVESCREEN</tt> key.</p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onGetSelectedUnit()</tt></p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onGetSelectedItem()</tt></p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onGetSelectedJob()</tt></p> +</li> +<li><p class="first"><tt class="docutils literal">function screen:onGetSelectedBuilding()</tt></p> +<p>Implement these to provide a return value for the matching +<tt class="docutils literal"><span class="pre">dfhack.gui.getSelected...</span></tt> function.</p> +</li> +</ul> +</div> <div class="section" id="internal-api"> -<h3><a class="toc-backref" href="#id26">Internal API</a></h3> +<h3><a class="toc-backref" href="#id28">Internal API</a></h3> <p>These functions are intended for the use by dfhack developers, and are only documented here for completeness:</p> <ul> @@ -1409,6 +1648,11 @@ global environment, persistent between calls to the script.</p> <li><p class="first"><tt class="docutils literal">dfhack.internal.getMemRanges()</tt></p> <p>Returns a sequence of tables describing virtual memory ranges of the process.</p> </li> +<li><p class="first"><tt class="docutils literal">dfhack.internal.patchMemory(dest,src,count)</tt></p> +<p>Like memmove below, but works even if dest is read-only memory, e.g. code. +If destination overlaps a completely invalid memory region, or another error +occurs, returns false.</p> +</li> <li><p class="first"><tt class="docutils literal">dfhack.internal.memmove(dest,src,count)</tt></p> <p>Wraps the standard memmove function. Accepts both numbers and refs as pointers.</p> </li> @@ -1429,7 +1673,7 @@ Returns: <em>found_index</em>, or <em>nil</em> if end reached.</p> </div> </div> <div class="section" id="core-interpreter-context"> -<h2><a class="toc-backref" href="#id27">Core interpreter context</a></h2> +<h2><a class="toc-backref" href="#id29">Core interpreter context</a></h2> <p>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.</p> @@ -1460,9 +1704,9 @@ Using <tt class="docutils literal">timeout_active(id,nil)</tt> cancels the timer </li> </ul> <div class="section" id="event-type"> -<h3><a class="toc-backref" href="#id28">Event type</a></h3> -<p>An event is just a lua table with a predefined metatable that -contains a __call metamethod. When it is invoked, it loops +<h3><a class="toc-backref" href="#id30">Event type</a></h3> +<p>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.</p> <p>This type itself is available in any context, but only the @@ -1473,9 +1717,15 @@ core context has the actual events defined by C++ code.</p> <p>Creates a new instance of an event.</p> </li> <li><p class="first"><tt class="docutils literal">event[key] = function</tt></p> -<p>Sets the function as one of the listeners.</p> +<p>Sets the function as one of the listeners. Assign <em>nil</em> to remove it.</p> <p><strong>NOTE</strong>: The <tt class="docutils literal">df.NULL</tt> key is reserved for the use by -the C++ owner of the event, and has some special semantics.</p> +the C++ owner of the event; it is an error to try setting it.</p> +</li> +<li><p class="first"><tt class="docutils literal">#event</tt></p> +<p>Returns the number of non-nil listeners.</p> +</li> +<li><p class="first"><tt class="docutils literal">pairs(event)</tt></p> +<p>Iterates over all listeners in the table.</p> </li> <li><p class="first"><tt class="docutils literal"><span class="pre">event(args...)</span></tt></p> <p>Invokes all listeners contained in the event in an arbitrary @@ -1486,7 +1736,7 @@ order using <tt class="docutils literal">dfhack.safecall</tt>.</p> </div> </div> <div class="section" id="lua-modules"> -<h1><a class="toc-backref" href="#id29">Lua Modules</a></h1> +<h1><a class="toc-backref" href="#id31">Lua Modules</a></h1> <p>DFHack sets up the lua interpreter so that the built-in <tt class="docutils literal">require</tt> function can be used to load shared lua code from hack/lua/. The <tt class="docutils literal">dfhack</tt> namespace reference itself may be obtained via @@ -1515,7 +1765,7 @@ in this document.</p> </li> </ul> <div class="section" id="global-environment"> -<h2><a class="toc-backref" href="#id30">Global environment</a></h2> +<h2><a class="toc-backref" href="#id32">Global environment</a></h2> <p>A number of variables and functions are provided in the base global environment by the mandatory init file dfhack.lua:</p> <ul> @@ -1556,7 +1806,7 @@ Returns <em>nil</em> if any of obj or indices is <em>nil</em>, or a numeric inde </ul> </div> <div class="section" id="utils"> -<h2><a class="toc-backref" href="#id31">utils</a></h2> +<h2><a class="toc-backref" href="#id33">utils</a></h2> <ul> <li><p class="first"><tt class="docutils literal">utils.compare(a,b)</tt></p> <p>Comparator function; returns <em>-1</em> if a<b, <em>1</em> if a>b, <em>0</em> otherwise.</p> @@ -1669,7 +1919,7 @@ throws an error.</p> </ul> </div> <div class="section" id="dumper"> -<h2><a class="toc-backref" href="#id32">dumper</a></h2> +<h2><a class="toc-backref" href="#id34">dumper</a></h2> <p>A third-party lua table dumper module from <a class="reference external" href="http://lua-users.org/wiki/DataDumper">http://lua-users.org/wiki/DataDumper</a>. Defines one function:</p> @@ -1681,16 +1931,88 @@ the other arguments see the original documentation link above.</p> </li> </ul> </div> +<div class="section" id="class"> +<h2><a class="toc-backref" href="#id35">class</a></h2> +<p>Implements a trivial single-inheritance class system.</p> +<ul> +<li><p class="first"><tt class="docutils literal">Foo = defclass(Foo[, ParentClass])</tt></p> +<p>Defines or updates class Foo. The <tt class="docutils literal">Foo = defclass(Foo)</tt> syntax +is needed so that when the module or script is reloaded, the +class identity will be preserved through the preservation of +global variable values.</p> +<p>The <tt class="docutils literal">defclass</tt> function is defined as a stub in the global +namespace, and using it will auto-load the class module.</p> +</li> +<li><p class="first"><tt class="docutils literal">Class.super</tt></p> +<p>This class field is set by defclass to the parent class, and +allows a readable <tt class="docutils literal">Class.super.method(self, <span class="pre">...)</span></tt> syntax for +calling superclass methods.</p> +</li> +<li><p class="first"><tt class="docutils literal">Class.ATTRS { foo = xxx, bar = yyy }</tt></p> +<p>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.</p> +<p>If the default value should be <em>nil</em>, use <tt class="docutils literal">ATTRS { foo = DEFAULT_NIL }</tt>.</p> +</li> +<li><p class="first"><tt class="docutils literal">new_obj = Class{ foo = arg, bar = arg, ... }</tt></p> +<p>Calling the class as a function creates and initializes a new instance. +Initialization happens in this order:</p> +<ol class="arabic simple"> +<li>An empty instance table is created, and its metatable set.</li> +<li>The <tt class="docutils literal">preinit</tt> method is called via <tt class="docutils literal">invoke_before</tt> (see below) +with the table used as argument to the class. This method is intended +for validating and tweaking that argument table.</li> +<li>Declared ATTRS are initialized from the argument table or their default values.</li> +<li>The <tt class="docutils literal">init</tt> method is called via <tt class="docutils literal">invoke_after</tt> with the argument table. +This is the main constructor method.</li> +<li>The <tt class="docutils literal">postinit</tt> method is called via <tt class="docutils literal">invoke_after</tt> with the argument table. +Place code that should be called after the object is fully constructed here.</li> +</ol> +</li> +</ul> +<p>Predefined instance methods:</p> +<ul> +<li><p class="first"><tt class="docutils literal">instance:assign{ foo = xxx }</tt></p> +<p>Assigns all values in the input table to the matching instance fields.</p> +</li> +<li><p class="first"><tt class="docutils literal">instance:callback(method_name, <span class="pre">[args...])</span></tt></p> +<p>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.</p> +</li> +<li><p class="first"><tt class="docutils literal">instance:invoke_before(method_name, <span class="pre">args...)</span></tt></p> +<p>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:</p> +<pre class="literal-block"> +function Class:invoke_before(method, ...) + if rawget(Class, method) then + rawget(Class, method)(self, ...) + end + Class.super.invoke_before(method, ...) +end +</pre> +</li> +<li><p class="first"><tt class="docutils literal">instance:invoke_after(method_name, <span class="pre">args...)</span></tt></p> +<p>Like invoke_before, only the method is called after the recursive call to super, +i.e. invocations happen in the parent to child order.</p> +<p>These two methods are inspired by the Common Lisp before and after methods, and +are intended for implementing similar protocols for certain things. The class +library itself uses them for constructors.</p> +</li> +</ul> +<p>To avoid confusion, these methods cannot be redefined.</p> +</div> </div> <div class="section" id="plugins"> -<h1><a class="toc-backref" href="#id33">Plugins</a></h1> +<h1><a class="toc-backref" href="#id36">Plugins</a></h1> <p>DFHack plugins may export native functions and events to lua contexts. They are automatically imported by <tt class="docutils literal"><span class="pre">mkmodule('plugins.<name>')</span></tt>; this means that a lua module file is still necessary for <tt class="docutils literal">require</tt> to read.</p> <p>The following plugins have lua support.</p> <div class="section" id="burrows"> -<h2><a class="toc-backref" href="#id34">burrows</a></h2> +<h2><a class="toc-backref" href="#id37">burrows</a></h2> <p>Implements extended burrow manipulations.</p> <p>Events:</p> <ul> @@ -1728,13 +2050,13 @@ set is the same as used by the command line.</p> <p>The lua module file also re-exports functions from <tt class="docutils literal">dfhack.burrows</tt>.</p> </div> <div class="section" id="sort"> -<h2><a class="toc-backref" href="#id35">sort</a></h2> +<h2><a class="toc-backref" href="#id38">sort</a></h2> <p>Does not export any native functions as of now. Instead, it calls lua code to perform the actual ordering of list items.</p> </div> </div> <div class="section" id="scripts"> -<h1><a class="toc-backref" href="#id36">Scripts</a></h1> +<h1><a class="toc-backref" href="#id39">Scripts</a></h1> <p>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 sans @@ -0,0 +1,88 @@ +DFHack v0.34.11-r2 (UNRELEASED) + + Internals: + - full support for Mac OS X. + - a plugin that adds scripting in ruby. + - support for interposing virtual methods in DF from C++ plugins. + - support for creating new interface screens from C++ and lua. + - added various other API functions. + Notable bugfixes: + - better terminal reset after exit on linux. + - seedwatch now works on reclaim. + - the sort plugin won't crash on cages anymore. + Misc improvements: + - autodump: can move items to any walkable tile, not just floors. + - stripcaged: by default keep armor, new dumparmor option. + - zone: allow non-domesticated birds in nestboxes. + - workflow: quality range in constraints. + - cleanplants: new command to remove rain water from plants. + - liquids: can paint permaflow, i.e. what makes rivers power water wheels. + - prospect: pre-embark prospector accounts for caves & magma sea in its estimate. + - rename: supports renaming stockpiles, workshops, traps, siege engines. + New tweaks: + - tweak stable-cursor: keeps exact cursor position between d/k/t/q/v etc menus. + - tweak patrol-duty: makes Train orders reduce patrol timer, like the binary patch does. + - tweak readable-build-plate: fix unreadable truncation in unit pressure plate build ui. + - tweak stable-temp: fixes bug 6012; may improve FPS by 50-100% on a slow item-heavy fort. + - tweak fast-heat: speeds up item heating & cooling, thus making stable-temp act faster. + - tweak fix-dimensions: fixes subtracting small amounts from stacked liquids etc. + - tweak advmode-contained: fixes UI bug in custom reactions with container inputs in advmode. + - tweak fast-trade: Shift-Enter for selecting items quckly in Trade and Move to Depot screens. + - tweak military-stable-assign: Stop rightmost list of military->Positions from jumping to top. + - tweak military-color-assigned: In same list, color already assigned units in brown & green. + New scripts: + - fixnaked: removes thoughts about nakedness. + - setfps: set FPS cap at runtime, in case you want slow motion or speed-up. + - siren: wakes up units, stops breaks and parties - but causes bad thoughts. + - fix/population-cap: run after every migrant wave to prevent exceeding the cap. + - fix/stable-temp: counts items with temperature updates; does instant one-shot stable-temp. + - fix/loyaltycascade: fix units allegiance, eg after ordering a dwarf merchant kill. + - deathcause: shows the circumstances of death for a given body. + - digfort: designate areas to dig from a csv file. + - drainaquifer: remove aquifers from the map. + - growcrops: cheat to make farm crops instantly grow. + - magmasource: continuously spawn magma from any map tile. + - removebadthoughts: delete all negative thoughts from your dwarves. + - slayrace: instakill all units of a given race, optionally with magma. + - superdwarf: per-creature fastdwarf. + New GUI scripts: + - gui/mechanisms: browse mechanism links of the current building. + - gui/room-list: browse other rooms owned by the unit when assigning one. + - gui/liquids: a GUI front-end for the liquids plugin. + - gui/rename: renaming stockpiles, workshops and units via an in-game dialog. + - gui/power-meter: front-end for the Power Meter plugin. + - gui/siege-engine: front-end for the Siege Engine plugin. + Autolabor plugin: + - can set nonidle hauler percentage. + - broker excluded from all labors when needed at depot. + - likewise, anybody with a scheduled diplomat meeting. + New Dwarf Manipulator plugin: + Open the unit list, and press 'l' to access a Dwarf Therapist like UI in the game. + New Steam Engine plugin: + Dwarven Water Reactors don't make any sense whatsoever and cause lag, so this may be + a replacement for those concerned by it. The plugin detects if a workshop with a + certain name is in the raws used by the current world, and provides the necessary + behavior. See hack/raw/*_steam_engine.txt for the necessary raw definitions. + Note: Stuff like animal treadmills might be more period, but absolutely can't be + done with tools dfhack has access to. + New Power Meter plugin: + When activated, implements a pressure plate modification that detects power in gear + boxes built on the four adjacent N/S/W/E tiles. The gui/power-meter script implements + the necessary build configuration UI. + New Siege Engine plugin: + When enabled and configured via gui/siege-engine, allows aiming siege engines + at a designated rectangular area with 360 degree fire range and across Z levels; + this works by rewriting the projectile trajectory immediately after it appears. + Also supports loading catapults with non-boulder projectiles, taking from a stockpile, + and restricting operator skill range like with ordinary workshops. + Disclaimer: not in any way to undermine the future siege update from Toady, but + the aiming logic of existing engines hasn't been updated since 2D, and is almost + useless above ground :(. Again, things like making siegers bring their own engines + is totally out of the scope of dfhack and can only be done by Toady. + New Add Spatter plugin: + Detects reactions with certain names in the raws, and changes them from adding + improvements to adding item contaminants. This allows directly covering items + with poisons. The added spatters are immune both to water and 'clean items'. + Intended to give some use to all those giant cave spider poison barrels brought + by the caravans. + @@ -1,3 +1,7 @@ +############# +DFHack Readme +############# + ============ Introduction ============ @@ -97,46 +101,178 @@ the issues tracker on github, contact me (peterix@gmail.com) or visit the ============= The init file ============= -If your DF folder contains a file named dfhack.init, its contents will be run +If your DF folder contains a file named ``dfhack.init``, its contents will be run every time you start DF. This allows setting up keybindings. An example file -is provided as dfhack.init-example - you can tweak it and rename to dfhack.init +is provided as ``dfhack.init-example`` - you can tweak it and rename to dfhack.init if you want to use this functionality. +Setting keybindings +=================== + +To set keybindings, use the built-in ``keybinding`` command. Like any other +command it can be used at any time from the console, but it is also meaningful +in the DFHack init file. + +Currently it supports any combination of Ctrl/Alt/Shift with F1-F9, or A-Z. + +Possible ways to call the command: + +:keybinding list <key>: List bindings active for the key combination. +:keybinding clear <key> <key>...: Remove bindings for the specified keys. +:keybinding add <key> "cmdline" "cmdline"...: Add bindings for the specified + key. +:keybinding set <key> "cmdline" "cmdline"...: Clear, and then add bindings for + the specified key. + +The *<key>* parameter above has the following *case-sensitive* syntax:: + + [Ctrl-][Alt-][Shift-]KEY[@context] + +where the *KEY* part can be F1-F9 or A-Z, and [] denote optional parts. + +When multiple commands are bound to the same key combination, DFHack selects +the first applicable one. Later 'add' commands, and earlier entries within one +'add' command have priority. Commands that are not specifically intended for use +as a hotkey are always considered applicable. + +The *context* part in the key specifier above can be used to explicitly restrict +the UI state where the binding would be applicable. If called without parameters, +the ``keybinding`` command among other things prints the current context string. +Only bindings with a *context* tag that either matches the current context fully, +or is a prefix ending at a '/' boundary would be considered for execution, i.e. +for context ``foo/bar/baz``, possible matches are any of ``@foo/bar/baz``, ``@foo/bar``, +``@foo`` or none. + + ======== Commands ======== +DFHack command syntax consists of a command name, followed by arguments separated +by whitespace. To include whitespace in an argument, quote it in double quotes. +To include a double quote character, use ``\"`` inside double quotes. + +If the first non-whitespace character of a line is ``#``, the line is treated +as a comment, i.e. a silent no-op command. + +If the first non-whitespace character is ``:``, the command is parsed in a special +alternative mode: first, non-whitespace characters immediately following the ``:`` +are used as the command name; the remaining part of the line, starting with the first +non-whitespace character *after* the command name, is used verbatim as the first argument. +The following two command lines are exactly equivalent: + + * ``:foo a b "c d" e f`` + * ``foo "a b \"c d\" e f"`` + +This is intended for commands like ``rb_eval`` that evaluate script language statements. + Almost all the commands support using the 'help <command-name>' built-in command to retrieve further help without having to look at this document. Alternatively, some accept a 'help'/'?' option on their command line. + +Game progress +============= + +die +--- +Instantly kills DF without saving. + +forcepause +---------- +Forces DF to pause. This is useful when your FPS drops below 1 and you lose +control of the game. + + * Activate with 'forcepause 1' + * Deactivate with 'forcepause 0' + +nopause +------- +Disables pausing (both manual and automatic) with the exception of pause forced +by 'reveal hell'. This is nice for digging under rivers. + +fastdwarf +--------- +Makes your minions move at ludicrous speeds. + + * Activate with 'fastdwarf 1' + * Deactivate with 'fastdwarf 0' + + +Game interface +============== + +follow +------ +Makes the game view follow the currently highlighted unit after you exit from +current menu/cursor mode. Handy for watching dwarves running around. Deactivated +by moving the view manually. + +tidlers +------- +Toggle between all possible positions where the idlers count can be placed. + +twaterlvl +--------- +Toggle between displaying/not displaying liquid depth as numbers. + +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. + +rename +------ +Allows renaming various things. + +Options: + + :rename squad <index> "name": Rename squad by index to 'name'. + :rename hotkey <index> \"name\": Rename hotkey by index. This allows assigning + longer commands to the DF hotkeys. + :rename unit "nickname": Rename a unit/creature highlighted in the DF user + interface. + :rename unit-profession "custom profession": Change proffession name of the + highlighted unit/creature. + :rename building "name": Set a custom name for the selected building. + The building must be one of stockpile, workshop, furnace, trap, + siege engine or an activity zone. + + +Adventure mode +============== + adv-bodyswap -============ +------------ This allows taking control over your followers and other creatures in adventure mode. For example, you can make them pick up new arms and armor and equip them properly. -Usage ------ +Usage: + * When viewing unit details, body-swaps into that unit. * In the main adventure mode screen, reverts transient swap. advtools -======== +-------- A package of different adventure mode tools (currently just one) - -Usage ------ -:list-equipped [all]: List armor and weapons equipped by your companions. - If all is specified, also lists non-metal clothing. -:metal-detector [all-types] [non-trader]: Reveal metal armor and weapons in - shops. The options disable the checks - on item type and being in shop. +Usage: + + :list-equipped [all]: List armor and weapons equipped by your companions. + If all is specified, also lists non-metal clothing. + :metal-detector [all-types] [non-trader]: Reveal metal armor and weapons in + shops. The options disable the checks + on item type and being in shop. + + +Map modification +================ 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 @@ -149,18 +285,18 @@ as well, though. Mineral veins and gem clusters will stay on the map. Use 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. +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 + :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 + :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 @@ -169,16 +305,16 @@ Options 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. + :verbose: Give some details about what is being changed. + :trouble: Give some advice about known problems. Examples: ---------- -``changelayer GRANITE`` + + ``changelayer GRANITE`` Convert layer at cursor position into granite. -``changelayer SILTY_CLAY force`` + ``changelayer SILTY_CLAY force`` Convert layer at cursor position into clay even if it's stone. -``changelayer MARBLE all_biomes all_layers`` + ``changelayer MARBLE all_biomes all_layers`` Convert all layers of all biomes which are not soil into marble. .. note:: @@ -197,17 +333,18 @@ Examples: You did save your game, right? changevein -========== +---------- Changes material of the vein under cursor to the specified inorganic RAW -material. +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`` + + ``changevein NATIVE_PLATINUM`` Convert vein at cursor position into platinum ore. changeitem -========== +---------- Allows changing item material and base quality. By default the item currently selected in the UI will be changed (you can select items in the 'k' list or inside containers/inventory). By default change is only allowed if materials @@ -218,498 +355,289 @@ 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. - -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: -Options -------- -:detail: Print full name, date of birth, date of curse and some status - info (some vampires might use fake identities in-game, though). -:nick: Set the type of curse as nickname (does not always show up - in-game, some vamps don't like nicknames). -:all: Include dead and passive cursed creatures (can result in a quite - long list after having FUN with necromancers). -:verbose: Print all curse tags (if you really want to know it all). + :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: ---------- -``cursecheck detail all`` - Give detailed info about all cursed creatures including deceased ones (no - in-game cursor). -``cursecheck nick`` - Give a nickname all living/active cursed creatures on the map(no in-game - cursor). - -.. note:: - * If you do a full search (with the option "all") former ghosts will show up - with the cursetype "unknown" because their ghostly flag is not set - anymore. But if you happen to find a living/active creature with cursetype - "unknown" please report that in the dfhack thread on the modding forum or - per irc. This is likely to happen with mods which introduce new types - of curses, for example. - -follow -====== -Makes the game view follow the currently highlighted unit after you exit from -current menu/cursor mode. Handy for watching dwarves running around. Deactivated -by moving the view manually. - -forcepause -========== -Forces DF to pause. This is useful when your FPS drops below 1 and you lose -control of the game. - - * Activate with 'forcepause 1' - * Deactivate with 'forcepause 0' + ``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. -nopause -======= -Disables pausing (both manual and automatic) with the exception of pause forced -by 'reveal hell'. This is nice for digging under rivers. +colonies +-------- +Allows listing all the vermin colonies on the map and optionally turning them into honey bee colonies. -die -=== -Instantly kills DF without saving. +Options: -autodump -======== -This utility lets you quickly move all items designated to be dumped. -Items are instantly moved to the cursor position, the dump flag is unset, -and the forbid flag is set, as if it had been dumped normally. -Be aware that any active dump item tasks still point at the item. + :bees: turn colonies into honey bee colonies -Cursor must be placed on a floor tile so the items can be dumped there. +deramp (by zilpin) +------------------ +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). -Options +feature ------- -:destroy: Destroy instead of dumping. Doesn't require a cursor. -:destroy-here: Destroy items only under the cursor. -:visible: Only process items that are not hidden. -:hidden: Only process hidden items. -:forbidden: Only process forbidden items (default: only unforbidden). - -autodump-destroy-here -===================== -Destroy items marked for dumping under cursor. Identical to autodump -destroy-here, but intended for use as keybinding. - -autodump-destroy-item -===================== -Destroy the selected item. The item may be selected in the 'k' list, or inside -a container. If called again before the game is resumed, cancels destroy. - -burrow -====== -Miscellaneous burrow control. Allows manipulating burrows and automated burrow -expansion while digging. +Enables management of map features. -Options -------- -:enable feature ...: -:disable feature ...: Enable or Disable features of the plugin. -:clear-unit burrow burrow ...: -:clear-tiles burrow burrow ...: Removes all units or tiles from the burrows. -:set-units target-burrow src-burrow ...: -:add-units target-burrow src-burrow ...: -:remove-units target-burrow src-burrow ...: Adds or removes units in source - burrows to/from the target burrow. Set is equivalent to clear and add. -:set-tiles target-burrow src-burrow ...: -:add-tiles target-burrow src-burrow ...: -:remove-tiles target-burrow src-burrow ...: Adds or removes tiles in source - burrows to/from the target burrow. In place of a source burrow it is - possible to use one of the following keywords: ABOVE_GROUND, - SUBTERRANEAN, INSIDE, OUTSIDE, LIGHT, DARK, HIDDEN, REVEALED - -Features --------- -:auto-grow: When a wall inside a burrow with a name ending in '+' is dug - out, the burrow is extended to newly-revealed adjacent walls. - This final '+' may be omitted in burrow name args of commands above. - Digging 1-wide corridors with the miner inside the burrow is SLOW. +* Discovering a magma feature (magma pool, volcano, magma sea, or curious + underground structure) permits magma workshops and furnaces to be built. +* Discovering a cavern layer causes plants (trees, shrubs, and grass) from + that cavern to grow within your fortress. -catsplosion -=========== -Makes cats just *multiply*. It is not a good idea to run this more than once or -twice. +Options: -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. + :list: Lists all map features in your current embark by index. + :show X: Marks the selected map feature as discovered. + :hide X: Marks the selected map feature as undiscovered. -Options +liquids ------- -: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. +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). -Extra options for 'map' ------------------------ -:mud: Remove mud in addition to the normal stuff. -:snow: Also remove snow coverings. +For more information, refer to the command's internal help. -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. +.. note:: -cleanowned -========== -Confiscates items owned by dwarfs. By default, owned food on the floor -and rotten items are confistacted and dumped. + Spawning and deleting liquids can F up pathing data and + temperatures (creating heat traps). You've been warned. -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. +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). -Example: --------- -``cleanowned scattered X`` : This will confiscate rotten and dropped food, garbage on the floors and any worn items with 'X' damage and above. +Intended to be used as keybinding. Requires an active in-game cursor. -colonies -======== -Allows listing all the vermin colonies on the map and optionally turning them into honey bee colonies. -Options -------- -:bees: turn colonies into honey bee colonies +tiletypes +--------- +Can be used for painting map tiles and is an interactive command, much like +liquids. -deramp (by zilpin) -================== -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). +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. -dfusion -======= -This is the DFusion lua plugin system by warmist/darius, running as a DFHack plugin. +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. -See the bay12 thread for details: http://www.bay12forums.com/smf/index.php?topic=69682.15 +The properties of filter and paint can be partially defined. This means that +you can for example do something like this: -Confirmed working DFusion plugins: ----------------------------------- -:simple_embark: allows changing the number of dwarves available on embark. +:: -.. note:: + filter material STONE + filter shape FORTIFICATION + paint shape FLOOR - * Some of the DFusion plugins aren't completely ported yet. This can lead to crashes. - * This is currently working only on Windows. - * The game will be suspended while you're using dfusion. Don't panic when it doen't respond. +This will turn all stone fortifications into floors, preserving the material. -drybuckets -========== -This utility removes water from all buckets in your fortress, allowing them to be safely used for making lye. +Or this: +:: -fastdwarf -========= -Makes your minions move at ludicrous speeds. + filter shape FLOOR + filter material MINERAL + paint shape WALL - * Activate with 'fastdwarf 1' - * Deactivate with 'fastdwarf 0' +Turning mineral vein floors back into walls. -feature -======= -Enables management of map features. +The tool also allows tweaking some tile flags: -* Discovering a magma feature (magma pool, volcano, magma sea, or curious - underground structure) permits magma workshops and furnaces to be built. -* Discovering a cavern layer causes plants (trees, shrubs, and grass) from - that cavern to grow within your fortress. +Or this: -Options -------- -:list: Lists all map features in your current embark by index. -:show X: Marks the selected map feature as discovered. -:hide X: Marks the selected map feature as undiscovered. +:: -filltraffic -=========== -Set traffic designations using flood-fill starting at the cursor. + paint hidden 1 + paint hidden 0 -Traffic Type Codes: -------------------- -:H: High Traffic -:N: Normal Traffic -:L: Low Traffic -:R: Restricted Traffic +This will hide previously revealed tiles (or show hidden with the 0 option). -Other Options: --------------- -:X: Fill accross z-levels. -:B: Include buildings and stockpiles. -:P: Include empty space. +Any paint or filter option (or the entire paint or filter) can be disabled entirely by using the ANY keyword: -Example: --------- -'filltraffic H' - When used in a room with doors, it will set traffic to HIGH in just that room. +:: -alltraffic -========== -Set traffic designations for every single tile of the map (useful for resetting traffic designations). + paint hidden ANY + paint shape ANY + filter material any + filter shape any + filter any -Traffic Type Codes: -------------------- -:H: High Traffic -:N: Normal Traffic -:L: Low Traffic -:R: Restricted Traffic +You can use several different brushes for painting tiles: + * Point. (point) + * Rectangular range. (range) + * A column ranging from current cursor to the first solid tile above. (column) + * DF map block - 16x16 tiles, in a regular grid. (block) Example: --------- -'alltraffic N' - Set traffic to 'normal' for all tiles. -fixdiplomats -============ -Up to version 0.31.12, Elves only sent Diplomats to your fortress to propose -tree cutting quotas due to a bug; once that bug was fixed, Elves stopped caring -about excess tree cutting. This command adds a Diplomat position to all Elven -civilizations, allowing them to negotiate tree cutting quotas (and allowing you -to violate them and potentially start wars) in case you haven't already modified -your raws accordingly. - -fixmerchants -============ -This command adds the Guild Representative position to all Human civilizations, -allowing them to make trade agreements (just as they did back in 0.28.181.40d -and earlier) in case you haven't already modified your raws accordingly. - -fixveins -======== -Removes invalid references to mineral inclusions and restores missing ones. -Use this if you broke your embark with tools like tiletypes, or if you -accidentally placed a construction on top of a valuable mineral floor. +:: -fixwagons -========= -Due to a bug in all releases of version 0.31, merchants no longer bring wagons -with their caravans. This command re-enables them for all appropriate -civilizations. + range 10 10 1 -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. +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. -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. +For more details, see the 'help' command while using this. -Options -------- -:-t: Select trees only (exclude shrubs) -:-s: Select shrubs only (exclude trees) -:-c: Clear designations instead of setting them -:-x: Apply selected action to all plants except those specified (invert - selection) +tiletypes-commands +------------------ +Runs tiletypes commands, separated by ;. This makes it possible to change +tiletypes modes from a hotkey. -Specifying both -t and -s will have no effect. If no plant IDs are specified, -all valid plant IDs will be listed. +tiletypes-here +-------------- +Apply the current tiletypes options at the in-game cursor position, including +the brush. Can be used from a hotkey. -tidlers -======= -Toggle between all possible positions where the idlers count can be placed. +tiletypes-here-point +-------------------- +Apply the current tiletypes options at the in-game cursor position to a single +tile. Can be used from a hotkey. -twaterlvl -========= -Toggle between displaying/not displaying liquid depth as numbers. +tubefill +-------- +Fills all the adamantine veins again. Veins that were empty will be filled in +too, but might still trigger a demon invasion (this is a known bug). -job -=== -Command for general job query and manipulation. +extirpate +--------- +A tool for getting rid of trees and shrubs. By default, it only kills +a tree/shrub under the cursor. The plants are turned into ashes instantly. Options: - * no extra options - Print details of the current job. The job can be selected - in a workshop, or the unit/jobs screen. - * list - Print details of all jobs in the selected workshop. - * item-material <item-idx> <material[:subtoken]> - Replace the exact material - id in the job item. - * item-type <item-idx> <type[:subtype]> - Replace the exact item type id in - the job item. -job-material -============ -Alter the material of the selected job. + :shrubs: affect all shrubs on the map + :trees: affect all trees on the map + :all: affect every plant! -Invoked as: job-material <inorganic-token> - -Intended to be used as a keybinding: - * In 'q' mode, when a job is highlighted within a workshop or furnace, - changes the material of the job. Only inorganic materials can be used - in this mode. - * In 'b' mode, during selection of building components positions the cursor - over the first available choice with the matching material. - -job-duplicate -============= -Duplicate the selected job in a workshop: - * In 'q' mode, when a job is highlighted within a workshop or furnace building, - instantly duplicates the job. - -keybinding -========== - -Manages DFHack keybindings. +grow +---- +Makes all saplings present on the map grow into trees (almost) instantly. -Currently it supports any combination of Ctrl/Alt/Shift with F1-F9, or A-Z. +immolate +-------- +Very similar to extirpate, but additionally sets the plants on fire. The fires +can and *will* spread ;) -Options +regrass ------- -: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. +Regrows grass. Not much to it ;) -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. +weather +------- +Prints the current weather map by default. -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). +Also lets you change the current weather to 'clear sky', 'rainy' or 'snowing'. -For more information, refer to the command's internal help. +Options: -.. note:: + :snow: make it snow everywhere. + :rain: make it rain. + :clear: clear the sky. - Spawning and deleting liquids can F up pathing data and - temperatures (creating heat traps). You've been warned. -liquids-here -============ -Run the liquid spawner with the current/last settings made in liquids (if no -settings in liquids were made it paints a point of 7/7 magma by default). +Map inspection +============== -Intended to be used as keybinding. Requires an active in-game cursor. +cursecheck +---------- +Checks a single map tile or the whole map/world for cursed creatures (ghosts, +vampires, necromancers, werebeasts, zombies). -mode -==== -This command lets you see and change the game mode directly. -Not all combinations are good for every situation and most of them will -produce undesirable results. There are a few good ones though. +With an active in-game cursor only the selected tile will be observed. +Without a cursor the whole map will be checked. -.. admonition:: Example +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". - You are in fort game mode, managing your fortress and paused. - You switch to the arena game mode, *assume control of a creature* and then - switch to adventure game mode(1). - You just lost a fortress and gained an adventurer. - You could also do this. - You are in fort game mode, managing your fortress and paused at the esc menu. - You switch to the adventure game mode, then use Dfusion to *assume control of a creature* and then - save or retire. - You just created a returnable mountain home and gained an adventurer. +Options: + :detail: Print full name, date of birth, date of curse and some status + info (some vampires might use fake identities in-game, though). + :nick: Set the type of curse as nickname (does not always show up + in-game, some vamps don't like nicknames). + :all: Include dead and passive cursed creatures (can result in a quite + long list after having FUN with necromancers). + :verbose: Print all curse tags (if you really want to know it all). -I take no responsibility of anything that happens as a result of using this tool +Examples: -extirpate -========= -A tool for getting rid of trees and shrubs. By default, it only kills -a tree/shrub under the cursor. The plants are turned into ashes instantly. + ``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). -Options -------- -:shrubs: affect all shrubs on the map -:trees: affect all trees on the map -:all: affect every plant! +.. note:: -grow -==== -Makes all saplings present on the map grow into trees (almost) instantly. + * If you do a full search (with the option "all") former ghosts will show up + with the cursetype "unknown" because their ghostly flag is not set + anymore. But if you happen to find a living/active creature with cursetype + "unknown" please report that in the dfhack thread on the modding forum or + per irc. This is likely to happen with mods which introduce new types + of curses, for example. -immolate -======== -Very similar to extirpate, but additionally sets the plants on fire. The fires -can and *will* spread ;) +flows +----- +A tool for checking how many tiles contain flowing liquids. If you suspect that +your magma sea leaks into HFS, you can use this tool to be sure without +revealing the map. probe -===== +----- Can be used to determine tile properties like temperature. prospect -======== +-------- Prints a big list of all the present minerals and plants. By default, only the visible part of the map is scanned. -Options -------- -:all: Scan the whole map, as if it was revealed. -:value: Show material value in the output. Most useful for gems. -:hell: Show the Z range of HFS tubes. Implies 'all'. +Options: + + :all: Scan the whole map, as if it was revealed. + :value: Show material value in the output. Most useful for gems. + :hell: Show the Z range of HFS tubes. Implies 'all'. Pre-embark estimate -------------------- -If called during the embark selection screen, displays an estimate of layer -stone availability. If the 'all' option is specified, also estimates veins. -The estimate is computed either for 1 embark tile of the blinking biome, or -for all tiles of the embark rectangle. +................... -Options -------- -:all: processes all tiles, even hidden ones. +If prospect is called during the embark selection screen, it displays an estimate of +layer stone availability. -regrass -======= -Regrows grass. Not much to it ;) +.. note:: -rename -====== -Allows renaming various things. + 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 -------- -:rename squad <index> "name": Rename squad by index to 'name'. -:rename hotkey <index> \"name\": Rename hotkey by index. This allows assigning - longer commands to the DF hotkeys. -:rename unit "nickname": Rename a unit/creature highlighted in the DF user - interface. -:rename unit-profession "custom profession": Change proffession name of the - highlighted unit/creature. +Options: + + :all: Also estimate vein mineral amounts. reveal -====== +------ This reveals the map. By default, HFS will remain hidden so that the demons don't spawn. You can use 'reveal hell' to reveal everything. With hell revealed, you won't be able to unpause until you hide the map again. If you really want @@ -719,167 +647,325 @@ Reveal also works in adventure mode, but any of its effects are negated once you move. When you use it this way, you don't need to run 'unreveal'. unreveal -======== +-------- Reverts the effects of 'reveal'. revtoggle -========= +--------- Switches between 'reveal' and 'unreveal'. revflood -======== +-------- This command will hide the whole map and then reveal all the tiles that have a path to the in-game cursor. revforget -========= +--------- When you use reveal, it saves information about what was/wasn't visible before revealing everything. Unreveal uses this information to hide things again. This command throws away the information. For example, use in cases where you abandoned with the fort revealed and no longer want the data. -lair -==== -This command allows you to mark the map as 'monster lair', preventing item -scatter on abandon. When invoked as 'lair reset', it does the opposite. +showmood +-------- +Shows all items needed for the currently active strange mood. -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) +Designations +============ -seedwatch -========= -Tool for turning cooking of seeds and plants on/off depending on how much you -have of them. +burrow +------ +Miscellaneous burrow control. Allows manipulating burrows and automated burrow +expansion while digging. -See 'seedwatch help' for detailed description. +Options: -showmood -======== -Shows all items needed for the currently active strange mood. + **enable feature ...** + Enable features of the plugin. + **disable feature ...** + Disable features of the plugin. + **clear-unit burrow burrow ...** + Remove all units from the burrows. + **clear-tiles burrow burrow ...** + Remove all tiles from the burrows. + **set-units target-burrow src-burrow ...** + Clear target, and adds units from source burrows. + **add-units target-burrow src-burrow ...** + Add units from the source burrows to the target. + **remove-units target-burrow src-burrow ...** + Remove units in source burrows from the target. + **set-tiles target-burrow src-burrow ...** + Clear target and adds tiles from the source burrows. + **add-tiles target-burrow src-burrow ...** + Add tiles from the source burrows to the target. + **remove-tiles target-burrow src-burrow ...** + Remove tiles in source burrows from the target. + + For these three options, in place of a source burrow it is + possible to use one of the following keywords: ABOVE_GROUND, + SUBTERRANEAN, INSIDE, OUTSIDE, LIGHT, DARK, HIDDEN, REVEALED + +Features: + + :auto-grow: When a wall inside a burrow with a name ending in '+' is dug + out, the burrow is extended to newly-revealed adjacent walls. + This final '+' may be omitted in burrow name args of commands above. + Digging 1-wide corridors with the miner inside the burrow is SLOW. -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. +digv +---- +Designates a whole vein for digging. Requires an active in-game cursor placed +over a vein tile. With the 'x' option, it will traverse z-levels (putting stairs +between the same-material tiles). -ssense / stonesense -=================== -An isometric visualizer that runs in a second window. This requires working -graphics acceleration and at least a dual core CPU (otherwise it will slow -down DF). +digvx +----- +A permanent alias for 'digv x'. -All the data resides in the 'stonesense' directory. For detailed instructions, -see stonesense/README.txt +digl +---- +Designates layer stone for digging. Requires an active in-game cursor placed +over a layer stone tile. With the 'x' option, it will traverse z-levels +(putting stairs between the same-material tiles). With the 'undo' option it +will remove the dig designation instead (if you realize that digging out a 50 +z-level deep layer was not such a good idea after all). -Compatible with Windows > XP SP3 and most modern Linux distributions. +diglx +----- +A permanent alias for 'digl x'. -Older versions, support and extra graphics can be found in the bay12 forum -thread: http://www.bay12forums.com/smf/index.php?topic=43260.0 +digexp +------ +This command can be used for exploratory mining. -Some additional resources: -http://df.magmawiki.com/index.php/Utility:Stonesense/Content_repository +See: http://df.magmawiki.com/index.php/DF2010:Exploratory_mining -tiletypes -========= -Can be used for painting map tiles and is an interactive command, much like -liquids. +There are two variables that can be set: pattern and filter. -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. +Patterns: -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. + :diag5: diagonals separated by 5 tiles + :diag5r: diag5 rotated 90 degrees + :ladder: A 'ladder' pattern + :ladderr: ladder rotated 90 degrees + :clear: Just remove all dig designations + :cross: A cross, exactly in the middle of the map. -The properties of filter and paint can be partially defined. This means that -you can for example do something like this: +Filters: -:: + :all: designate whole z-level + :hidden: designate only hidden tiles of z-level (default) + :designated: Take current designation and apply pattern to it. - filter material STONE - filter shape FORTIFICATION - paint shape FLOOR +After you have a pattern set, you can use 'expdig' to apply it again. -This will turn all stone fortifications into floors, preserving the material. +Examples: -Or this: -:: + designate the diagonal 5 patter over all hidden tiles: + * expdig diag5 hidden + apply last used pattern and filter: + * expdig + Take current designations and replace them with the ladder pattern: + * expdig ladder designated - filter shape FLOOR - filter material MINERAL - paint shape WALL +digcircle +--------- +A command for easy designation of filled and hollow circles. +It has several types of options. -Turning mineral vein floors back into walls. +Shape: -The tool also allows tweaking some tile flags: + :hollow: Set the circle to hollow (default) + :filled: Set the circle to filled + :#: Diameter in tiles (default = 0, does nothing) -Or this: +Action: -:: + :set: Set designation (default) + :unset: Unset current designation + :invert: Invert designations already present - paint hidden 1 - paint hidden 0 +Designation types: -This will hide previously revealed tiles (or show hidden with the 0 option). + :dig: Normal digging designation (default) + :ramp: Ramp digging + :ustair: Staircase up + :dstair: Staircase down + :xstair: Staircase up/down + :chan: Dig channel -Any paint or filter option (or the entire paint or filter) can be disabled entirely by using the ANY keyword: +After you have set the options, the command called with no options +repeats with the last selected parameters. -:: +Examples: - paint hidden ANY - paint shape ANY - filter material any - filter shape any - filter any +* 'digcircle filled 3' = Dig a filled circle with radius = 3. +* 'digcircle' = Do it again. -You can use several different brushes for painting tiles: - * Point. (point) - * Rectangular range. (range) - * A column ranging from current cursor to the first solid tile above. (column) - * DF map block - 16x16 tiles, in a regular grid. (block) + +filltraffic +----------- +Set traffic designations using flood-fill starting at the cursor. + +Traffic Type Codes: + + :H: High Traffic + :N: Normal Traffic + :L: Low Traffic + :R: Restricted Traffic + +Other Options: + + :X: Fill accross z-levels. + :B: Include buildings and stockpiles. + :P: Include empty space. Example: -:: + 'filltraffic H' - When used in a room with doors, it will set traffic to HIGH in just that room. - range 10 10 1 +alltraffic +---------- +Set traffic designations for every single tile of the map (useful for resetting traffic designations). -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. +Traffic Type Codes: -For more details, see the 'help' command while using this. + :H: High Traffic + :N: Normal Traffic + :L: Low Traffic + :R: Restricted Traffic -tiletypes-commands -================== -Runs tiletypes commands, separated by ;. This makes it possible to change -tiletypes modes from a hotkey. +Example: -tiletypes-here -============== -Apply the current tiletypes options at the in-game cursor position, including -the brush. Can be used from a hotkey. + 'alltraffic N' - Set traffic to 'normal' for all tiles. -tiletypes-here-point -==================== -Apply the current tiletypes options at the in-game cursor position to a single -tile. Can be used from a hotkey. +getplants +--------- +This tool allows plant gathering and tree cutting by RAW ID. Specify the types +of trees to cut down and/or shrubs to gather by their plant names, separated +by spaces. + +Options: + + :-t: Select trees only (exclude shrubs) + :-s: Select shrubs only (exclude trees) + :-c: Clear designations instead of setting them + :-x: Apply selected action to all plants except those specified (invert + selection) + +Specifying both -t and -s will have no effect. If no plant IDs are specified, +all valid plant IDs will be listed. + + +Cleanup and garbage disposal +============================ + +clean +----- +Cleans all the splatter that get scattered all over the map, items and +creatures. In an old fortress, this can significantly reduce FPS lag. It can +also spoil your !!FUN!!, so think before you use it. + +Options: + + :map: Clean the map tiles. By default, it leaves mud and snow alone. + :units: Clean the creatures. Will also clean hostiles. + :items: Clean all the items. Even a poisoned blade. + +Extra options for 'map': + + :mud: Remove mud in addition to the normal stuff. + :snow: Also remove snow coverings. + +spotclean +--------- +Works like 'clean map snow mud', but only for the tile under the cursor. Ideal +if you want to keep that bloody entrance 'clean map' would clean up. + +autodump +-------- +This utility lets you quickly move all items designated to be dumped. +Items are instantly moved to the cursor position, the dump flag is unset, +and the forbid flag is set, as if it had been dumped normally. +Be aware that any active dump item tasks still point at the item. + +Cursor must be placed on a floor tile so the items can be dumped there. + +Options: + + :destroy: Destroy instead of dumping. Doesn't require a cursor. + :destroy-here: Destroy items only under the cursor. + :visible: Only process items that are not hidden. + :hidden: Only process hidden items. + :forbidden: Only process forbidden items (default: only unforbidden). + +autodump-destroy-here +--------------------- +Destroy items marked for dumping under cursor. Identical to autodump +destroy-here, but intended for use as keybinding. + +autodump-destroy-item +--------------------- +Destroy the selected item. The item may be selected in the 'k' list, or inside +a container. If called again before the game is resumed, cancels destroy. + +cleanowned +---------- +Confiscates items owned by dwarfs. By default, owned food on the floor +and rotten items are confistacted and dumped. + +Options: + + :all: confiscate all owned items + :scattered: confiscated and dump all items scattered on the floor + :x: confiscate/dump items with wear level 'x' and more + :X: confiscate/dump items with wear level 'X' and more + :dryrun: a dry run. combine with other options to see what will happen + without it actually happening. + +Example: + + ``cleanowned scattered X`` + This will confiscate rotten and dropped food, garbage on the floors and any + worn items with 'X' damage and above. + + + +Bugfixes +======== + +drybuckets +---------- +This utility removes water from all buckets in your fortress, allowing them to be safely used for making lye. + +fixdiplomats +------------ +Up to version 0.31.12, Elves only sent Diplomats to your fortress to propose +tree cutting quotas due to a bug; once that bug was fixed, Elves stopped caring +about excess tree cutting. This command adds a Diplomat position to all Elven +civilizations, allowing them to negotiate tree cutting quotas (and allowing you +to violate them and potentially start wars) in case you haven't already modified +your raws accordingly. + +fixmerchants +------------ +This command adds the Guild Representative position to all Human civilizations, +allowing them to make trade agreements (just as they did back in 0.28.181.40d +and earlier) in case you haven't already modified your raws accordingly. + +fixveins +-------- +Removes invalid references to mineral inclusions and restores missing ones. +Use this if you broke your embark with tools like tiletypes, or if you +accidentally placed a construction on top of a valuable mineral floor. tweak -===== -Contains various tweaks for minor bugs (currently just one). +----- +Contains various tweaks for minor bugs. + +One-shot subcommands: -Options -------- :clear-missing: Remove the missing status from the selected unit. This allows engraving slabs for ghostly, but not yet found, creatures. @@ -908,136 +994,166 @@ Options for slaughter. Grabbing wagons results in some funny spam, then they are scuttled. -tubefill -======== -Fills all the adamantine veins again. Veins that were empty will be filled in -too, but might still trigger a demon invasion (this is a known bug). +Subcommands that persist until disabled or DF quit: + +:stable-cursor: Saves the exact cursor position between t/q/k/d/etc menus of dwarfmode. +:patrol-duty: Makes Train orders not count as patrol duty to stop unhappy thoughts. + Does NOT fix the problem when soldiers go off-duty (i.e. civilian). +:readable-build-plate: Fixes rendering of creature weight limits in pressure plate build menu. +:stable-temp: Fixes performance bug 6012 by squashing jitter in temperature updates. + In very item-heavy forts with big stockpiles this can improve FPS by 50-100% +:fast-heat: Further improves temperature update performance by ensuring that 1 degree + of item temperature is crossed in no more than specified number of frames + when updating from the environment temperature. This reduces the time it + takes for stable-temp to stop updates again when equilibrium is disturbed. +:fix-dimensions: Fixes subtracting small amount of thread/cloth/liquid from a stack + by splitting the stack and subtracting from the remaining single item. + This is a necessary addition to the binary patch in bug 808. +:advmode-contained: Works around bug 6202, i.e. custom reactions with container inputs + in advmode. The issue is that the screen tries to force you to select + the contents separately from the container. This forcefully skips child + reagents. +:fast-trade: Makes Shift-Enter in the Move Goods to Depot and Trade screens select + the current item (fully, in case of a stack), and scroll down one line. +: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. +:military-color-assigned: Color squad candidates already assigned to other squads in brown/green + to make them stand out more in the list. + + +Mode switch and reclaim +======================= -digv -==== -Designates a whole vein for digging. Requires an active in-game cursor placed -over a vein tile. With the 'x' option, it will traverse z-levels (putting stairs -between the same-material tiles). +lair +---- +This command allows you to mark the map as 'monster lair', preventing item +scatter on abandon. When invoked as 'lair reset', it does the opposite. -digvx -===== -A permanent alias for 'digv x'. +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'. -digl -==== -Designates layer stone for digging. Requires an active in-game cursor placed -over a layer stone tile. With the 'x' option, it will traverse z-levels -(putting stairs between the same-material tiles). With the 'undo' option it -will remove the dig designation instead (if you realize that digging out a 50 -z-level deep layer was not such a good idea after all). +Options: -diglx -===== -A permanent alias for 'digl x'. + :lair: Mark the map as monster lair + :lair reset: Mark the map as ordinary (not lair) -digexp -====== -This command can be used for exploratory mining. +mode +---- +This command lets you see and change the game mode directly. +Not all combinations are good for every situation and most of them will +produce undesirable results. There are a few good ones though. -See: http://df.magmawiki.com/index.php/DF2010:Exploratory_mining +.. admonition:: Example -There are two variables that can be set: pattern and filter. + You are in fort game mode, managing your fortress and paused. + You switch to the arena game mode, *assume control of a creature* and then + switch to adventure game mode(1). + You just lost a fortress and gained an adventurer. + You could also do this. + You are in fort game mode, managing your fortress and paused at the esc menu. + You switch to the adventure game mode, then use Dfusion to *assume control of a creature* and then + save or retire. + You just created a returnable mountain home and gained an adventurer. -Patterns: ---------- -:diag5: diagonals separated by 5 tiles -:diag5r: diag5 rotated 90 degrees -:ladder: A 'ladder' pattern -:ladderr: ladder rotated 90 degrees -:clear: Just remove all dig designations -:cross: A cross, exactly in the middle of the map. -Filters: --------- -:all: designate whole z-level -:hidden: designate only hidden tiles of z-level (default) -:designated: Take current designation and apply pattern to it. +I take no responsibility of anything that happens as a result of using this tool -After you have a pattern set, you can use 'expdig' to apply it again. -Examples: ---------- -designate the diagonal 5 patter over all hidden tiles: - * expdig diag5 hidden -apply last used pattern and filter: - * expdig -Take current designations and replace them with the ladder pattern: - * expdig ladder designated +Visualizer and data export +========================== -digcircle -========= -A command for easy designation of filled and hollow circles. -It has several types of options. +ssense / stonesense +------------------- +An isometric visualizer that runs in a second window. This requires working +graphics acceleration and at least a dual core CPU (otherwise it will slow +down DF). -Shape: --------- -:hollow: Set the circle to hollow (default) -:filled: Set the circle to filled -:#: Diameter in tiles (default = 0, does nothing) +All the data resides in the 'stonesense' directory. For detailed instructions, +see stonesense/README.txt -Action: -------- -:set: Set designation (default) -:unset: Unset current designation -:invert: Invert designations already present +Compatible with Windows > XP SP3 and most modern Linux distributions. -Designation types: ------------------- -:dig: Normal digging designation (default) -:ramp: Ramp digging -:ustair: Staircase up -:dstair: Staircase down -:xstair: Staircase up/down -:chan: Dig channel +Older versions, support and extra graphics can be found in the bay12 forum +thread: http://www.bay12forums.com/smf/index.php?topic=43260.0 -After you have set the options, the command called with no options -repeats with the last selected parameters. +Some additional resources: +http://df.magmawiki.com/index.php/Utility:Stonesense/Content_repository -Examples: +mapexport --------- -* 'digcircle filled 3' = Dig a filled circle with radius = 3. -* 'digcircle' = Do it again. +Export the current loaded map as a file. This will be eventually usable +with visualizers. -weather -======= -Prints the current weather map by default. +dwarfexport +----------- +Export dwarves to RuneSmith-compatible XML. -Also lets you change the current weather to 'clear sky', 'rainy' or 'snowing'. + +Job management +============== + +job +--- +Command for general job query and manipulation. Options: --------- -:snow: make it snow everywhere. -:rain: make it rain. -:clear: clear the sky. + *no extra options* + Print details of the current job. The job can be selected + in a workshop, or the unit/jobs screen. + **list** + Print details of all jobs in the selected workshop. + **item-material <item-idx> <material[:subtoken]>** + Replace the exact material id in the job item. + **item-type <item-idx> <type[:subtype]>** + Replace the exact item type id in the job item. + +job-material +------------ +Alter the material of the selected job. + +Invoked as:: + + job-material <inorganic-token> + +Intended to be used as a keybinding: + + * In 'q' mode, when a job is highlighted within a workshop or furnace, + changes the material of the job. Only inorganic materials can be used + in this mode. + * In 'b' mode, during selection of building components positions the cursor + over the first available choice with the matching material. + +job-duplicate +------------- +Duplicate the selected job in a workshop: + * In 'q' mode, when a job is highlighted within a workshop or furnace building, + instantly duplicates the job. workflow -======== +-------- Manage control of repeat jobs. -Usage ------ -``workflow enable [option...], workflow disable [option...]`` +Usage: + + ``workflow enable [option...], workflow disable [option...]`` If no options are specified, enables or disables the plugin. Otherwise, enables or disables any of the following options: - drybuckets: Automatically empty abandoned water buckets. - auto-melt: Resume melt jobs when there are objects to melt. -``workflow jobs`` + ``workflow jobs`` List workflow-controlled jobs (if in a workshop, filtered by it). -``workflow list`` + ``workflow list`` List active constraints, and their job counts. -``workflow count <constraint-spec> <cnt-limit> [cnt-gap], workflow amount <constraint-spec> <cnt-limit> [cnt-gap]`` + ``workflow count <constraint-spec> <cnt-limit> [cnt-gap], workflow amount <constraint-spec> <cnt-limit> [cnt-gap]`` Set a constraint. The first form counts each stack as only 1 item. -``workflow unlimit <constraint-spec>`` + ``workflow unlimit <constraint-spec>`` Delete a constraint. 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. @@ -1050,7 +1166,8 @@ the frequency of jobs being toggled. Constraint examples -------------------- +................... + Keep metal bolts within 900-1000, and wood/bone within 150-200. :: @@ -1091,73 +1208,76 @@ Make sure there are always 80-100 units of dimple dye. on the Mill Plants job to MUSHROOM_CUP_DIMPLE using the 'job item-material' command. -mapexport -========= -Export the current loaded map as a file. This will be eventually usable -with visualizers. -dwarfexport -=========== -Export dwarves to RuneSmith-compatible XML. +Fortress activity management +============================ + +seedwatch +--------- +Tool for turning cooking of seeds and plants on/off depending on how much you +have of them. + +See 'seedwatch help' for detailed description. zone -==== +---- Helps a bit with managing activity zones (pens, pastures and pits) and cages. Options: --------- -:set: Set zone or cage under cursor as default for future assigns. -:assign: Assign unit(s) to the pen or pit marked with the 'set' command. + + :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 + :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 + :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 + :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. + :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. + + :all: Process all units (to be used with additional filters). + :count: Must be followed by a number. Process only n units (to be used + with additional filters). + :unassigned: Not assigned to zone, chain or built cage. + :minage: Minimum age. Must be followed by number. + :maxage: Maximum age. Must be followed by number. + :race: Must be followed by a race RAW ID (e.g. BIRD_TURKEY, ALPACA, + etc). Negatable. + :caged: In a built cage. Negatable. + :own: From own civilization. Negatable. + :merchant: Is a merchant / belongs to a merchant. Should only be used for + pitting, not for stealing animals (slaughter should work). + :war: Trained war creature. Negatable. + :hunting: Trained hunting creature. Negatable. + :tamed: Creature is tame. Negatable. + :trained: Creature is trained. Finds war/hunting creatures as well as + creatures who have a training level greater than 'domesticated'. + If you want to specifically search for war/hunting creatures use + 'war' or 'hunting' Negatable. + :trainablewar: Creature can be trained for war (and is not already trained for + war/hunt). Negatable. + :trainablehunt: Creature can be trained for hunting (and is not already trained + for war/hunt). Negatable. + :male: Creature is male. Negatable. + :female: Creature is female. Negatable. + :egglayer: Race lays eggs. Negatable. + :grazer: Race is a grazer. Negatable. + :milkable: Race is milkable. Negatable. Usage with single units ------------------------ +....................... + One convenient way to use the zone tool is to bind the command 'zone assign' to a hotkey, maybe also the command 'zone set'. Place the in-game cursor over a pen/pasture or pit, use 'zone set' to mark it. Then you can select units @@ -1166,7 +1286,8 @@ and use 'zone assign' to assign them to their new home. Allows pitting your own dwarves, by the way. Usage with filters ------------------- +.................. + All filters can be used together with the 'assign' command. Restrictions: It's not possible to assign units who are inside built cages @@ -1187,14 +1308,16 @@ are not properly added to your own stocks; slaughtering them should work). Most filters can be negated (e.g. 'not grazer' -> race is not a grazer). Mass-renaming -------------- +............. + Using the 'nick' command you can set the same nickname for multiple units. If used without 'assign', 'all' or 'count' it will rename all units in the current default target zone. Combined with 'assign', 'all' or 'count' (and further optional filters) it will rename units matching the filter conditions. Cage zones ----------- +.......... + Using the 'tocages' command you can assign units to a set of cages, for example a room next to your butcher shop(s). They will be spread evenly among available cages to optimize hauling to and butchering from them. For this to work you need @@ -1205,7 +1328,8 @@ 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. @@ -1228,7 +1352,7 @@ Examples on the current default zone. autonestbox -=========== +----------- Assigns unpastured female egg-layers to nestbox zones. Requires that you create pen/pasture zones above nestboxes. If the pen is bigger than 1x1 the nestbox must be in the top left corner. Only 1 unit will be assigned per pen, regardless @@ -1240,15 +1364,15 @@ 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. + + :start: Start running every X frames (df simulation ticks). + Default: X=6000, which would be every 60 seconds at 100fps. + :stop: Stop running automatically. + :sleep: Must be followed by number X. Changes the timer to sleep X + frames between runs. autobutcher -=========== +----------- Assigns lifestock for slaughter once it reaches a specific count. Requires that you add the target race(s) to a watch list. Only tame units will be processed. @@ -1267,41 +1391,41 @@ If you don't set any target count the following default will be used: 1 male kid, 5 female kids, 1 male adult, 5 female adults. Options: --------- -:start: Start running every X frames (df simulation ticks). - Default: X=6000, which would be every 60 seconds at 100fps. -:stop: Stop running automatically. -:sleep: Must be followed by number X. Changes the timer to sleep - X frames between runs. -:watch R: Start watching a race. R can be a valid race RAW id (ALPACA, - BIRD_TURKEY, etc) or a list of ids seperated by spaces or - the keyword 'all' which affects all races on your current - watchlist. -:unwatch R: Stop watching race(s). The current target settings will be - remembered. R can be a list of ids or the keyword 'all'. -:forget R: Stop watching race(s) and forget it's/their target settings. - R can be a list of ids or the keyword 'all'. -:autowatch: Automatically adds all new races (animals you buy from merchants, - tame yourself or get from migrants) to the watch list using - default target count. -:noautowatch: Stop auto-adding new races to the watchlist. -:list: Print the current status and watchlist. -:list_export: Print status and watchlist in a format which can be used - to import them to another savegame (see notes). -:target fk mk fa ma R: Set target count for specified race(s). - fk = number of female kids, - mk = number of male kids, - fa = number of female adults, - ma = number of female adults. - R can be a list of ids or the keyword 'all' or 'new'. - R = 'all': change target count for all races on watchlist - and set the new default for the future. R = 'new': don't touch - current settings on the watchlist, only set the new default - for future entries. -:example: Print some usage examples. + + :start: Start running every X frames (df simulation ticks). + Default: X=6000, which would be every 60 seconds at 100fps. + :stop: Stop running automatically. + :sleep: Must be followed by number X. Changes the timer to sleep + X frames between runs. + :watch R: Start watching a race. R can be a valid race RAW id (ALPACA, + BIRD_TURKEY, etc) or a list of ids seperated by spaces or + the keyword 'all' which affects all races on your current + watchlist. + :unwatch R: Stop watching race(s). The current target settings will be + remembered. R can be a list of ids or the keyword 'all'. + :forget R: Stop watching race(s) and forget it's/their target settings. + R can be a list of ids or the keyword 'all'. + :autowatch: Automatically adds all new races (animals you buy from merchants, + tame yourself or get from migrants) to the watch list using + default target count. + :noautowatch: Stop auto-adding new races to the watchlist. + :list: Print the current status and watchlist. + :list_export: Print status and watchlist in a format which can be used + to import them to another savegame (see notes). + :target fk mk fa ma R: Set target count for specified race(s). + fk = number of female kids, + mk = number of male kids, + fa = number of female adults, + ma = number of female adults. + R can be a list of ids or the keyword 'all' or 'new'. + R = 'all': change target count for all races on watchlist + and set the new default for the future. R = 'new': don't touch + current settings on the watchlist, only set the new default + for future entries. + :example: Print some usage examples. Examples: ---------- + You want to keep max 7 kids (4 female, 3 male) and max 3 adults (2 female, 1 male) of the race alpaca. Once the kids grow up the oldest adults will get slaughtered. Excess kids will get slaughtered starting with the youngest @@ -1333,8 +1457,8 @@ add some new races with 'watch'. If you simply want to stop it completely use autobutcher unwatch ALPACA CAT -Note: ------ +**Note:** + Settings and watchlist are stored in the savegame, so that you can have different settings for each world. If you want to copy your watchlist to another savegame you can use the command list_export: @@ -1348,7 +1472,7 @@ another savegame you can use the command list_export: autolabor -========= +--------- Automatically manage dwarf labors. When enabled, autolabor periodically checks your dwarves and enables or @@ -1362,6 +1486,101 @@ also tries to have dwarves specialize in specific skills. For detailed usage information, see 'help autolabor'. +Other +===== + +catsplosion +----------- +Makes cats just *multiply*. It is not a good idea to run this more than once or +twice. + +dfusion +------- +This is the DFusion lua plugin system by warmist/darius, running as a DFHack plugin. + +See the bay12 thread for details: http://www.bay12forums.com/smf/index.php?topic=69682.15 + +Confirmed working DFusion plugins: + +:simple_embark: allows changing the number of dwarves available on embark. + +.. note:: + + * Some of the DFusion plugins aren't completely ported yet. This can lead to crashes. + * This is currently working only on Windows. + * The game will be suspended while you're using dfusion. Don't panic when it doen't respond. + + +======= +Scripts +======= + +Lua or ruby scripts placed in the hack/scripts/ directory are considered for +execution as if they were native DFHack commands. They are listed at the end +of the 'ls' command output. + +Note: scripts in subdirectories of hack/scripts/ can still be called, but will +only be listed by ls if called as 'ls -a'. This is intended as a way to hide +scripts that are obscure, developer-oriented, or should be used as keybindings. + +Some notable scripts: + +fix/* +===== + +Scripts in this subdirectory fix various bugs and issues, some of them obscure. + +* fix/dead-units + + Removes uninteresting dead units from the unit list. Doesn't seem to give any + noticeable performance gain, but migrants normally stop if the unit list grows + to around 3000 units, and this script reduces it back. + +* fix/population-cap + + Run this after every migrant wave to ensure your population cap is not exceeded. + The issue with the cap is that it is compared to the population number reported + by the last caravan, so once it drops below the cap, migrants continue to come + until that number is updated again. + +* fix/stable-temp + + Instantly sets the temperature of all free-lying items to be in equilibrium with + the environment and stops temperature updates. In order to maintain this efficient + state however, use ``tweak stable-temp`` and ``tweak fast-heat``. + +* fix/item-occupancy + + Diagnoses and fixes issues with nonexistant 'items occupying site', usually + caused by autodump bugs or other hacking mishaps. + + +gui/* +===== + +Scripts that implement dialogs inserted into the main game window are put in this +directory. + +quicksave +========= + +If called in dwarf mode, makes DF immediately auto-save the game by setting a flag +normally used in seasonal auto-save. + +setfps +====== + +Run ``setfps <number>`` to set the FPS cap at runtime, in case you want to watch +combat in slow motion or something :) + +siren +===== + +Wakes up sleeping units, cancels breaks and stops parties either everywhere, +or in the burrows given as arguments. In return, adds bad thoughts about +noise, tiredness and lack of protection. Also, the units with interrupted +breaks will go on break again a lot sooner. The script is intended for +emergencies, e.g. when a siege appears, and all your military is partying. growcrops ========= @@ -1414,16 +1633,16 @@ using this mode for birds is not recommanded.) Will target any unit on a revealed tile of the map, including ambushers. -Ex: -:: +Ex:: + slayrace gob -To kill a single creature, select the unit with the 'v' cursor and: -:: +To kill a single creature, select the unit with the 'v' cursor and:: + slayrace him -To purify all elves on the map with fire (may have side-effects): -:: +To purify all elves on the map with fire (may have side-effects):: + slayrace elve magma @@ -1435,8 +1654,8 @@ This script registers a map tile as a magma source, and every 12 game ticks that tile receives 1 new unit of flowing magma. 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 -:: +flow-passable tile, and not too high in the sky) and call:: + magmasource here To add more than 1 unit everytime, call the command again. @@ -1446,3 +1665,327 @@ To remove all placed sources, call ``magmasource stop``. With no argument, this command shows an help message and list existing sources. + +digfort +======= +A script to designate an area for digging according to a plan in csv format. + +This script, inspired from quickfort, can designate an area for digging. +Your plan should be stored in a .csv file like this:: + + # this is a comment + d;d;u;d;d;skip this tile;d + d;d;d;i + +Available tile shapes are named after the 'dig' menu shortcuts: +``d`` for dig, ``u`` for upstairs, ``d`` downstairs, ``i`` updown, +``h`` channel, ``r`` upward ramp, ``x`` remove designation. +Unrecognized characters are ignored (eg the 'skip this tile' in the sample). + +Empty lines and data after a ``#`` are ignored as comments. +To skip a row in your design, use a single ``;``. + +The script takes the plan filename, starting from the root df folder. + +superdwarf +========== +Similar to fastdwarf, per-creature. + +To make any creature superfast, target it ingame using 'v' and:: + + superdwarf add + +Other options available: ``del``, ``clear``, ``list``. + +This plugin also shortens the 'sleeping' and 'on break' periods of targets. + +drainaquifer +============ +Remove all 'aquifer' tag from the map blocks. Irreversible. + +deathcause +========== +Focus a body part ingame, and this script will display the cause of death of +the creature. + + +======================= +In-game interface tools +======================= + +These tools work by displaying dialogs or overlays in the game window, and +are mostly implemented by lua scripts. + + +Dwarf Manipulator +================= + +Implemented by the manipulator plugin. To activate, open the unit screen and +press 'l'. + +This tool implements a Dwarf Therapist-like interface within the game UI. The +far left column displays the unit's Happiness (color-coded based on its +value), and the right half of the screen displays each dwarf's labor settings +and skill levels (0-9 for Dabbling thru Professional, A-E for Great thru Grand +Master, and U-Z for Legendary thru Legendary+5). Cells with red backgrounds +denote skills not controlled by labors. + +Use the arrow keys or number pad to move the cursor around, holding Shift to +move 10 tiles at a time. + +Press the Z-Up (<) and Z-Down (>) keys to move quickly between labor/skill +categories. The numpad Z-Up and Z-Down keys seek to the first or last unit +in the list. + +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, +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 or + profession) 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 or profession to view its properties. +* Right-click on a unit's name or profession to zoom to it. + +Pressing ESC normally returns to the unit screen, but Shift-ESC would exit +directly to the main dwarf mode screen. + + +Liquids +======= + +Implemented by the gui/liquids script. To use, bind to a key and activate in the 'k' mode. + +While active, use the suggested keys to switch the usual liquids parameters, and Enter +to select the target area and apply changes. + + +Mechanisms +========== + +Implemented by the gui/mechanims script. To use, bind to a key and activate in the 'q' mode. + +Lists mechanisms connected to the building, and their links. Navigating the list centers +the view on the relevant linked buildings. + +To exit, press ESC or Enter; ESC recenters on the original building, while Enter leaves +focus on the current one. Shift-Enter has an effect equivalent to pressing Enter, and then +re-entering the mechanisms ui. + + +Rename +====== + +Backed by the rename plugin, the gui/rename 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. + +* ``gui/rename unit-profession`` changes the selected unit's custom profession name. + +The ``building`` or ``unit`` options are automatically assumed when in relevant ui state. + + +Room List +========= + +Implemented by the gui/room-list script. To use, bind to a key and activate in the '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. + + +============= +Behavior Mods +============= + +These plugins, when activated via configuration UI or by detecting certain +structures in RAWs, modify the game engine behavior concerning the target +objects to add features not otherwise present. + + +Siege Engine +============ + +The siege-engine plugin enables siege engines to be linked to stockpiles, and +aimed at an arbitrary rectangular area across Z levels, instead of the original +four directions. Also, catapults can be ordered to load arbitrary objects, not +just stones. + +The configuration front-end to the plugin is implemented by the gui/siege-engine +script. Bind it to a key and activate 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 designations. When a target area is set, the engine projectiles are +aimed at that area, or units within it (this doesn't actually change the original aiming +code, instead the projectile trajectory parameters are rewritten as soon as it appears). + +After setting the target in this way for one engine, you can 'paste' the same area into others +just by pressing 'p' in the main page of this script. The area to paste is kept until you quit +DF, or select another area manually. + +Pressing 't' switches to a mode for selecting a stockpile to take ammo from. + +Exiting from the siege engine script via ESC reverts the view to the state prior to starting +the script. Shift-ESC retains the current viewport, and also exits from the 'q' mode to main +menu. + +.. admonition:: DISCLAIMER + + Siege engines are a very interesting feature, but sadly almost useless in the current state + because they haven't been updated since 2D and can only aim in four directions. This is an + attempt to bring them more up to date until Toady has time to work on it. Actual improvements, + e.g. like making siegers bring their own, are something only Toady can do. + + +Power Meter +=========== + +The power-meter plugin implements a modified pressure plate that detects power being +supplied to gear boxes built in the four adjacent N/S/W/E tiles. + +The configuration front-end is implemented by the gui/power-meter script. Bind it to a +key and activate 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. + + +Steam Engine +============ + +The steam-engine plugin detects custom workshops with STEAM_ENGINE in +their token, and turns them into real steam engines. + +Rationale +--------- + +The vanilla game contains only water wheels and windmills as sources of +power, but windmills give relatively little power, and water wheels require +flowing water, which must either be a real river and thus immovable and +limited in supply, or actually flowing and thus laggy. + +Steam engines are an alternative to water reactors that actually makes +sense, and hopefully doesn't lag. Also, unlike e.g. animal treadmills, +it can be done just by combining existing features of the game engine +in a new way with some glue code and a bit of custom logic. + +Construction +------------ + +The workshop needs water as its input, which it takes via a +passable floor tile below it, like usual magma workshops do. +The magma version also needs magma. + +.. admonition:: ISSUE + + Since this building is a machine, and machine collapse + code cannot be hooked, it would collapse over true open space. + As a loophole, down stair provides support to machines, while + being passable, so use them. + +After constructing the building itself, machines can be connected +to the edge tiles that look like gear boxes. Their exact position +is extracted from the workshop raws. + +.. admonition:: ISSUE + + Like with collapse above, part of the code involved in + machine connection cannot be hooked. As a result, the workshop + can only immediately connect to machine components built AFTER it. + This also means that engines cannot be chained without intermediate + short axles that can be built later than both of the engines. + +Operation +--------- + +In order to operate the engine, queue the Stoke Boiler job (optionally +on repeat). A furnace operator will come, possibly bringing a bar of fuel, +and perform it. As a result, a "boiling water" item will appear +in the 't' view of the workshop. + +.. note:: + + The completion of the job will actually consume one unit + of the appropriate liquids from below the workshop. This means + that you cannot just raise 7 units of magma with a piston and + have infinite power. However, liquid consumption should be slow + enough that water can be supplied by a pond zone bucket chain. + +Every such item gives 100 power, up to a limit of 300 for coal, +and 500 for a magma engine. The building can host twice that +amount of items to provide longer autonomous running. When the +boiler gets filled to capacity, all queued jobs are suspended; +once it drops back to 3+1 or 5+1 items, they are re-enabled. + +While the engine is providing power, steam is being consumed. +The consumption speed includes a fixed 10% waste rate, and +the remaining 90% are applied proportionally to the actual +load in the machine. With the engine at nominal 300 power with +150 load in the system, it will consume steam for actual +300*(10% + 90%*150/300) = 165 power. + +Masterpiece mechanism and chain will decrease the mechanical +power drawn by the engine itself from 10 to 5. Masterpiece +barrel decreases waste rate by 4%. Masterpiece piston and pipe +decrease it by further 4%, and also decrease the whole steam +use rate by 10%. + +Explosions +---------- + +The engine must be constructed using barrel, pipe and piston +from fire-safe, or in the magma version magma-safe metals. + +During operation weak parts get gradually worn out, and +eventually the engine explodes. It should also explode if +toppled during operation by a building destroyer, or a +tantruming dwarf. + +Save files +---------- + +It should be safe to load and view engine-using fortresses +from a DF version without DFHack installed, except that in such +case the engines won't work. However actually making modifications +to them, or machines they connect to (including by pulling levers), +can easily result in inconsistent state once this plugin is +available again. The effects may be as weird as negative power +being generated. + + +Add Spatter +=========== + +This plugin makes reactions with names starting with ``SPATTER_ADD_`` +produce contaminants on the items instead of improvements. The produced +contaminants are immune to being washed away by water or destroyed by +the ``clean items`` command. + +The plugin is intended to give some use to all those poisons that can +be bought from caravans. :) + +To be really useful this needs patches from bug 808, ``tweak fix-dimensions`` +and ``tweak advmode-contained``. diff --git a/Readme.html b/Readme.html index 50ceae99..6155b72c 100644 --- a/Readme.html +++ b/Readme.html @@ -3,8 +3,8 @@ <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> -<meta name="generator" content="Docutils 0.9: http://docutils.sourceforge.net/" /> -<title></title> +<meta name="generator" content="Docutils 0.8.1: http://docutils.sourceforge.net/" /> +<title>DFHack Readme</title> <style type="text/css"> /* @@ -314,11 +314,11 @@ ul.auto-toc { </style> </head> <body> -<div class="document"> - +<div class="document" id="dfhack-readme"> +<h1 class="title">DFHack Readme</h1> <div class="section" id="introduction"> -<h1><a class="toc-backref" href="#id34">Introduction</a></h1> +<h1><a class="toc-backref" href="#id3">Introduction</a></h1> <p>DFHack is a Dwarf Fortress memory access library and a set of basic tools that use it. Tools come in the form of plugins or (not yet) external tools. It is an attempt to unite the various ways tools @@ -326,219 +326,198 @@ access DF memory and allow for easier development of new tools.</p> <div class="contents topic" id="contents"> <p class="topic-title first">Contents</p> <ul class="simple"> -<li><a class="reference internal" href="#introduction" id="id34">Introduction</a></li> -<li><a class="reference internal" href="#getting-dfhack" id="id35">Getting DFHack</a></li> -<li><a class="reference internal" href="#compatibility" id="id36">Compatibility</a></li> -<li><a class="reference internal" href="#installation-removal" id="id37">Installation/Removal</a></li> -<li><a class="reference internal" href="#using-dfhack" id="id38">Using DFHack</a></li> -<li><a class="reference internal" href="#something-doesn-t-work-help" id="id39">Something doesn't work, help!</a></li> -<li><a class="reference internal" href="#the-init-file" id="id40">The init file</a></li> -<li><a class="reference internal" href="#commands" id="id41">Commands</a><ul> -<li><a class="reference internal" href="#adv-bodyswap" id="id42">adv-bodyswap</a><ul> -<li><a class="reference internal" href="#usage" id="id43">Usage</a></li> -</ul> -</li> -<li><a class="reference internal" href="#advtools" id="id44">advtools</a><ul> -<li><a class="reference internal" href="#id1" id="id45">Usage</a></li> -</ul> -</li> -<li><a class="reference internal" href="#changelayer" id="id46">changelayer</a><ul> -<li><a class="reference internal" href="#options" id="id47">Options</a></li> -<li><a class="reference internal" href="#examples" id="id48">Examples:</a></li> -</ul> -</li> -<li><a class="reference internal" href="#changevein" id="id49">changevein</a><ul> -<li><a class="reference internal" href="#example" id="id50">Example:</a></li> -</ul> -</li> -<li><a class="reference internal" href="#changeitem" id="id51">changeitem</a><ul> -<li><a class="reference internal" href="#id2" id="id52">Options</a></li> -<li><a class="reference internal" href="#id3" id="id53">Examples:</a></li> -</ul> -</li> -<li><a class="reference internal" href="#cursecheck" id="id54">cursecheck</a><ul> -<li><a class="reference internal" href="#id4" id="id55">Options</a></li> -<li><a class="reference internal" href="#id5" id="id56">Examples:</a></li> -</ul> -</li> -<li><a class="reference internal" href="#follow" id="id57">follow</a></li> -<li><a class="reference internal" href="#forcepause" id="id58">forcepause</a></li> -<li><a class="reference internal" href="#nopause" id="id59">nopause</a></li> -<li><a class="reference internal" href="#die" id="id60">die</a></li> -<li><a class="reference internal" href="#autodump" id="id61">autodump</a><ul> -<li><a class="reference internal" href="#id6" id="id62">Options</a></li> -</ul> -</li> -<li><a class="reference internal" href="#autodump-destroy-here" id="id63">autodump-destroy-here</a></li> -<li><a class="reference internal" href="#autodump-destroy-item" id="id64">autodump-destroy-item</a></li> -<li><a class="reference internal" href="#burrow" id="id65">burrow</a><ul> -<li><a class="reference internal" href="#id7" id="id66">Options</a></li> -<li><a class="reference internal" href="#features" id="id67">Features</a></li> +<li><a class="reference internal" href="#introduction" id="id3">Introduction</a></li> +<li><a class="reference internal" href="#getting-dfhack" id="id4">Getting DFHack</a></li> +<li><a class="reference internal" href="#compatibility" id="id5">Compatibility</a></li> +<li><a class="reference internal" href="#installation-removal" id="id6">Installation/Removal</a></li> +<li><a class="reference internal" href="#using-dfhack" id="id7">Using DFHack</a></li> +<li><a class="reference internal" href="#something-doesn-t-work-help" id="id8">Something doesn't work, help!</a></li> +<li><a class="reference internal" href="#the-init-file" id="id9">The init file</a><ul> +<li><a class="reference internal" href="#setting-keybindings" id="id10">Setting keybindings</a></li> </ul> </li> -<li><a class="reference internal" href="#catsplosion" id="id68">catsplosion</a></li> -<li><a class="reference internal" href="#clean" id="id69">clean</a><ul> -<li><a class="reference internal" href="#id8" id="id70">Options</a></li> -<li><a class="reference internal" href="#extra-options-for-map" id="id71">Extra options for 'map'</a></li> +<li><a class="reference internal" href="#commands" id="id11">Commands</a><ul> +<li><a class="reference internal" href="#game-progress" id="id12">Game progress</a><ul> +<li><a class="reference internal" href="#die" id="id13">die</a></li> +<li><a class="reference internal" href="#forcepause" id="id14">forcepause</a></li> +<li><a class="reference internal" href="#nopause" id="id15">nopause</a></li> +<li><a class="reference internal" href="#fastdwarf" id="id16">fastdwarf</a></li> </ul> </li> -<li><a class="reference internal" href="#spotclean" id="id72">spotclean</a></li> -<li><a class="reference internal" href="#cleanowned" id="id73">cleanowned</a><ul> -<li><a class="reference internal" href="#id9" id="id74">Options</a></li> -<li><a class="reference internal" href="#id10" id="id75">Example:</a></li> +<li><a class="reference internal" href="#game-interface" id="id17">Game interface</a><ul> +<li><a class="reference internal" href="#follow" id="id18">follow</a></li> +<li><a class="reference internal" href="#tidlers" id="id19">tidlers</a></li> +<li><a class="reference internal" href="#twaterlvl" id="id20">twaterlvl</a></li> +<li><a class="reference internal" href="#copystock" id="id21">copystock</a></li> +<li><a class="reference internal" href="#rename" id="id22">rename</a></li> </ul> </li> -<li><a class="reference internal" href="#colonies" id="id76">colonies</a><ul> -<li><a class="reference internal" href="#id11" id="id77">Options</a></li> +<li><a class="reference internal" href="#adventure-mode" id="id23">Adventure mode</a><ul> +<li><a class="reference internal" href="#adv-bodyswap" id="id24">adv-bodyswap</a></li> +<li><a class="reference internal" href="#advtools" id="id25">advtools</a></li> </ul> </li> -<li><a class="reference internal" href="#deramp-by-zilpin" id="id78">deramp (by zilpin)</a></li> -<li><a class="reference internal" href="#dfusion" id="id79">dfusion</a><ul> -<li><a class="reference internal" href="#confirmed-working-dfusion-plugins" id="id80">Confirmed working DFusion plugins:</a></li> +<li><a class="reference internal" href="#map-modification" id="id26">Map modification</a><ul> +<li><a class="reference internal" href="#changelayer" id="id27">changelayer</a></li> +<li><a class="reference internal" href="#changevein" id="id28">changevein</a></li> +<li><a class="reference internal" href="#changeitem" id="id29">changeitem</a></li> +<li><a class="reference internal" href="#colonies" id="id30">colonies</a></li> +<li><a class="reference internal" href="#deramp-by-zilpin" id="id31">deramp (by zilpin)</a></li> +<li><a class="reference internal" href="#feature" id="id32">feature</a></li> +<li><a class="reference internal" href="#liquids" id="id33">liquids</a></li> +<li><a class="reference internal" href="#liquids-here" id="id34">liquids-here</a></li> +<li><a class="reference internal" href="#tiletypes" id="id35">tiletypes</a></li> +<li><a class="reference internal" href="#tiletypes-commands" id="id36">tiletypes-commands</a></li> +<li><a class="reference internal" href="#tiletypes-here" id="id37">tiletypes-here</a></li> +<li><a class="reference internal" href="#tiletypes-here-point" id="id38">tiletypes-here-point</a></li> +<li><a class="reference internal" href="#tubefill" id="id39">tubefill</a></li> +<li><a class="reference internal" href="#extirpate" id="id40">extirpate</a></li> +<li><a class="reference internal" href="#grow" id="id41">grow</a></li> +<li><a class="reference internal" href="#immolate" id="id42">immolate</a></li> +<li><a class="reference internal" href="#regrass" id="id43">regrass</a></li> +<li><a class="reference internal" href="#weather" id="id44">weather</a></li> </ul> </li> -<li><a class="reference internal" href="#drybuckets" id="id81">drybuckets</a></li> -<li><a class="reference internal" href="#fastdwarf" id="id82">fastdwarf</a></li> -<li><a class="reference internal" href="#feature" id="id83">feature</a><ul> -<li><a class="reference internal" href="#id12" id="id84">Options</a></li> +<li><a class="reference internal" href="#map-inspection" id="id45">Map inspection</a><ul> +<li><a class="reference internal" href="#cursecheck" id="id46">cursecheck</a></li> +<li><a class="reference internal" href="#flows" id="id47">flows</a></li> +<li><a class="reference internal" href="#probe" id="id48">probe</a></li> +<li><a class="reference internal" href="#prospect" id="id49">prospect</a><ul> +<li><a class="reference internal" href="#pre-embark-estimate" id="id50">Pre-embark estimate</a></li> </ul> </li> -<li><a class="reference internal" href="#filltraffic" id="id85">filltraffic</a><ul> -<li><a class="reference internal" href="#traffic-type-codes" id="id86">Traffic Type Codes:</a></li> -<li><a class="reference internal" href="#other-options" id="id87">Other Options:</a></li> -<li><a class="reference internal" href="#id13" id="id88">Example:</a></li> +<li><a class="reference internal" href="#reveal" id="id51">reveal</a></li> +<li><a class="reference internal" href="#unreveal" id="id52">unreveal</a></li> +<li><a class="reference internal" href="#revtoggle" id="id53">revtoggle</a></li> +<li><a class="reference internal" href="#revflood" id="id54">revflood</a></li> +<li><a class="reference internal" href="#revforget" id="id55">revforget</a></li> +<li><a class="reference internal" href="#showmood" id="id56">showmood</a></li> </ul> </li> -<li><a class="reference internal" href="#alltraffic" id="id89">alltraffic</a><ul> -<li><a class="reference internal" href="#id14" id="id90">Traffic Type Codes:</a></li> -<li><a class="reference internal" href="#id15" id="id91">Example:</a></li> +<li><a class="reference internal" href="#designations" id="id57">Designations</a><ul> +<li><a class="reference internal" href="#burrow" id="id58">burrow</a></li> +<li><a class="reference internal" href="#digv" id="id59">digv</a></li> +<li><a class="reference internal" href="#digvx" id="id60">digvx</a></li> +<li><a class="reference internal" href="#digl" id="id61">digl</a></li> +<li><a class="reference internal" href="#diglx" id="id62">diglx</a></li> +<li><a class="reference internal" href="#digexp" id="id63">digexp</a></li> +<li><a class="reference internal" href="#digcircle" id="id64">digcircle</a></li> +<li><a class="reference internal" href="#filltraffic" id="id65">filltraffic</a></li> +<li><a class="reference internal" href="#alltraffic" id="id66">alltraffic</a></li> +<li><a class="reference internal" href="#getplants" id="id67">getplants</a></li> </ul> </li> -<li><a class="reference internal" href="#fixdiplomats" id="id92">fixdiplomats</a></li> -<li><a class="reference internal" href="#fixmerchants" id="id93">fixmerchants</a></li> -<li><a class="reference internal" href="#fixveins" id="id94">fixveins</a></li> -<li><a class="reference internal" href="#fixwagons" id="id95">fixwagons</a></li> -<li><a class="reference internal" href="#flows" id="id96">flows</a></li> -<li><a class="reference internal" href="#getplants" id="id97">getplants</a><ul> -<li><a class="reference internal" href="#id16" id="id98">Options</a></li> +<li><a class="reference internal" href="#cleanup-and-garbage-disposal" id="id68">Cleanup and garbage disposal</a><ul> +<li><a class="reference internal" href="#clean" id="id69">clean</a></li> +<li><a class="reference internal" href="#spotclean" id="id70">spotclean</a></li> +<li><a class="reference internal" href="#autodump" id="id71">autodump</a></li> +<li><a class="reference internal" href="#autodump-destroy-here" id="id72">autodump-destroy-here</a></li> +<li><a class="reference internal" href="#autodump-destroy-item" id="id73">autodump-destroy-item</a></li> +<li><a class="reference internal" href="#cleanowned" id="id74">cleanowned</a></li> </ul> </li> -<li><a class="reference internal" href="#tidlers" id="id99">tidlers</a></li> -<li><a class="reference internal" href="#twaterlvl" id="id100">twaterlvl</a></li> -<li><a class="reference internal" href="#job" id="id101">job</a></li> -<li><a class="reference internal" href="#job-material" id="id102">job-material</a></li> -<li><a class="reference internal" href="#job-duplicate" id="id103">job-duplicate</a></li> -<li><a class="reference internal" href="#keybinding" id="id104">keybinding</a><ul> -<li><a class="reference internal" href="#id17" id="id105">Options</a></li> +<li><a class="reference internal" href="#bugfixes" id="id75">Bugfixes</a><ul> +<li><a class="reference internal" href="#drybuckets" id="id76">drybuckets</a></li> +<li><a class="reference internal" href="#fixdiplomats" id="id77">fixdiplomats</a></li> +<li><a class="reference internal" href="#fixmerchants" id="id78">fixmerchants</a></li> +<li><a class="reference internal" href="#fixveins" id="id79">fixveins</a></li> +<li><a class="reference internal" href="#tweak" id="id80">tweak</a></li> </ul> </li> -<li><a class="reference internal" href="#liquids" id="id106">liquids</a></li> -<li><a class="reference internal" href="#liquids-here" id="id107">liquids-here</a></li> -<li><a class="reference internal" href="#mode" id="id108">mode</a></li> -<li><a class="reference internal" href="#extirpate" id="id109">extirpate</a><ul> -<li><a class="reference internal" href="#id18" id="id110">Options</a></li> +<li><a class="reference internal" href="#mode-switch-and-reclaim" id="id81">Mode switch and reclaim</a><ul> +<li><a class="reference internal" href="#lair" id="id82">lair</a></li> +<li><a class="reference internal" href="#mode" id="id83">mode</a></li> </ul> </li> -<li><a class="reference internal" href="#grow" id="id111">grow</a></li> -<li><a class="reference internal" href="#immolate" id="id112">immolate</a></li> -<li><a class="reference internal" href="#probe" id="id113">probe</a></li> -<li><a class="reference internal" href="#prospect" id="id114">prospect</a><ul> -<li><a class="reference internal" href="#id19" id="id115">Options</a></li> -<li><a class="reference internal" href="#pre-embark-estimate" id="id116">Pre-embark estimate</a></li> -<li><a class="reference internal" href="#id20" id="id117">Options</a></li> +<li><a class="reference internal" href="#visualizer-and-data-export" id="id84">Visualizer and data export</a><ul> +<li><a class="reference internal" href="#ssense-stonesense" id="id85">ssense / stonesense</a></li> +<li><a class="reference internal" href="#mapexport" id="id86">mapexport</a></li> +<li><a class="reference internal" href="#dwarfexport" id="id87">dwarfexport</a></li> </ul> </li> -<li><a class="reference internal" href="#regrass" id="id118">regrass</a></li> -<li><a class="reference internal" href="#rename" id="id119">rename</a><ul> -<li><a class="reference internal" href="#id21" id="id120">Options</a></li> +<li><a class="reference internal" href="#job-management" id="id88">Job management</a><ul> +<li><a class="reference internal" href="#job" id="id89">job</a></li> +<li><a class="reference internal" href="#job-material" id="id90">job-material</a></li> +<li><a class="reference internal" href="#job-duplicate" id="id91">job-duplicate</a></li> +<li><a class="reference internal" href="#workflow" id="id92">workflow</a><ul> +<li><a class="reference internal" href="#function" id="id93">Function</a></li> +<li><a class="reference internal" href="#constraint-examples" id="id94">Constraint examples</a></li> </ul> </li> -<li><a class="reference internal" href="#reveal" id="id121">reveal</a></li> -<li><a class="reference internal" href="#unreveal" id="id122">unreveal</a></li> -<li><a class="reference internal" href="#revtoggle" id="id123">revtoggle</a></li> -<li><a class="reference internal" href="#revflood" id="id124">revflood</a></li> -<li><a class="reference internal" href="#revforget" id="id125">revforget</a></li> -<li><a class="reference internal" href="#lair" id="id126">lair</a><ul> -<li><a class="reference internal" href="#id22" id="id127">Options</a></li> </ul> </li> -<li><a class="reference internal" href="#seedwatch" id="id128">seedwatch</a></li> -<li><a class="reference internal" href="#showmood" id="id129">showmood</a></li> -<li><a class="reference internal" href="#copystock" id="id130">copystock</a></li> -<li><a class="reference internal" href="#ssense-stonesense" id="id131">ssense / stonesense</a></li> -<li><a class="reference internal" href="#tiletypes" id="id132">tiletypes</a></li> -<li><a class="reference internal" href="#tiletypes-commands" id="id133">tiletypes-commands</a></li> -<li><a class="reference internal" href="#tiletypes-here" id="id134">tiletypes-here</a></li> -<li><a class="reference internal" href="#tiletypes-here-point" id="id135">tiletypes-here-point</a></li> -<li><a class="reference internal" href="#tweak" id="id136">tweak</a><ul> -<li><a class="reference internal" href="#id23" id="id137">Options</a></li> +<li><a class="reference internal" href="#fortress-activity-management" id="id95">Fortress activity management</a><ul> +<li><a class="reference internal" href="#seedwatch" id="id96">seedwatch</a></li> +<li><a class="reference internal" href="#zone" id="id97">zone</a><ul> +<li><a class="reference internal" href="#usage-with-single-units" id="id98">Usage with single units</a></li> +<li><a class="reference internal" href="#usage-with-filters" id="id99">Usage with filters</a></li> +<li><a class="reference internal" href="#mass-renaming" id="id100">Mass-renaming</a></li> +<li><a class="reference internal" href="#cage-zones" id="id101">Cage zones</a></li> +<li><a class="reference internal" href="#examples" id="id102">Examples</a></li> </ul> </li> -<li><a class="reference internal" href="#tubefill" id="id138">tubefill</a></li> -<li><a class="reference internal" href="#digv" id="id139">digv</a></li> -<li><a class="reference internal" href="#digvx" id="id140">digvx</a></li> -<li><a class="reference internal" href="#digl" id="id141">digl</a></li> -<li><a class="reference internal" href="#diglx" id="id142">diglx</a></li> -<li><a class="reference internal" href="#digexp" id="id143">digexp</a><ul> -<li><a class="reference internal" href="#patterns" id="id144">Patterns:</a></li> -<li><a class="reference internal" href="#filters" id="id145">Filters:</a></li> -<li><a class="reference internal" href="#id24" id="id146">Examples:</a></li> +<li><a class="reference internal" href="#autonestbox" id="id103">autonestbox</a></li> +<li><a class="reference internal" href="#autobutcher" id="id104">autobutcher</a></li> +<li><a class="reference internal" href="#autolabor" id="id105">autolabor</a></li> </ul> </li> -<li><a class="reference internal" href="#digcircle" id="id147">digcircle</a><ul> -<li><a class="reference internal" href="#shape" id="id148">Shape:</a></li> -<li><a class="reference internal" href="#action" id="id149">Action:</a></li> -<li><a class="reference internal" href="#designation-types" id="id150">Designation types:</a></li> -<li><a class="reference internal" href="#id25" id="id151">Examples:</a></li> +<li><a class="reference internal" href="#other" id="id106">Other</a><ul> +<li><a class="reference internal" href="#catsplosion" id="id107">catsplosion</a></li> +<li><a class="reference internal" href="#dfusion" id="id108">dfusion</a></li> </ul> </li> -<li><a class="reference internal" href="#weather" id="id152">weather</a><ul> -<li><a class="reference internal" href="#id26" id="id153">Options:</a></li> </ul> </li> -<li><a class="reference internal" href="#workflow" id="id154">workflow</a><ul> -<li><a class="reference internal" href="#id27" id="id155">Usage</a></li> -<li><a class="reference internal" href="#function" id="id156">Function</a></li> -<li><a class="reference internal" href="#constraint-examples" id="id157">Constraint examples</a></li> +<li><a class="reference internal" href="#scripts" id="id109">Scripts</a><ul> +<li><a class="reference internal" href="#fix" id="id110">fix/*</a></li> +<li><a class="reference internal" href="#gui" id="id111">gui/*</a></li> +<li><a class="reference internal" href="#quicksave" id="id112">quicksave</a></li> +<li><a class="reference internal" href="#setfps" id="id113">setfps</a></li> +<li><a class="reference internal" href="#siren" id="id114">siren</a></li> +<li><a class="reference internal" href="#growcrops" id="id115">growcrops</a></li> +<li><a class="reference internal" href="#removebadthoughts" id="id116">removebadthoughts</a></li> +<li><a class="reference internal" href="#slayrace" id="id117">slayrace</a></li> +<li><a class="reference internal" href="#magmasource" id="id118">magmasource</a></li> +<li><a class="reference internal" href="#digfort" id="id119">digfort</a></li> +<li><a class="reference internal" href="#superdwarf" id="id120">superdwarf</a></li> +<li><a class="reference internal" href="#drainaquifer" id="id121">drainaquifer</a></li> +<li><a class="reference internal" href="#deathcause" id="id122">deathcause</a></li> </ul> </li> -<li><a class="reference internal" href="#mapexport" id="id158">mapexport</a></li> -<li><a class="reference internal" href="#dwarfexport" id="id159">dwarfexport</a></li> -<li><a class="reference internal" href="#zone" id="id160">zone</a><ul> -<li><a class="reference internal" href="#id28" id="id161">Options:</a></li> -<li><a class="reference internal" href="#id29" id="id162">Filters:</a></li> -<li><a class="reference internal" href="#usage-with-single-units" id="id163">Usage with single units</a></li> -<li><a class="reference internal" href="#usage-with-filters" id="id164">Usage with filters</a></li> -<li><a class="reference internal" href="#mass-renaming" id="id165">Mass-renaming</a></li> -<li><a class="reference internal" href="#cage-zones" id="id166">Cage zones</a></li> -<li><a class="reference internal" href="#id30" id="id167">Examples</a></li> +<li><a class="reference internal" href="#in-game-interface-tools" id="id123">In-game interface tools</a><ul> +<li><a class="reference internal" href="#dwarf-manipulator" id="id124">Dwarf Manipulator</a></li> +<li><a class="reference internal" href="#id1" id="id125">Liquids</a></li> +<li><a class="reference internal" href="#mechanisms" id="id126">Mechanisms</a></li> +<li><a class="reference internal" href="#id2" id="id127">Rename</a></li> +<li><a class="reference internal" href="#room-list" id="id128">Room List</a></li> </ul> </li> -<li><a class="reference internal" href="#autonestbox" id="id168">autonestbox</a><ul> -<li><a class="reference internal" href="#id31" id="id169">Options:</a></li> +<li><a class="reference internal" href="#behavior-mods" id="id129">Behavior Mods</a><ul> +<li><a class="reference internal" href="#siege-engine" id="id130">Siege Engine</a></li> +<li><a class="reference internal" href="#power-meter" id="id131">Power Meter</a></li> +<li><a class="reference internal" href="#steam-engine" id="id132">Steam Engine</a><ul> +<li><a class="reference internal" href="#rationale" id="id133">Rationale</a></li> +<li><a class="reference internal" href="#construction" id="id134">Construction</a></li> +<li><a class="reference internal" href="#operation" id="id135">Operation</a></li> +<li><a class="reference internal" href="#explosions" id="id136">Explosions</a></li> +<li><a class="reference internal" href="#save-files" id="id137">Save files</a></li> </ul> </li> -<li><a class="reference internal" href="#autobutcher" id="id170">autobutcher</a><ul> -<li><a class="reference internal" href="#id32" id="id171">Options:</a></li> -<li><a class="reference internal" href="#id33" id="id172">Examples:</a></li> -<li><a class="reference internal" href="#note" id="id173">Note:</a></li> -</ul> -</li> -<li><a class="reference internal" href="#autolabor" id="id174">autolabor</a></li> +<li><a class="reference internal" href="#add-spatter" id="id138">Add Spatter</a></li> </ul> </li> </ul> </div> </div> <div class="section" id="getting-dfhack"> -<h1><a class="toc-backref" href="#id35">Getting DFHack</a></h1> +<h1><a class="toc-backref" href="#id4">Getting DFHack</a></h1> <p>The project is currently hosted on <a class="reference external" href="http://www.github.com/">github</a>, for both source and binaries at <a class="reference external" href="http://github.com/peterix/dfhack">http://github.com/peterix/dfhack</a></p> <p>Releases can be downloaded from here: <a class="reference external" href="https://github.com/peterix/dfhack/downloads">https://github.com/peterix/dfhack/downloads</a></p> <p>All new releases are announced in the bay12 thread: <a class="reference external" href="http://tinyurl.com/dfhack-ng">http://tinyurl.com/dfhack-ng</a></p> </div> <div class="section" id="compatibility"> -<h1><a class="toc-backref" href="#id36">Compatibility</a></h1> +<h1><a class="toc-backref" href="#id5">Compatibility</a></h1> <p>DFHack works on Windows XP, Vista, 7 or any modern Linux distribution. OSX is not supported due to lack of developers with a Mac.</p> <p>Currently, versions 0.34.08 - 0.34.11 are supported. If you need DFHack @@ -547,7 +526,7 @@ for older versions, look for older releases.</p> <p>It is possible to use the Windows DFHack under wine/OSX.</p> </div> <div class="section" id="installation-removal"> -<h1><a class="toc-backref" href="#id37">Installation/Removal</a></h1> +<h1><a class="toc-backref" href="#id6">Installation/Removal</a></h1> <p>Installing DFhack involves copying files into your DF folder. Copy the files from a release archive so that:</p> <blockquote> @@ -569,7 +548,7 @@ remove the other DFHack files</li> file created in your DF folder.</p> </div> <div class="section" id="using-dfhack"> -<h1><a class="toc-backref" href="#id38">Using DFHack</a></h1> +<h1><a class="toc-backref" href="#id7">Using DFHack</a></h1> <p>DFHack basically extends what DF can do with something similar to the drop-down console found in Quake engine games. On Windows, this is a separate command line window. On linux, the terminal used to launch the dfhack script is taken over @@ -593,7 +572,7 @@ they are re-created every time it is loaded.</p> <p>Most of the commands come from plugins. Those reside in 'hack/plugins/'.</p> </div> <div class="section" id="something-doesn-t-work-help"> -<h1><a class="toc-backref" href="#id39">Something doesn't work, help!</a></h1> +<h1><a class="toc-backref" href="#id8">Something doesn't work, help!</a></h1> <p>First, don't panic :) Second, dfhack keeps a few log files in DF's folder - stderr.log and stdout.log. You can look at those and possibly find out what's happening. @@ -602,24 +581,175 @@ the issues tracker on github, contact me (<a class="reference external" href="ma #dfhack IRC channel on freenode.</p> </div> <div class="section" id="the-init-file"> -<h1><a class="toc-backref" href="#id40">The init file</a></h1> -<p>If your DF folder contains a file named dfhack.init, its contents will be run +<h1><a class="toc-backref" href="#id9">The init file</a></h1> +<p>If your DF folder contains a file named <tt class="docutils literal">dfhack.init</tt>, its contents will be run every time you start DF. This allows setting up keybindings. An example file -is provided as dfhack.init-example - you can tweak it and rename to dfhack.init +is provided as <tt class="docutils literal"><span class="pre">dfhack.init-example</span></tt> - you can tweak it and rename to dfhack.init if you want to use this functionality.</p> +<div class="section" id="setting-keybindings"> +<h2><a class="toc-backref" href="#id10">Setting keybindings</a></h2> +<p>To set keybindings, use the built-in <tt class="docutils literal">keybinding</tt> command. Like any other +command it can be used at any time from the console, but it is also meaningful +in the DFHack init file.</p> +<p>Currently it supports any combination of Ctrl/Alt/Shift with F1-F9, or A-Z.</p> +<p>Possible ways to call the command:</p> +<table class="docutils field-list" frame="void" rules="none"> +<col class="field-name" /> +<col class="field-body" /> +<tbody valign="top"> +<tr class="field"><th class="field-name" colspan="2">keybinding list <key>:</th></tr> +<tr class="field"><td> </td><td class="field-body">List bindings active for the key combination.</td> +</tr> +<tr class="field"><th class="field-name" colspan="2">keybinding clear <key> <key>...:</th></tr> +<tr class="field"><td> </td><td class="field-body">Remove bindings for the specified keys.</td> +</tr> +<tr class="field"><th class="field-name" colspan="2">keybinding add <key> "cmdline" "cmdline"...:</th></tr> +<tr class="field"><td> </td><td class="field-body">Add bindings for the specified +key.</td> +</tr> +<tr class="field"><th class="field-name" colspan="2">keybinding set <key> "cmdline" "cmdline"...:</th></tr> +<tr class="field"><td> </td><td class="field-body">Clear, and then add bindings for +the specified key.</td> +</tr> +</tbody> +</table> +<p>The <em><key></em> parameter above has the following <em>case-sensitive</em> syntax:</p> +<pre class="literal-block"> +[Ctrl-][Alt-][Shift-]KEY[@context] +</pre> +<p>where the <em>KEY</em> part can be F1-F9 or A-Z, and [] denote optional parts.</p> +<p>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.</p> +<p>The <em>context</em> 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 <tt class="docutils literal">keybinding</tt> command among other things prints the current context string. +Only bindings with a <em>context</em> tag that either matches the current context fully, +or is a prefix ending at a '/' boundary would be considered for execution, i.e. +for context <tt class="docutils literal">foo/bar/baz</tt>, possible matches are any of <tt class="docutils literal">@foo/bar/baz</tt>, <tt class="docutils literal">@foo/bar</tt>, +<tt class="docutils literal">@foo</tt> or none.</p> +</div> </div> <div class="section" id="commands"> -<h1><a class="toc-backref" href="#id41">Commands</a></h1> +<h1><a class="toc-backref" href="#id11">Commands</a></h1> +<p>DFHack command syntax consists of a command name, followed by arguments separated +by whitespace. To include whitespace in an argument, quote it in double quotes. +To include a double quote character, use <tt class="docutils literal">\"</tt> inside double quotes.</p> +<p>If the first non-whitespace character of a line is <tt class="docutils literal">#</tt>, the line is treated +as a comment, i.e. a silent no-op command.</p> +<p>If the first non-whitespace character is <tt class="docutils literal">:</tt>, the command is parsed in a special +alternative mode: first, non-whitespace characters immediately following the <tt class="docutils literal">:</tt> +are used as the command name; the remaining part of the line, starting with the first +non-whitespace character <em>after</em> the command name, is used verbatim as the first argument. +The following two command lines are exactly equivalent:</p> +<blockquote> +<ul class="simple"> +<li><tt class="docutils literal">:foo a b "c d" e f</tt></li> +<li><tt class="docutils literal">foo "a b \"c d\" e f"</tt></li> +</ul> +</blockquote> +<p>This is intended for commands like <tt class="docutils literal">rb_eval</tt> that evaluate script language statements.</p> <p>Almost all the commands support using the 'help <command-name>' built-in command to retrieve further help without having to look at this document. Alternatively, some accept a 'help'/'?' option on their command line.</p> +<div class="section" id="game-progress"> +<h2><a class="toc-backref" href="#id12">Game progress</a></h2> +<div class="section" id="die"> +<h3><a class="toc-backref" href="#id13">die</a></h3> +<p>Instantly kills DF without saving.</p> +</div> +<div class="section" id="forcepause"> +<h3><a class="toc-backref" href="#id14">forcepause</a></h3> +<p>Forces DF to pause. This is useful when your FPS drops below 1 and you lose +control of the game.</p> +<blockquote> +<ul class="simple"> +<li>Activate with 'forcepause 1'</li> +<li>Deactivate with 'forcepause 0'</li> +</ul> +</blockquote> +</div> +<div class="section" id="nopause"> +<h3><a class="toc-backref" href="#id15">nopause</a></h3> +<p>Disables pausing (both manual and automatic) with the exception of pause forced +by 'reveal hell'. This is nice for digging under rivers.</p> +</div> +<div class="section" id="fastdwarf"> +<h3><a class="toc-backref" href="#id16">fastdwarf</a></h3> +<p>Makes your minions move at ludicrous speeds.</p> +<blockquote> +<ul class="simple"> +<li>Activate with 'fastdwarf 1'</li> +<li>Deactivate with 'fastdwarf 0'</li> +</ul> +</blockquote> +</div> +</div> +<div class="section" id="game-interface"> +<h2><a class="toc-backref" href="#id17">Game interface</a></h2> +<div class="section" id="follow"> +<h3><a class="toc-backref" href="#id18">follow</a></h3> +<p>Makes the game view follow the currently highlighted unit after you exit from +current menu/cursor mode. Handy for watching dwarves running around. Deactivated +by moving the view manually.</p> +</div> +<div class="section" id="tidlers"> +<h3><a class="toc-backref" href="#id19">tidlers</a></h3> +<p>Toggle between all possible positions where the idlers count can be placed.</p> +</div> +<div class="section" id="twaterlvl"> +<h3><a class="toc-backref" href="#id20">twaterlvl</a></h3> +<p>Toggle between displaying/not displaying liquid depth as numbers.</p> +</div> +<div class="section" id="copystock"> +<h3><a class="toc-backref" href="#id21">copystock</a></h3> +<p>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.</p> +</div> +<div class="section" id="rename"> +<h3><a class="toc-backref" href="#id22">rename</a></h3> +<p>Allows renaming various things.</p> +<p>Options:</p> +<blockquote> +<table class="docutils field-list" frame="void" rules="none"> +<col class="field-name" /> +<col class="field-body" /> +<tbody valign="top"> +<tr class="field"><th class="field-name" colspan="2">rename squad <index> "name":</th></tr> +<tr class="field"><td> </td><td class="field-body">Rename squad by index to 'name'.</td> +</tr> +<tr class="field"><th class="field-name" colspan="2">rename hotkey <index> "name":</th></tr> +<tr class="field"><td> </td><td class="field-body">Rename hotkey by index. This allows assigning +longer commands to the DF hotkeys.</td> +</tr> +<tr class="field"><th class="field-name" colspan="2">rename unit "nickname":</th></tr> +<tr class="field"><td> </td><td class="field-body">Rename a unit/creature highlighted in the DF user +interface.</td> +</tr> +<tr class="field"><th class="field-name" colspan="2">rename unit-profession "custom profession":</th></tr> +<tr class="field"><td> </td><td class="field-body">Change proffession name of the +highlighted unit/creature.</td> +</tr> +<tr class="field"><th class="field-name" colspan="2">rename building "name":</th></tr> +<tr class="field"><td> </td><td class="field-body">Set a custom name for the selected building. +The building must be one of stockpile, workshop, furnace, trap, +siege engine or an activity zone.</td> +</tr> +</tbody> +</table> +</blockquote> +</div> +</div> +<div class="section" id="adventure-mode"> +<h2><a class="toc-backref" href="#id23">Adventure mode</a></h2> <div class="section" id="adv-bodyswap"> -<h2><a class="toc-backref" href="#id42">adv-bodyswap</a></h2> +<h3><a class="toc-backref" href="#id24">adv-bodyswap</a></h3> <p>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.</p> -<div class="section" id="usage"> -<h3><a class="toc-backref" href="#id43">Usage</a></h3> +<p>Usage:</p> <blockquote> <ul class="simple"> <li>When viewing unit details, body-swaps into that unit.</li> @@ -627,12 +757,11 @@ properly.</p> </ul> </blockquote> </div> -</div> <div class="section" id="advtools"> -<h2><a class="toc-backref" href="#id44">advtools</a></h2> +<h3><a class="toc-backref" href="#id25">advtools</a></h3> <p>A package of different adventure mode tools (currently just one)</p> -<div class="section" id="id1"> -<h3><a class="toc-backref" href="#id45">Usage</a></h3> +<p>Usage:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -648,10 +777,13 @@ on item type and being in shop.</td> </tr> </tbody> </table> +</blockquote> </div> </div> +<div class="section" id="map-modification"> +<h2><a class="toc-backref" href="#id26">Map modification</a></h2> <div class="section" id="changelayer"> -<h2><a class="toc-backref" href="#id46">changelayer</a></h2> +<h3><a class="toc-backref" href="#id27">changelayer</a></h3> <p>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 @@ -662,8 +794,8 @@ as well, though. Mineral veins and gem clusters will stay on the map. Use 'changevein' for them.</p> <p>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.</p> -<div class="section" id="options"> -<h3><a class="toc-backref" href="#id47">Options</a></h3> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -695,9 +827,9 @@ soil.</td> </tr> </tbody> </table> -</div> -<div class="section" id="examples"> -<h3><a class="toc-backref" href="#id48">Examples:</a></h3> +</blockquote> +<p>Examples:</p> +<blockquote> <dl class="docutils"> <dt><tt class="docutils literal">changelayer GRANITE</tt></dt> <dd>Convert layer at cursor position into granite.</dd> @@ -706,6 +838,7 @@ soil.</td> <dt><tt class="docutils literal">changelayer MARBLE all_biomes all_layers</tt></dt> <dd>Convert all layers of all biomes which are not soil into marble.</dd> </dl> +</blockquote> <div class="note"> <p class="first admonition-title">Note</p> <ul class="last simple"> @@ -724,21 +857,21 @@ You did save your game, right?</li> </ul> </div> </div> -</div> <div class="section" id="changevein"> -<h2><a class="toc-backref" href="#id49">changevein</a></h2> +<h3><a class="toc-backref" href="#id28">changevein</a></h3> <p>Changes material of the vein under cursor to the specified inorganic RAW -material.</p> -<div class="section" id="example"> -<h3><a class="toc-backref" href="#id50">Example:</a></h3> +material. Only affects tiles within the current 16x16 block - for veins and +large clusters, you will need to use this command multiple times.</p> +<p>Example:</p> +<blockquote> <dl class="docutils"> <dt><tt class="docutils literal">changevein NATIVE_PLATINUM</tt></dt> <dd>Convert vein at cursor position into platinum ore.</dd> </dl> -</div> +</blockquote> </div> <div class="section" id="changeitem"> -<h2><a class="toc-backref" href="#id51">changeitem</a></h2> +<h3><a class="toc-backref" href="#id29">changeitem</a></h3> <p>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 @@ -748,8 +881,8 @@ 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.</p> -<div class="section" id="id2"> -<h3><a class="toc-backref" href="#id52">Options</a></h3> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -766,19 +899,220 @@ crafters/haulers.</p> </tr> </tbody> </table> -</div> -<div class="section" id="id3"> -<h3><a class="toc-backref" href="#id53">Examples:</a></h3> +</blockquote> +<p>Examples:</p> +<blockquote> <dl class="docutils"> <dt><tt class="docutils literal">changeitem m INORGANIC:GRANITE here</tt></dt> <dd>Change material of all items under the cursor to granite.</dd> <dt><tt class="docutils literal">changeitem q 5</tt></dt> <dd>Change currently selected item to masterpiece quality.</dd> </dl> +</blockquote> +</div> +<div class="section" id="colonies"> +<h3><a class="toc-backref" href="#id30">colonies</a></h3> +<p>Allows listing all the vermin colonies on the map and optionally turning them into honey bee colonies.</p> +<p>Options:</p> +<blockquote> +<table class="docutils field-list" frame="void" rules="none"> +<col class="field-name" /> +<col class="field-body" /> +<tbody valign="top"> +<tr class="field"><th class="field-name">bees:</th><td class="field-body">turn colonies into honey bee colonies</td> +</tr> +</tbody> +</table> +</blockquote> +</div> +<div class="section" id="deramp-by-zilpin"> +<h3><a class="toc-backref" href="#id31">deramp (by zilpin)</a></h3> +<p>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).</p> </div> +<div class="section" id="feature"> +<h3><a class="toc-backref" href="#id32">feature</a></h3> +<p>Enables management of map features.</p> +<ul class="simple"> +<li>Discovering a magma feature (magma pool, volcano, magma sea, or curious +underground structure) permits magma workshops and furnaces to be built.</li> +<li>Discovering a cavern layer causes plants (trees, shrubs, and grass) from +that cavern to grow within your fortress.</li> +</ul> +<p>Options:</p> +<blockquote> +<table class="docutils field-list" frame="void" rules="none"> +<col class="field-name" /> +<col class="field-body" /> +<tbody valign="top"> +<tr class="field"><th class="field-name">list:</th><td class="field-body">Lists all map features in your current embark by index.</td> +</tr> +<tr class="field"><th class="field-name">show X:</th><td class="field-body">Marks the selected map feature as discovered.</td> +</tr> +<tr class="field"><th class="field-name">hide X:</th><td class="field-body">Marks the selected map feature as undiscovered.</td> +</tr> +</tbody> +</table> +</blockquote> +</div> +<div class="section" id="liquids"> +<h3><a class="toc-backref" href="#id33">liquids</a></h3> +<p>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).</p> +<p>For more information, refer to the command's internal help.</p> +<div class="note"> +<p class="first admonition-title">Note</p> +<p class="last">Spawning and deleting liquids can F up pathing data and +temperatures (creating heat traps). You've been warned.</p> +</div> +</div> +<div class="section" id="liquids-here"> +<h3><a class="toc-backref" href="#id34">liquids-here</a></h3> +<p>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).</p> +<p>Intended to be used as keybinding. Requires an active in-game cursor.</p> +</div> +<div class="section" id="tiletypes"> +<h3><a class="toc-backref" href="#id35">tiletypes</a></h3> +<p>Can be used for painting map tiles and is an interactive command, much like +liquids.</p> +<p>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.</p> +<p>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.</p> +<p>The properties of filter and paint can be partially defined. This means that +you can for example do something like this:</p> +<pre class="literal-block"> +filter material STONE +filter shape FORTIFICATION +paint shape FLOOR +</pre> +<p>This will turn all stone fortifications into floors, preserving the material.</p> +<p>Or this:</p> +<pre class="literal-block"> +filter shape FLOOR +filter material MINERAL +paint shape WALL +</pre> +<p>Turning mineral vein floors back into walls.</p> +<p>The tool also allows tweaking some tile flags:</p> +<p>Or this:</p> +<pre class="literal-block"> +paint hidden 1 +paint hidden 0 +</pre> +<p>This will hide previously revealed tiles (or show hidden with the 0 option).</p> +<p>Any paint or filter option (or the entire paint or filter) can be disabled entirely by using the ANY keyword:</p> +<pre class="literal-block"> +paint hidden ANY +paint shape ANY +filter material any +filter shape any +filter any +</pre> +<dl class="docutils"> +<dt>You can use several different brushes for painting tiles:</dt> +<dd><ul class="first last simple"> +<li>Point. (point)</li> +<li>Rectangular range. (range)</li> +<li>A column ranging from current cursor to the first solid tile above. (column)</li> +<li>DF map block - 16x16 tiles, in a regular grid. (block)</li> +</ul> +</dd> +</dl> +<p>Example:</p> +<pre class="literal-block"> +range 10 10 1 +</pre> +<p>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.</p> +<p>For more details, see the 'help' command while using this.</p> +</div> +<div class="section" id="tiletypes-commands"> +<h3><a class="toc-backref" href="#id36">tiletypes-commands</a></h3> +<p>Runs tiletypes commands, separated by ;. This makes it possible to change +tiletypes modes from a hotkey.</p> +</div> +<div class="section" id="tiletypes-here"> +<h3><a class="toc-backref" href="#id37">tiletypes-here</a></h3> +<p>Apply the current tiletypes options at the in-game cursor position, including +the brush. Can be used from a hotkey.</p> +</div> +<div class="section" id="tiletypes-here-point"> +<h3><a class="toc-backref" href="#id38">tiletypes-here-point</a></h3> +<p>Apply the current tiletypes options at the in-game cursor position to a single +tile. Can be used from a hotkey.</p> +</div> +<div class="section" id="tubefill"> +<h3><a class="toc-backref" href="#id39">tubefill</a></h3> +<p>Fills all the adamantine veins again. Veins that were empty will be filled in +too, but might still trigger a demon invasion (this is a known bug).</p> +</div> +<div class="section" id="extirpate"> +<h3><a class="toc-backref" href="#id40">extirpate</a></h3> +<p>A tool for getting rid of trees and shrubs. By default, it only kills +a tree/shrub under the cursor. The plants are turned into ashes instantly.</p> +<p>Options:</p> +<blockquote> +<table class="docutils field-list" frame="void" rules="none"> +<col class="field-name" /> +<col class="field-body" /> +<tbody valign="top"> +<tr class="field"><th class="field-name">shrubs:</th><td class="field-body">affect all shrubs on the map</td> +</tr> +<tr class="field"><th class="field-name">trees:</th><td class="field-body">affect all trees on the map</td> +</tr> +<tr class="field"><th class="field-name">all:</th><td class="field-body">affect every plant!</td> +</tr> +</tbody> +</table> +</blockquote> +</div> +<div class="section" id="grow"> +<h3><a class="toc-backref" href="#id41">grow</a></h3> +<p>Makes all saplings present on the map grow into trees (almost) instantly.</p> +</div> +<div class="section" id="immolate"> +<h3><a class="toc-backref" href="#id42">immolate</a></h3> +<p>Very similar to extirpate, but additionally sets the plants on fire. The fires +can and <em>will</em> spread ;)</p> +</div> +<div class="section" id="regrass"> +<h3><a class="toc-backref" href="#id43">regrass</a></h3> +<p>Regrows grass. Not much to it ;)</p> +</div> +<div class="section" id="weather"> +<h3><a class="toc-backref" href="#id44">weather</a></h3> +<p>Prints the current weather map by default.</p> +<p>Also lets you change the current weather to 'clear sky', 'rainy' or 'snowing'.</p> +<p>Options:</p> +<blockquote> +<table class="docutils field-list" frame="void" rules="none"> +<col class="field-name" /> +<col class="field-body" /> +<tbody valign="top"> +<tr class="field"><th class="field-name">snow:</th><td class="field-body">make it snow everywhere.</td> +</tr> +<tr class="field"><th class="field-name">rain:</th><td class="field-body">make it rain.</td> +</tr> +<tr class="field"><th class="field-name">clear:</th><td class="field-body">clear the sky.</td> +</tr> +</tbody> +</table> +</blockquote> </div> +</div> +<div class="section" id="map-inspection"> +<h2><a class="toc-backref" href="#id45">Map inspection</a></h2> <div class="section" id="cursecheck"> -<h2><a class="toc-backref" href="#id54">cursecheck</a></h2> +<h3><a class="toc-backref" href="#id46">cursecheck</a></h3> <p>Checks a single map tile or the whole map/world for cursed creatures (ghosts, vampires, necromancers, werebeasts, zombies).</p> <p>With an active in-game cursor only the selected tile will be observed. @@ -789,8 +1123,8 @@ 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".</p> -<div class="section" id="id4"> -<h3><a class="toc-backref" href="#id55">Options</a></h3> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -808,9 +1142,9 @@ long list after having FUN with necromancers).</td> </tr> </tbody> </table> -</div> -<div class="section" id="id5"> -<h3><a class="toc-backref" href="#id56">Examples:</a></h3> +</blockquote> +<p>Examples:</p> +<blockquote> <dl class="docutils"> <dt><tt class="docutils literal">cursecheck detail all</tt></dt> <dd>Give detailed info about all cursed creatures including deceased ones (no @@ -819,6 +1153,7 @@ in-game cursor).</dd> <dd>Give a nickname all living/active cursed creatures on the map(no in-game cursor).</dd> </dl> +</blockquote> <div class="note"> <p class="first admonition-title">Note</p> <ul class="last simple"> @@ -831,119 +1166,131 @@ of curses, for example.</li> </ul> </div> </div> +<div class="section" id="flows"> +<h3><a class="toc-backref" href="#id47">flows</a></h3> +<p>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.</p> </div> -<div class="section" id="follow"> -<h2><a class="toc-backref" href="#id57">follow</a></h2> -<p>Makes the game view follow the currently highlighted unit after you exit from -current menu/cursor mode. Handy for watching dwarves running around. Deactivated -by moving the view manually.</p> +<div class="section" id="probe"> +<h3><a class="toc-backref" href="#id48">probe</a></h3> +<p>Can be used to determine tile properties like temperature.</p> </div> -<div class="section" id="forcepause"> -<h2><a class="toc-backref" href="#id58">forcepause</a></h2> -<p>Forces DF to pause. This is useful when your FPS drops below 1 and you lose -control of the game.</p> +<div class="section" id="prospect"> +<h3><a class="toc-backref" href="#id49">prospect</a></h3> +<p>Prints a big list of all the present minerals and plants. By default, only +the visible part of the map is scanned.</p> +<p>Options:</p> <blockquote> -<ul class="simple"> -<li>Activate with 'forcepause 1'</li> -<li>Deactivate with 'forcepause 0'</li> -</ul> -</blockquote> -</div> -<div class="section" id="nopause"> -<h2><a class="toc-backref" href="#id59">nopause</a></h2> -<p>Disables pausing (both manual and automatic) with the exception of pause forced -by 'reveal hell'. This is nice for digging under rivers.</p> -</div> -<div class="section" id="die"> -<h2><a class="toc-backref" href="#id60">die</a></h2> -<p>Instantly kills DF without saving.</p> -</div> -<div class="section" id="autodump"> -<h2><a class="toc-backref" href="#id61">autodump</a></h2> -<p>This utility lets you quickly move all items designated to be dumped. -Items are instantly moved to the cursor position, the dump flag is unset, -and the forbid flag is set, as if it had been dumped normally. -Be aware that any active dump item tasks still point at the item.</p> -<p>Cursor must be placed on a floor tile so the items can be dumped there.</p> -<div class="section" id="id6"> -<h3><a class="toc-backref" href="#id62">Options</a></h3> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">destroy:</th><td class="field-body">Destroy instead of dumping. Doesn't require a cursor.</td> -</tr> -<tr class="field"><th class="field-name">destroy-here:</th><td class="field-body">Destroy items only under the cursor.</td> -</tr> -<tr class="field"><th class="field-name">visible:</th><td class="field-body">Only process items that are not hidden.</td> +<tr class="field"><th class="field-name">all:</th><td class="field-body">Scan the whole map, as if it was revealed.</td> </tr> -<tr class="field"><th class="field-name">hidden:</th><td class="field-body">Only process hidden items.</td> +<tr class="field"><th class="field-name">value:</th><td class="field-body">Show material value in the output. Most useful for gems.</td> </tr> -<tr class="field"><th class="field-name">forbidden:</th><td class="field-body">Only process forbidden items (default: only unforbidden).</td> +<tr class="field"><th class="field-name">hell:</th><td class="field-body">Show the Z range of HFS tubes. Implies 'all'.</td> </tr> </tbody> </table> +</blockquote> +<div class="section" id="pre-embark-estimate"> +<h4><a class="toc-backref" href="#id50">Pre-embark estimate</a></h4> +<p>If prospect is called during the embark selection screen, it displays an estimate of +layer stone availability.</p> +<div class="note"> +<p class="first admonition-title">Note</p> +<p class="last">The results of pre-embark prospect are an <em>estimate</em>, 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.</p> </div> -</div> -<div class="section" id="autodump-destroy-here"> -<h2><a class="toc-backref" href="#id63">autodump-destroy-here</a></h2> -<p>Destroy items marked for dumping under cursor. Identical to autodump -destroy-here, but intended for use as keybinding.</p> -</div> -<div class="section" id="autodump-destroy-item"> -<h2><a class="toc-backref" href="#id64">autodump-destroy-item</a></h2> -<p>Destroy the selected item. The item may be selected in the 'k' list, or inside -a container. If called again before the game is resumed, cancels destroy.</p> -</div> -<div class="section" id="burrow"> -<h2><a class="toc-backref" href="#id65">burrow</a></h2> -<p>Miscellaneous burrow control. Allows manipulating burrows and automated burrow -expansion while digging.</p> -<div class="section" id="id7"> -<h3><a class="toc-backref" href="#id66">Options</a></h3> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name" colspan="2">enable feature ...:</th></tr> -<tr class="field"><td> </td><td class="field-body"></td> -</tr> -<tr class="field"><th class="field-name" colspan="2">disable feature ...:</th></tr> -<tr class="field"><td> </td><td class="field-body">Enable or Disable features of the plugin.</td> -</tr> -<tr class="field"><th class="field-name" colspan="2">clear-unit burrow burrow ...:</th></tr> -<tr class="field"><td> </td><td class="field-body"></td> -</tr> -<tr class="field"><th class="field-name" colspan="2">clear-tiles burrow burrow ...:</th></tr> -<tr class="field"><td> </td><td class="field-body">Removes all units or tiles from the burrows.</td> -</tr> -<tr class="field"><th class="field-name" colspan="2">set-units target-burrow src-burrow ...:</th></tr> -<tr class="field"><td> </td><td class="field-body"></td> -</tr> -<tr class="field"><th class="field-name" colspan="2">add-units target-burrow src-burrow ...:</th></tr> -<tr class="field"><td> </td><td class="field-body"></td> -</tr> -<tr class="field"><th class="field-name" colspan="2">remove-units target-burrow src-burrow ...:</th></tr> -<tr class="field"><td> </td><td class="field-body">Adds or removes units in source -burrows to/from the target burrow. Set is equivalent to clear and add.</td> -</tr> -<tr class="field"><th class="field-name" colspan="2">set-tiles target-burrow src-burrow ...:</th></tr> -<tr class="field"><td> </td><td class="field-body"></td> -</tr> -<tr class="field"><th class="field-name" colspan="2">add-tiles target-burrow src-burrow ...:</th></tr> -<tr class="field"><td> </td><td class="field-body"></td> -</tr> -<tr class="field"><th class="field-name" colspan="2">remove-tiles target-burrow src-burrow ...:</th></tr> -<tr class="field"><td> </td><td class="field-body">Adds or removes tiles in source -burrows to/from the target burrow. In place of a source burrow it is -possible to use one of the following keywords: ABOVE_GROUND, -SUBTERRANEAN, INSIDE, OUTSIDE, LIGHT, DARK, HIDDEN, REVEALED</td> +<tr class="field"><th class="field-name">all:</th><td class="field-body">Also estimate vein mineral amounts.</td> </tr> </tbody> </table> +</blockquote> +</div> </div> -<div class="section" id="features"> -<h3><a class="toc-backref" href="#id67">Features</a></h3> +<div class="section" id="reveal"> +<h3><a class="toc-backref" href="#id51">reveal</a></h3> +<p>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'.</p> +<p>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'.</p> +</div> +<div class="section" id="unreveal"> +<h3><a class="toc-backref" href="#id52">unreveal</a></h3> +<p>Reverts the effects of 'reveal'.</p> +</div> +<div class="section" id="revtoggle"> +<h3><a class="toc-backref" href="#id53">revtoggle</a></h3> +<p>Switches between 'reveal' and 'unreveal'.</p> +</div> +<div class="section" id="revflood"> +<h3><a class="toc-backref" href="#id54">revflood</a></h3> +<p>This command will hide the whole map and then reveal all the tiles that have +a path to the in-game cursor.</p> +</div> +<div class="section" id="revforget"> +<h3><a class="toc-backref" href="#id55">revforget</a></h3> +<p>When you use reveal, it saves information about what was/wasn't visible before +revealing everything. Unreveal uses this information to hide things again. +This command throws away the information. For example, use in cases where +you abandoned with the fort revealed and no longer want the data.</p> +</div> +<div class="section" id="showmood"> +<h3><a class="toc-backref" href="#id56">showmood</a></h3> +<p>Shows all items needed for the currently active strange mood.</p> +</div> +</div> +<div class="section" id="designations"> +<h2><a class="toc-backref" href="#id57">Designations</a></h2> +<div class="section" id="burrow"> +<h3><a class="toc-backref" href="#id58">burrow</a></h3> +<p>Miscellaneous burrow control. Allows manipulating burrows and automated burrow +expansion while digging.</p> +<p>Options:</p> +<blockquote> +<dl class="docutils"> +<dt><strong>enable feature ...</strong></dt> +<dd>Enable features of the plugin.</dd> +<dt><strong>disable feature ...</strong></dt> +<dd>Disable features of the plugin.</dd> +<dt><strong>clear-unit burrow burrow ...</strong></dt> +<dd>Remove all units from the burrows.</dd> +<dt><strong>clear-tiles burrow burrow ...</strong></dt> +<dd>Remove all tiles from the burrows.</dd> +<dt><strong>set-units target-burrow src-burrow ...</strong></dt> +<dd>Clear target, and adds units from source burrows.</dd> +<dt><strong>add-units target-burrow src-burrow ...</strong></dt> +<dd>Add units from the source burrows to the target.</dd> +<dt><strong>remove-units target-burrow src-burrow ...</strong></dt> +<dd>Remove units in source burrows from the target.</dd> +<dt><strong>set-tiles target-burrow src-burrow ...</strong></dt> +<dd>Clear target and adds tiles from the source burrows.</dd> +<dt><strong>add-tiles target-burrow src-burrow ...</strong></dt> +<dd>Add tiles from the source burrows to the target.</dd> +<dt><strong>remove-tiles target-burrow src-burrow ...</strong></dt> +<dd><p class="first">Remove tiles in source burrows from the target.</p> +<p class="last">For these three options, in place of a source burrow it is +possible to use one of the following keywords: ABOVE_GROUND, +SUBTERRANEAN, INSIDE, OUTSIDE, LIGHT, DARK, HIDDEN, REVEALED</p> +</dd> +</dl> +</blockquote> +<p>Features:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -955,169 +1302,161 @@ Digging 1-wide corridors with the miner inside the burrow is SLOW.</td> </tr> </tbody> </table> +</blockquote> </div> +<div class="section" id="digv"> +<h3><a class="toc-backref" href="#id59">digv</a></h3> +<p>Designates a whole vein for digging. Requires an active in-game cursor placed +over a vein tile. With the 'x' option, it will traverse z-levels (putting stairs +between the same-material tiles).</p> </div> -<div class="section" id="catsplosion"> -<h2><a class="toc-backref" href="#id68">catsplosion</a></h2> -<p>Makes cats just <em>multiply</em>. It is not a good idea to run this more than once or -twice.</p> +<div class="section" id="digvx"> +<h3><a class="toc-backref" href="#id60">digvx</a></h3> +<p>A permanent alias for 'digv x'.</p> </div> -<div class="section" id="clean"> -<h2><a class="toc-backref" href="#id69">clean</a></h2> -<p>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.</p> -<div class="section" id="id8"> -<h3><a class="toc-backref" href="#id70">Options</a></h3> +<div class="section" id="digl"> +<h3><a class="toc-backref" href="#id61">digl</a></h3> +<p>Designates layer stone for digging. Requires an active in-game cursor placed +over a layer stone tile. With the 'x' option, it will traverse z-levels +(putting stairs between the same-material tiles). With the 'undo' option it +will remove the dig designation instead (if you realize that digging out a 50 +z-level deep layer was not such a good idea after all).</p> +</div> +<div class="section" id="diglx"> +<h3><a class="toc-backref" href="#id62">diglx</a></h3> +<p>A permanent alias for 'digl x'.</p> +</div> +<div class="section" id="digexp"> +<h3><a class="toc-backref" href="#id63">digexp</a></h3> +<p>This command can be used for exploratory mining.</p> +<p>See: <a class="reference external" href="http://df.magmawiki.com/index.php/DF2010:Exploratory_mining">http://df.magmawiki.com/index.php/DF2010:Exploratory_mining</a></p> +<p>There are two variables that can be set: pattern and filter.</p> +<p>Patterns:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">map:</th><td class="field-body">Clean the map tiles. By default, it leaves mud and snow alone.</td> +<tr class="field"><th class="field-name">diag5:</th><td class="field-body">diagonals separated by 5 tiles</td> </tr> -<tr class="field"><th class="field-name">units:</th><td class="field-body">Clean the creatures. Will also clean hostiles.</td> +<tr class="field"><th class="field-name">diag5r:</th><td class="field-body">diag5 rotated 90 degrees</td> </tr> -<tr class="field"><th class="field-name">items:</th><td class="field-body">Clean all the items. Even a poisoned blade.</td> +<tr class="field"><th class="field-name">ladder:</th><td class="field-body">A 'ladder' pattern</td> </tr> -</tbody> -</table> -</div> -<div class="section" id="extra-options-for-map"> -<h3><a class="toc-backref" href="#id71">Extra options for 'map'</a></h3> -<table class="docutils field-list" frame="void" rules="none"> -<col class="field-name" /> -<col class="field-body" /> -<tbody valign="top"> -<tr class="field"><th class="field-name">mud:</th><td class="field-body">Remove mud in addition to the normal stuff.</td> +<tr class="field"><th class="field-name">ladderr:</th><td class="field-body">ladder rotated 90 degrees</td> </tr> -<tr class="field"><th class="field-name">snow:</th><td class="field-body">Also remove snow coverings.</td> +<tr class="field"><th class="field-name">clear:</th><td class="field-body">Just remove all dig designations</td> +</tr> +<tr class="field"><th class="field-name">cross:</th><td class="field-body">A cross, exactly in the middle of the map.</td> </tr> </tbody> </table> -</div> -</div> -<div class="section" id="spotclean"> -<h2><a class="toc-backref" href="#id72">spotclean</a></h2> -<p>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.</p> -</div> -<div class="section" id="cleanowned"> -<h2><a class="toc-backref" href="#id73">cleanowned</a></h2> -<p>Confiscates items owned by dwarfs. By default, owned food on the floor -and rotten items are confistacted and dumped.</p> -<div class="section" id="id9"> -<h3><a class="toc-backref" href="#id74">Options</a></h3> +</blockquote> +<p>Filters:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">all:</th><td class="field-body">confiscate all owned items</td> -</tr> -<tr class="field"><th class="field-name">scattered:</th><td class="field-body">confiscated and dump all items scattered on the floor</td> -</tr> -<tr class="field"><th class="field-name">x:</th><td class="field-body">confiscate/dump items with wear level 'x' and more</td> +<tr class="field"><th class="field-name">all:</th><td class="field-body">designate whole z-level</td> </tr> -<tr class="field"><th class="field-name">X:</th><td class="field-body">confiscate/dump items with wear level 'X' and more</td> +<tr class="field"><th class="field-name">hidden:</th><td class="field-body">designate only hidden tiles of z-level (default)</td> </tr> -<tr class="field"><th class="field-name">dryrun:</th><td class="field-body">a dry run. combine with other options to see what will happen -without it actually happening.</td> +<tr class="field"><th class="field-name">designated:</th><td class="field-body">Take current designation and apply pattern to it.</td> </tr> </tbody> </table> +</blockquote> +<p>After you have a pattern set, you can use 'expdig' to apply it again.</p> +<p>Examples:</p> +<blockquote> +<dl class="docutils"> +<dt>designate the diagonal 5 patter over all hidden tiles:</dt> +<dd><ul class="first last simple"> +<li>expdig diag5 hidden</li> +</ul> +</dd> +<dt>apply last used pattern and filter:</dt> +<dd><ul class="first last simple"> +<li>expdig</li> +</ul> +</dd> +<dt>Take current designations and replace them with the ladder pattern:</dt> +<dd><ul class="first last simple"> +<li>expdig ladder designated</li> +</ul> +</dd> +</dl> +</blockquote> </div> -<div class="section" id="id10"> -<h3><a class="toc-backref" href="#id75">Example:</a></h3> -<p><tt class="docutils literal">cleanowned scattered X</tt> : This will confiscate rotten and dropped food, garbage on the floors and any worn items with 'X' damage and above.</p> -</div> -</div> -<div class="section" id="colonies"> -<h2><a class="toc-backref" href="#id76">colonies</a></h2> -<p>Allows listing all the vermin colonies on the map and optionally turning them into honey bee colonies.</p> -<div class="section" id="id11"> -<h3><a class="toc-backref" href="#id77">Options</a></h3> +<div class="section" id="digcircle"> +<h3><a class="toc-backref" href="#id64">digcircle</a></h3> +<p>A command for easy designation of filled and hollow circles. +It has several types of options.</p> +<p>Shape:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">bees:</th><td class="field-body">turn colonies into honey bee colonies</td> +<tr class="field"><th class="field-name">hollow:</th><td class="field-body">Set the circle to hollow (default)</td> +</tr> +<tr class="field"><th class="field-name">filled:</th><td class="field-body">Set the circle to filled</td> +</tr> +<tr class="field"><th class="field-name">#:</th><td class="field-body">Diameter in tiles (default = 0, does nothing)</td> </tr> </tbody> </table> -</div> -</div> -<div class="section" id="deramp-by-zilpin"> -<h2><a class="toc-backref" href="#id78">deramp (by zilpin)</a></h2> -<p>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).</p> -</div> -<div class="section" id="dfusion"> -<h2><a class="toc-backref" href="#id79">dfusion</a></h2> -<p>This is the DFusion lua plugin system by warmist/darius, running as a DFHack plugin.</p> -<p>See the bay12 thread for details: <a class="reference external" href="http://www.bay12forums.com/smf/index.php?topic=69682.15">http://www.bay12forums.com/smf/index.php?topic=69682.15</a></p> -<div class="section" id="confirmed-working-dfusion-plugins"> -<h3><a class="toc-backref" href="#id80">Confirmed working DFusion plugins:</a></h3> +</blockquote> +<p>Action:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">simple_embark:</th><td class="field-body">allows changing the number of dwarves available on embark.</td> +<tr class="field"><th class="field-name">set:</th><td class="field-body">Set designation (default)</td> +</tr> +<tr class="field"><th class="field-name">unset:</th><td class="field-body">Unset current designation</td> +</tr> +<tr class="field"><th class="field-name">invert:</th><td class="field-body">Invert designations already present</td> </tr> </tbody> </table> -<div class="note"> -<p class="first admonition-title">Note</p> -<ul class="last simple"> -<li>Some of the DFusion plugins aren't completely ported yet. This can lead to crashes.</li> -<li>This is currently working only on Windows.</li> -<li>The game will be suspended while you're using dfusion. Don't panic when it doen't respond.</li> -</ul> -</div> -</div> -</div> -<div class="section" id="drybuckets"> -<h2><a class="toc-backref" href="#id81">drybuckets</a></h2> -<p>This utility removes water from all buckets in your fortress, allowing them to be safely used for making lye.</p> -</div> -<div class="section" id="fastdwarf"> -<h2><a class="toc-backref" href="#id82">fastdwarf</a></h2> -<p>Makes your minions move at ludicrous speeds.</p> -<blockquote> -<ul class="simple"> -<li>Activate with 'fastdwarf 1'</li> -<li>Deactivate with 'fastdwarf 0'</li> -</ul> </blockquote> -</div> -<div class="section" id="feature"> -<h2><a class="toc-backref" href="#id83">feature</a></h2> -<p>Enables management of map features.</p> -<ul class="simple"> -<li>Discovering a magma feature (magma pool, volcano, magma sea, or curious -underground structure) permits magma workshops and furnaces to be built.</li> -<li>Discovering a cavern layer causes plants (trees, shrubs, and grass) from -that cavern to grow within your fortress.</li> -</ul> -<div class="section" id="id12"> -<h3><a class="toc-backref" href="#id84">Options</a></h3> +<p>Designation types:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">list:</th><td class="field-body">Lists all map features in your current embark by index.</td> +<tr class="field"><th class="field-name">dig:</th><td class="field-body">Normal digging designation (default)</td> </tr> -<tr class="field"><th class="field-name">show X:</th><td class="field-body">Marks the selected map feature as discovered.</td> +<tr class="field"><th class="field-name">ramp:</th><td class="field-body">Ramp digging</td> </tr> -<tr class="field"><th class="field-name">hide X:</th><td class="field-body">Marks the selected map feature as undiscovered.</td> +<tr class="field"><th class="field-name">ustair:</th><td class="field-body">Staircase up</td> +</tr> +<tr class="field"><th class="field-name">dstair:</th><td class="field-body">Staircase down</td> +</tr> +<tr class="field"><th class="field-name">xstair:</th><td class="field-body">Staircase up/down</td> +</tr> +<tr class="field"><th class="field-name">chan:</th><td class="field-body">Dig channel</td> </tr> </tbody> </table> -</div> +</blockquote> +<p>After you have set the options, the command called with no options +repeats with the last selected parameters.</p> +<p>Examples:</p> +<ul class="simple"> +<li>'digcircle filled 3' = Dig a filled circle with radius = 3.</li> +<li>'digcircle' = Do it again.</li> +</ul> </div> <div class="section" id="filltraffic"> -<h2><a class="toc-backref" href="#id85">filltraffic</a></h2> +<h3><a class="toc-backref" href="#id65">filltraffic</a></h3> <p>Set traffic designations using flood-fill starting at the cursor.</p> -<div class="section" id="traffic-type-codes"> -<h3><a class="toc-backref" href="#id86">Traffic Type Codes:</a></h3> +<p>Traffic Type Codes:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -1132,9 +1471,9 @@ that cavern to grow within your fortress.</li> </tr> </tbody> </table> -</div> -<div class="section" id="other-options"> -<h3><a class="toc-backref" href="#id87">Other Options:</a></h3> +</blockquote> +<p>Other Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -1147,17 +1486,16 @@ that cavern to grow within your fortress.</li> </tr> </tbody> </table> -</div> -<div class="section" id="id13"> -<h3><a class="toc-backref" href="#id88">Example:</a></h3> -<p>'filltraffic H' - When used in a room with doors, it will set traffic to HIGH in just that room.</p> -</div> +</blockquote> +<p>Example:</p> +<blockquote> +'filltraffic H' - When used in a room with doors, it will set traffic to HIGH in just that room.</blockquote> </div> <div class="section" id="alltraffic"> -<h2><a class="toc-backref" href="#id89">alltraffic</a></h2> +<h3><a class="toc-backref" href="#id66">alltraffic</a></h3> <p>Set traffic designations for every single tile of the map (useful for resetting traffic designations).</p> -<div class="section" id="id14"> -<h3><a class="toc-backref" href="#id90">Traffic Type Codes:</a></h3> +<p>Traffic Type Codes:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -1172,52 +1510,18 @@ that cavern to grow within your fortress.</li> </tr> </tbody> </table> -</div> -<div class="section" id="id15"> -<h3><a class="toc-backref" href="#id91">Example:</a></h3> -<p>'alltraffic N' - Set traffic to 'normal' for all tiles.</p> -</div> -</div> -<div class="section" id="fixdiplomats"> -<h2><a class="toc-backref" href="#id92">fixdiplomats</a></h2> -<p>Up to version 0.31.12, Elves only sent Diplomats to your fortress to propose -tree cutting quotas due to a bug; once that bug was fixed, Elves stopped caring -about excess tree cutting. This command adds a Diplomat position to all Elven -civilizations, allowing them to negotiate tree cutting quotas (and allowing you -to violate them and potentially start wars) in case you haven't already modified -your raws accordingly.</p> -</div> -<div class="section" id="fixmerchants"> -<h2><a class="toc-backref" href="#id93">fixmerchants</a></h2> -<p>This command adds the Guild Representative position to all Human civilizations, -allowing them to make trade agreements (just as they did back in 0.28.181.40d -and earlier) in case you haven't already modified your raws accordingly.</p> -</div> -<div class="section" id="fixveins"> -<h2><a class="toc-backref" href="#id94">fixveins</a></h2> -<p>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.</p> -</div> -<div class="section" id="fixwagons"> -<h2><a class="toc-backref" href="#id95">fixwagons</a></h2> -<p>Due to a bug in all releases of version 0.31, merchants no longer bring wagons -with their caravans. This command re-enables them for all appropriate -civilizations.</p> -</div> -<div class="section" id="flows"> -<h2><a class="toc-backref" href="#id96">flows</a></h2> -<p>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.</p> +</blockquote> +<p>Example:</p> +<blockquote> +'alltraffic N' - Set traffic to 'normal' for all tiles.</blockquote> </div> <div class="section" id="getplants"> -<h2><a class="toc-backref" href="#id97">getplants</a></h2> +<h3><a class="toc-backref" href="#id67">getplants</a></h3> <p>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.</p> -<div class="section" id="id16"> -<h3><a class="toc-backref" href="#id98">Options</a></h3> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -1233,394 +1537,154 @@ selection)</td> </tr> </tbody> </table> +</blockquote> <p>Specifying both -t and -s will have no effect. If no plant IDs are specified, all valid plant IDs will be listed.</p> </div> </div> -<div class="section" id="tidlers"> -<h2><a class="toc-backref" href="#id99">tidlers</a></h2> -<p>Toggle between all possible positions where the idlers count can be placed.</p> -</div> -<div class="section" id="twaterlvl"> -<h2><a class="toc-backref" href="#id100">twaterlvl</a></h2> -<p>Toggle between displaying/not displaying liquid depth as numbers.</p> -</div> -<div class="section" id="job"> -<h2><a class="toc-backref" href="#id101">job</a></h2> -<p>Command for general job query and manipulation.</p> -<dl class="docutils"> -<dt>Options:</dt> -<dd><ul class="first last simple"> -<li>no extra options - Print details of the current job. The job can be selected -in a workshop, or the unit/jobs screen.</li> -<li>list - Print details of all jobs in the selected workshop.</li> -<li>item-material <item-idx> <material[:subtoken]> - Replace the exact material -id in the job item.</li> -<li>item-type <item-idx> <type[:subtype]> - Replace the exact item type id in -the job item.</li> -</ul> -</dd> -</dl> -</div> -<div class="section" id="job-material"> -<h2><a class="toc-backref" href="#id102">job-material</a></h2> -<p>Alter the material of the selected job.</p> -<p>Invoked as: job-material <inorganic-token></p> -<dl class="docutils"> -<dt>Intended to be used as a keybinding:</dt> -<dd><ul class="first last simple"> -<li>In 'q' mode, when a job is highlighted within a workshop or furnace, -changes the material of the job. Only inorganic materials can be used -in this mode.</li> -<li>In 'b' mode, during selection of building components positions the cursor -over the first available choice with the matching material.</li> -</ul> -</dd> -</dl> -</div> -<div class="section" id="job-duplicate"> -<h2><a class="toc-backref" href="#id103">job-duplicate</a></h2> -<dl class="docutils"> -<dt>Duplicate the selected job in a workshop:</dt> -<dd><ul class="first last simple"> -<li>In 'q' mode, when a job is highlighted within a workshop or furnace building, -instantly duplicates the job.</li> -</ul> -</dd> -</dl> -</div> -<div class="section" id="keybinding"> -<h2><a class="toc-backref" href="#id104">keybinding</a></h2> -<p>Manages DFHack keybindings.</p> -<p>Currently it supports any combination of Ctrl/Alt/Shift with F1-F9, or A-Z.</p> -<div class="section" id="id17"> -<h3><a class="toc-backref" href="#id105">Options</a></h3> +<div class="section" id="cleanup-and-garbage-disposal"> +<h2><a class="toc-backref" href="#id68">Cleanup and garbage disposal</a></h2> +<div class="section" id="clean"> +<h3><a class="toc-backref" href="#id69">clean</a></h3> +<p>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.</p> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name" colspan="2">keybinding list <key>:</th></tr> -<tr class="field"><td> </td><td class="field-body">List bindings active for the key combination.</td> -</tr> -<tr class="field"><th class="field-name" colspan="2">keybinding clear <key> <key>...:</th></tr> -<tr class="field"><td> </td><td class="field-body">Remove bindings for the specified keys.</td> +<tr class="field"><th class="field-name">map:</th><td class="field-body">Clean the map tiles. By default, it leaves mud and snow alone.</td> </tr> -<tr class="field"><th class="field-name" colspan="2">keybinding add <key> "cmdline" "cmdline"...:</th></tr> -<tr class="field"><td> </td><td class="field-body">Add bindings for the specified -key.</td> +<tr class="field"><th class="field-name">units:</th><td class="field-body">Clean the creatures. Will also clean hostiles.</td> </tr> -<tr class="field"><th class="field-name" colspan="2">keybinding set <key> "cmdline" "cmdline"...:</th></tr> -<tr class="field"><td> </td><td class="field-body">Clear, and then add bindings for -the specified key.</td> +<tr class="field"><th class="field-name">items:</th><td class="field-body">Clean all the items. Even a poisoned blade.</td> </tr> </tbody> </table> -<p>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.</p> -</div> -</div> -<div class="section" id="liquids"> -<h2><a class="toc-backref" href="#id106">liquids</a></h2> -<p>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).</p> -<p>For more information, refer to the command's internal help.</p> -<div class="note"> -<p class="first admonition-title">Note</p> -<p class="last">Spawning and deleting liquids can F up pathing data and -temperatures (creating heat traps). You've been warned.</p> -</div> -</div> -<div class="section" id="liquids-here"> -<h2><a class="toc-backref" href="#id107">liquids-here</a></h2> -<p>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).</p> -<p>Intended to be used as keybinding. Requires an active in-game cursor.</p> -</div> -<div class="section" id="mode"> -<h2><a class="toc-backref" href="#id108">mode</a></h2> -<p>This command lets you see and change the game mode directly. -Not all combinations are good for every situation and most of them will -produce undesirable results. There are a few good ones though.</p> -<div class="admonition-example admonition"> -<p class="first admonition-title">Example</p> -<p class="last">You are in fort game mode, managing your fortress and paused. -You switch to the arena game mode, <em>assume control of a creature</em> and then -switch to adventure game mode(1). -You just lost a fortress and gained an adventurer. -You could also do this. -You are in fort game mode, managing your fortress and paused at the esc menu. -You switch to the adventure game mode, then use Dfusion to <em>assume control of a creature</em> and then -save or retire. -You just created a returnable mountain home and gained an adventurer.</p> -</div> -<p>I take no responsibility of anything that happens as a result of using this tool</p> -</div> -<div class="section" id="extirpate"> -<h2><a class="toc-backref" href="#id109">extirpate</a></h2> -<p>A tool for getting rid of trees and shrubs. By default, it only kills -a tree/shrub under the cursor. The plants are turned into ashes instantly.</p> -<div class="section" id="id18"> -<h3><a class="toc-backref" href="#id110">Options</a></h3> +</blockquote> +<p>Extra options for 'map':</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">shrubs:</th><td class="field-body">affect all shrubs on the map</td> -</tr> -<tr class="field"><th class="field-name">trees:</th><td class="field-body">affect all trees on the map</td> +<tr class="field"><th class="field-name">mud:</th><td class="field-body">Remove mud in addition to the normal stuff.</td> </tr> -<tr class="field"><th class="field-name">all:</th><td class="field-body">affect every plant!</td> +<tr class="field"><th class="field-name">snow:</th><td class="field-body">Also remove snow coverings.</td> </tr> </tbody> </table> +</blockquote> </div> +<div class="section" id="spotclean"> +<h3><a class="toc-backref" href="#id70">spotclean</a></h3> +<p>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.</p> </div> -<div class="section" id="grow"> -<h2><a class="toc-backref" href="#id111">grow</a></h2> -<p>Makes all saplings present on the map grow into trees (almost) instantly.</p> -</div> -<div class="section" id="immolate"> -<h2><a class="toc-backref" href="#id112">immolate</a></h2> -<p>Very similar to extirpate, but additionally sets the plants on fire. The fires -can and <em>will</em> spread ;)</p> -</div> -<div class="section" id="probe"> -<h2><a class="toc-backref" href="#id113">probe</a></h2> -<p>Can be used to determine tile properties like temperature.</p> -</div> -<div class="section" id="prospect"> -<h2><a class="toc-backref" href="#id114">prospect</a></h2> -<p>Prints a big list of all the present minerals and plants. By default, only -the visible part of the map is scanned.</p> -<div class="section" id="id19"> -<h3><a class="toc-backref" href="#id115">Options</a></h3> +<div class="section" id="autodump"> +<h3><a class="toc-backref" href="#id71">autodump</a></h3> +<p>This utility lets you quickly move all items designated to be dumped. +Items are instantly moved to the cursor position, the dump flag is unset, +and the forbid flag is set, as if it had been dumped normally. +Be aware that any active dump item tasks still point at the item.</p> +<p>Cursor must be placed on a floor tile so the items can be dumped there.</p> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">all:</th><td class="field-body">Scan the whole map, as if it was revealed.</td> +<tr class="field"><th class="field-name">destroy:</th><td class="field-body">Destroy instead of dumping. Doesn't require a cursor.</td> </tr> -<tr class="field"><th class="field-name">value:</th><td class="field-body">Show material value in the output. Most useful for gems.</td> +<tr class="field"><th class="field-name">destroy-here:</th><td class="field-body">Destroy items only under the cursor.</td> </tr> -<tr class="field"><th class="field-name">hell:</th><td class="field-body">Show the Z range of HFS tubes. Implies 'all'.</td> +<tr class="field"><th class="field-name">visible:</th><td class="field-body">Only process items that are not hidden.</td> </tr> -</tbody> -</table> -</div> -<div class="section" id="pre-embark-estimate"> -<h3><a class="toc-backref" href="#id116">Pre-embark estimate</a></h3> -<p>If called during the embark selection screen, displays an estimate of layer -stone availability. If the 'all' option is specified, also estimates veins. -The estimate is computed either for 1 embark tile of the blinking biome, or -for all tiles of the embark rectangle.</p> -</div> -<div class="section" id="id20"> -<h3><a class="toc-backref" href="#id117">Options</a></h3> -<table class="docutils field-list" frame="void" rules="none"> -<col class="field-name" /> -<col class="field-body" /> -<tbody valign="top"> -<tr class="field"><th class="field-name">all:</th><td class="field-body">processes all tiles, even hidden ones.</td> +<tr class="field"><th class="field-name">hidden:</th><td class="field-body">Only process hidden items.</td> +</tr> +<tr class="field"><th class="field-name">forbidden:</th><td class="field-body">Only process forbidden items (default: only unforbidden).</td> </tr> </tbody> </table> +</blockquote> </div> +<div class="section" id="autodump-destroy-here"> +<h3><a class="toc-backref" href="#id72">autodump-destroy-here</a></h3> +<p>Destroy items marked for dumping under cursor. Identical to autodump +destroy-here, but intended for use as keybinding.</p> </div> -<div class="section" id="regrass"> -<h2><a class="toc-backref" href="#id118">regrass</a></h2> -<p>Regrows grass. Not much to it ;)</p> +<div class="section" id="autodump-destroy-item"> +<h3><a class="toc-backref" href="#id73">autodump-destroy-item</a></h3> +<p>Destroy the selected item. The item may be selected in the 'k' list, or inside +a container. If called again before the game is resumed, cancels destroy.</p> </div> -<div class="section" id="rename"> -<h2><a class="toc-backref" href="#id119">rename</a></h2> -<p>Allows renaming various things.</p> -<div class="section" id="id21"> -<h3><a class="toc-backref" href="#id120">Options</a></h3> +<div class="section" id="cleanowned"> +<h3><a class="toc-backref" href="#id74">cleanowned</a></h3> +<p>Confiscates items owned by dwarfs. By default, owned food on the floor +and rotten items are confistacted and dumped.</p> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name" colspan="2">rename squad <index> "name":</th></tr> -<tr class="field"><td> </td><td class="field-body">Rename squad by index to 'name'.</td> -</tr> -<tr class="field"><th class="field-name" colspan="2">rename hotkey <index> "name":</th></tr> -<tr class="field"><td> </td><td class="field-body">Rename hotkey by index. This allows assigning -longer commands to the DF hotkeys.</td> +<tr class="field"><th class="field-name">all:</th><td class="field-body">confiscate all owned items</td> </tr> -<tr class="field"><th class="field-name" colspan="2">rename unit "nickname":</th></tr> -<tr class="field"><td> </td><td class="field-body">Rename a unit/creature highlighted in the DF user -interface.</td> +<tr class="field"><th class="field-name">scattered:</th><td class="field-body">confiscated and dump all items scattered on the floor</td> </tr> -<tr class="field"><th class="field-name" colspan="2">rename unit-profession "custom profession":</th></tr> -<tr class="field"><td> </td><td class="field-body">Change proffession name of the -highlighted unit/creature.</td> +<tr class="field"><th class="field-name">x:</th><td class="field-body">confiscate/dump items with wear level 'x' and more</td> </tr> -</tbody> -</table> -</div> -</div> -<div class="section" id="reveal"> -<h2><a class="toc-backref" href="#id121">reveal</a></h2> -<p>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'.</p> -<p>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'.</p> -</div> -<div class="section" id="unreveal"> -<h2><a class="toc-backref" href="#id122">unreveal</a></h2> -<p>Reverts the effects of 'reveal'.</p> -</div> -<div class="section" id="revtoggle"> -<h2><a class="toc-backref" href="#id123">revtoggle</a></h2> -<p>Switches between 'reveal' and 'unreveal'.</p> -</div> -<div class="section" id="revflood"> -<h2><a class="toc-backref" href="#id124">revflood</a></h2> -<p>This command will hide the whole map and then reveal all the tiles that have -a path to the in-game cursor.</p> -</div> -<div class="section" id="revforget"> -<h2><a class="toc-backref" href="#id125">revforget</a></h2> -<p>When you use reveal, it saves information about what was/wasn't visible before -revealing everything. Unreveal uses this information to hide things again. -This command throws away the information. For example, use in cases where -you abandoned with the fort revealed and no longer want the data.</p> -</div> -<div class="section" id="lair"> -<h2><a class="toc-backref" href="#id126">lair</a></h2> -<p>This command allows you to mark the map as 'monster lair', preventing item -scatter on abandon. When invoked as 'lair reset', it does the opposite.</p> -<p>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'.</p> -<div class="section" id="id22"> -<h3><a class="toc-backref" href="#id127">Options</a></h3> -<table class="docutils field-list" frame="void" rules="none"> -<col class="field-name" /> -<col class="field-body" /> -<tbody valign="top"> -<tr class="field"><th class="field-name">lair:</th><td class="field-body">Mark the map as monster lair</td> +<tr class="field"><th class="field-name">X:</th><td class="field-body">confiscate/dump items with wear level 'X' and more</td> </tr> -<tr class="field"><th class="field-name">lair reset:</th><td class="field-body">Mark the map as ordinary (not lair)</td> +<tr class="field"><th class="field-name">dryrun:</th><td class="field-body">a dry run. combine with other options to see what will happen +without it actually happening.</td> </tr> </tbody> </table> -</div> -</div> -<div class="section" id="seedwatch"> -<h2><a class="toc-backref" href="#id128">seedwatch</a></h2> -<p>Tool for turning cooking of seeds and plants on/off depending on how much you -have of them.</p> -<p>See 'seedwatch help' for detailed description.</p> -</div> -<div class="section" id="showmood"> -<h2><a class="toc-backref" href="#id129">showmood</a></h2> -<p>Shows all items needed for the currently active strange mood.</p> -</div> -<div class="section" id="copystock"> -<h2><a class="toc-backref" href="#id130">copystock</a></h2> -<p>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.</p> -</div> -<div class="section" id="ssense-stonesense"> -<h2><a class="toc-backref" href="#id131">ssense / stonesense</a></h2> -<p>An isometric visualizer that runs in a second window. This requires working -graphics acceleration and at least a dual core CPU (otherwise it will slow -down DF).</p> -<p>All the data resides in the 'stonesense' directory. For detailed instructions, -see stonesense/README.txt</p> -<p>Compatible with Windows > XP SP3 and most modern Linux distributions.</p> -<p>Older versions, support and extra graphics can be found in the bay12 forum -thread: <a class="reference external" href="http://www.bay12forums.com/smf/index.php?topic=43260.0">http://www.bay12forums.com/smf/index.php?topic=43260.0</a></p> -<p>Some additional resources: -<a class="reference external" href="http://df.magmawiki.com/index.php/Utility:Stonesense/Content_repository">http://df.magmawiki.com/index.php/Utility:Stonesense/Content_repository</a></p> -</div> -<div class="section" id="tiletypes"> -<h2><a class="toc-backref" href="#id132">tiletypes</a></h2> -<p>Can be used for painting map tiles and is an interactive command, much like -liquids.</p> -<p>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.</p> -<p>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.</p> -<p>The properties of filter and paint can be partially defined. This means that -you can for example do something like this:</p> -<pre class="literal-block"> -filter material STONE -filter shape FORTIFICATION -paint shape FLOOR -</pre> -<p>This will turn all stone fortifications into floors, preserving the material.</p> -<p>Or this:</p> -<pre class="literal-block"> -filter shape FLOOR -filter material MINERAL -paint shape WALL -</pre> -<p>Turning mineral vein floors back into walls.</p> -<p>The tool also allows tweaking some tile flags:</p> -<p>Or this:</p> -<pre class="literal-block"> -paint hidden 1 -paint hidden 0 -</pre> -<p>This will hide previously revealed tiles (or show hidden with the 0 option).</p> -<p>Any paint or filter option (or the entire paint or filter) can be disabled entirely by using the ANY keyword:</p> -<pre class="literal-block"> -paint hidden ANY -paint shape ANY -filter material any -filter shape any -filter any -</pre> +</blockquote> +<p>Example:</p> +<blockquote> <dl class="docutils"> -<dt>You can use several different brushes for painting tiles:</dt> -<dd><ul class="first last simple"> -<li>Point. (point)</li> -<li>Rectangular range. (range)</li> -<li>A column ranging from current cursor to the first solid tile above. (column)</li> -<li>DF map block - 16x16 tiles, in a regular grid. (block)</li> -</ul> -</dd> +<dt><tt class="docutils literal">cleanowned scattered X</tt></dt> +<dd>This will confiscate rotten and dropped food, garbage on the floors and any +worn items with 'X' damage and above.</dd> </dl> -<p>Example:</p> -<pre class="literal-block"> -range 10 10 1 -</pre> -<p>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.</p> -<p>For more details, see the 'help' command while using this.</p> +</blockquote> </div> -<div class="section" id="tiletypes-commands"> -<h2><a class="toc-backref" href="#id133">tiletypes-commands</a></h2> -<p>Runs tiletypes commands, separated by ;. This makes it possible to change -tiletypes modes from a hotkey.</p> </div> -<div class="section" id="tiletypes-here"> -<h2><a class="toc-backref" href="#id134">tiletypes-here</a></h2> -<p>Apply the current tiletypes options at the in-game cursor position, including -the brush. Can be used from a hotkey.</p> +<div class="section" id="bugfixes"> +<h2><a class="toc-backref" href="#id75">Bugfixes</a></h2> +<div class="section" id="drybuckets"> +<h3><a class="toc-backref" href="#id76">drybuckets</a></h3> +<p>This utility removes water from all buckets in your fortress, allowing them to be safely used for making lye.</p> </div> -<div class="section" id="tiletypes-here-point"> -<h2><a class="toc-backref" href="#id135">tiletypes-here-point</a></h2> -<p>Apply the current tiletypes options at the in-game cursor position to a single -tile. Can be used from a hotkey.</p> +<div class="section" id="fixdiplomats"> +<h3><a class="toc-backref" href="#id77">fixdiplomats</a></h3> +<p>Up to version 0.31.12, Elves only sent Diplomats to your fortress to propose +tree cutting quotas due to a bug; once that bug was fixed, Elves stopped caring +about excess tree cutting. This command adds a Diplomat position to all Elven +civilizations, allowing them to negotiate tree cutting quotas (and allowing you +to violate them and potentially start wars) in case you haven't already modified +your raws accordingly.</p> +</div> +<div class="section" id="fixmerchants"> +<h3><a class="toc-backref" href="#id78">fixmerchants</a></h3> +<p>This command adds the Guild Representative position to all Human civilizations, +allowing them to make trade agreements (just as they did back in 0.28.181.40d +and earlier) in case you haven't already modified your raws accordingly.</p> +</div> +<div class="section" id="fixveins"> +<h3><a class="toc-backref" href="#id79">fixveins</a></h3> +<p>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.</p> </div> <div class="section" id="tweak"> -<h2><a class="toc-backref" href="#id136">tweak</a></h2> -<p>Contains various tweaks for minor bugs (currently just one).</p> -<div class="section" id="id23"> -<h3><a class="toc-backref" href="#id137">Options</a></h3> +<h3><a class="toc-backref" href="#id80">tweak</a></h3> +<p>Contains various tweaks for minor bugs.</p> +<p>One-shot subcommands:</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -1658,188 +1722,166 @@ they are scuttled.</td> </tr> </tbody> </table> -</div> -</div> -<div class="section" id="tubefill"> -<h2><a class="toc-backref" href="#id138">tubefill</a></h2> -<p>Fills all the adamantine veins again. Veins that were empty will be filled in -too, but might still trigger a demon invasion (this is a known bug).</p> -</div> -<div class="section" id="digv"> -<h2><a class="toc-backref" href="#id139">digv</a></h2> -<p>Designates a whole vein for digging. Requires an active in-game cursor placed -over a vein tile. With the 'x' option, it will traverse z-levels (putting stairs -between the same-material tiles).</p> -</div> -<div class="section" id="digvx"> -<h2><a class="toc-backref" href="#id140">digvx</a></h2> -<p>A permanent alias for 'digv x'.</p> -</div> -<div class="section" id="digl"> -<h2><a class="toc-backref" href="#id141">digl</a></h2> -<p>Designates layer stone for digging. Requires an active in-game cursor placed -over a layer stone tile. With the 'x' option, it will traverse z-levels -(putting stairs between the same-material tiles). With the 'undo' option it -will remove the dig designation instead (if you realize that digging out a 50 -z-level deep layer was not such a good idea after all).</p> -</div> -<div class="section" id="diglx"> -<h2><a class="toc-backref" href="#id142">diglx</a></h2> -<p>A permanent alias for 'digl x'.</p> -</div> -<div class="section" id="digexp"> -<h2><a class="toc-backref" href="#id143">digexp</a></h2> -<p>This command can be used for exploratory mining.</p> -<p>See: <a class="reference external" href="http://df.magmawiki.com/index.php/DF2010:Exploratory_mining">http://df.magmawiki.com/index.php/DF2010:Exploratory_mining</a></p> -<p>There are two variables that can be set: pattern and filter.</p> -<div class="section" id="patterns"> -<h3><a class="toc-backref" href="#id144">Patterns:</a></h3> +<p>Subcommands that persist until disabled or DF quit:</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">diag5:</th><td class="field-body">diagonals separated by 5 tiles</td> +<tr class="field"><th class="field-name">stable-cursor:</th><td class="field-body">Saves the exact cursor position between t/q/k/d/etc menus of dwarfmode.</td> </tr> -<tr class="field"><th class="field-name">diag5r:</th><td class="field-body">diag5 rotated 90 degrees</td> -</tr> -<tr class="field"><th class="field-name">ladder:</th><td class="field-body">A 'ladder' pattern</td> +<tr class="field"><th class="field-name">patrol-duty:</th><td class="field-body">Makes Train orders not count as patrol duty to stop unhappy thoughts. +Does NOT fix the problem when soldiers go off-duty (i.e. civilian).</td> </tr> -<tr class="field"><th class="field-name">ladderr:</th><td class="field-body">ladder rotated 90 degrees</td> +<tr class="field"><th class="field-name" colspan="2">readable-build-plate:</th></tr> +<tr class="field"><td> </td><td class="field-body">Fixes rendering of creature weight limits in pressure plate build menu.</td> </tr> -<tr class="field"><th class="field-name">clear:</th><td class="field-body">Just remove all dig designations</td> +<tr class="field"><th class="field-name">stable-temp:</th><td class="field-body">Fixes performance bug 6012 by squashing jitter in temperature updates. +In very item-heavy forts with big stockpiles this can improve FPS by 50-100%</td> </tr> -<tr class="field"><th class="field-name">cross:</th><td class="field-body">A cross, exactly in the middle of the map.</td> +<tr class="field"><th class="field-name">fast-heat:</th><td class="field-body">Further improves temperature update performance by ensuring that 1 degree +of item temperature is crossed in no more than specified number of frames +when updating from the environment temperature. This reduces the time it +takes for stable-temp to stop updates again when equilibrium is disturbed.</td> </tr> -</tbody> -</table> -</div> -<div class="section" id="filters"> -<h3><a class="toc-backref" href="#id145">Filters:</a></h3> -<table class="docutils field-list" frame="void" rules="none"> -<col class="field-name" /> -<col class="field-body" /> -<tbody valign="top"> -<tr class="field"><th class="field-name">all:</th><td class="field-body">designate whole z-level</td> +<tr class="field"><th class="field-name">fix-dimensions:</th><td class="field-body">Fixes subtracting small amount of thread/cloth/liquid from a stack +by splitting the stack and subtracting from the remaining single item. +This is a necessary addition to the binary patch in bug 808.</td> </tr> -<tr class="field"><th class="field-name">hidden:</th><td class="field-body">designate only hidden tiles of z-level (default)</td> +<tr class="field"><th class="field-name" colspan="2">advmode-contained:</th></tr> +<tr class="field"><td> </td><td class="field-body">Works around bug 6202, i.e. custom reactions with container inputs +in advmode. The issue is that the screen tries to force you to select +the contents separately from the container. This forcefully skips child +reagents.</td> </tr> -<tr class="field"><th class="field-name">designated:</th><td class="field-body">Take current designation and apply pattern to it.</td> +<tr class="field"><th class="field-name">fast-trade:</th><td class="field-body">Makes Shift-Enter in the Move Goods to Depot and Trade screens select +the current item (fully, in case of a stack), and scroll down one line.</td> </tr> </tbody> </table> -<p>After you have a pattern set, you can use 'expdig' to apply it again.</p> -</div> -<div class="section" id="id24"> -<h3><a class="toc-backref" href="#id146">Examples:</a></h3> -<dl class="docutils"> -<dt>designate the diagonal 5 patter over all hidden tiles:</dt> -<dd><ul class="first last simple"> -<li>expdig diag5 hidden</li> -</ul> -</dd> -<dt>apply last used pattern and filter:</dt> -<dd><ul class="first last simple"> -<li>expdig</li> -</ul> -</dd> -<dt>Take current designations and replace them with the ladder pattern:</dt> -<dd><ul class="first last simple"> -<li>expdig ladder designated</li> -</ul> -</dd> -</dl> </div> </div> -<div class="section" id="digcircle"> -<h2><a class="toc-backref" href="#id147">digcircle</a></h2> -<p>A command for easy designation of filled and hollow circles. -It has several types of options.</p> -<div class="section" id="shape"> -<h3><a class="toc-backref" href="#id148">Shape:</a></h3> +<div class="section" id="mode-switch-and-reclaim"> +<h2><a class="toc-backref" href="#id81">Mode switch and reclaim</a></h2> +<div class="section" id="lair"> +<h3><a class="toc-backref" href="#id82">lair</a></h3> +<p>This command allows you to mark the map as 'monster lair', preventing item +scatter on abandon. When invoked as 'lair reset', it does the opposite.</p> +<p>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'.</p> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> -<tr class="field"><th class="field-name">hollow:</th><td class="field-body">Set the circle to hollow (default)</td> -</tr> -<tr class="field"><th class="field-name">filled:</th><td class="field-body">Set the circle to filled</td> +<tr class="field"><th class="field-name">lair:</th><td class="field-body">Mark the map as monster lair</td> </tr> -<tr class="field"><th class="field-name">#:</th><td class="field-body">Diameter in tiles (default = 0, does nothing)</td> +<tr class="field"><th class="field-name">lair reset:</th><td class="field-body">Mark the map as ordinary (not lair)</td> </tr> </tbody> </table> +</blockquote> </div> -<div class="section" id="action"> -<h3><a class="toc-backref" href="#id149">Action:</a></h3> -<table class="docutils field-list" frame="void" rules="none"> -<col class="field-name" /> -<col class="field-body" /> -<tbody valign="top"> -<tr class="field"><th class="field-name">set:</th><td class="field-body">Set designation (default)</td> -</tr> -<tr class="field"><th class="field-name">unset:</th><td class="field-body">Unset current designation</td> -</tr> -<tr class="field"><th class="field-name">invert:</th><td class="field-body">Invert designations already present</td> -</tr> -</tbody> -</table> +<div class="section" id="mode"> +<h3><a class="toc-backref" href="#id83">mode</a></h3> +<p>This command lets you see and change the game mode directly. +Not all combinations are good for every situation and most of them will +produce undesirable results. There are a few good ones though.</p> +<div class="admonition-example admonition"> +<p class="first admonition-title">Example</p> +<p class="last">You are in fort game mode, managing your fortress and paused. +You switch to the arena game mode, <em>assume control of a creature</em> and then +switch to adventure game mode(1). +You just lost a fortress and gained an adventurer. +You could also do this. +You are in fort game mode, managing your fortress and paused at the esc menu. +You switch to the adventure game mode, then use Dfusion to <em>assume control of a creature</em> and then +save or retire. +You just created a returnable mountain home and gained an adventurer.</p> </div> -<div class="section" id="designation-types"> -<h3><a class="toc-backref" href="#id150">Designation types:</a></h3> -<table class="docutils field-list" frame="void" rules="none"> -<col class="field-name" /> -<col class="field-body" /> -<tbody valign="top"> -<tr class="field"><th class="field-name">dig:</th><td class="field-body">Normal digging designation (default)</td> -</tr> -<tr class="field"><th class="field-name">ramp:</th><td class="field-body">Ramp digging</td> -</tr> -<tr class="field"><th class="field-name">ustair:</th><td class="field-body">Staircase up</td> -</tr> -<tr class="field"><th class="field-name">dstair:</th><td class="field-body">Staircase down</td> -</tr> -<tr class="field"><th class="field-name">xstair:</th><td class="field-body">Staircase up/down</td> -</tr> -<tr class="field"><th class="field-name">chan:</th><td class="field-body">Dig channel</td> -</tr> -</tbody> -</table> -<p>After you have set the options, the command called with no options -repeats with the last selected parameters.</p> +<p>I take no responsibility of anything that happens as a result of using this tool</p> </div> -<div class="section" id="id25"> -<h3><a class="toc-backref" href="#id151">Examples:</a></h3> -<ul class="simple"> -<li>'digcircle filled 3' = Dig a filled circle with radius = 3.</li> -<li>'digcircle' = Do it again.</li> -</ul> </div> +<div class="section" id="visualizer-and-data-export"> +<h2><a class="toc-backref" href="#id84">Visualizer and data export</a></h2> +<div class="section" id="ssense-stonesense"> +<h3><a class="toc-backref" href="#id85">ssense / stonesense</a></h3> +<p>An isometric visualizer that runs in a second window. This requires working +graphics acceleration and at least a dual core CPU (otherwise it will slow +down DF).</p> +<p>All the data resides in the 'stonesense' directory. For detailed instructions, +see stonesense/README.txt</p> +<p>Compatible with Windows > XP SP3 and most modern Linux distributions.</p> +<p>Older versions, support and extra graphics can be found in the bay12 forum +thread: <a class="reference external" href="http://www.bay12forums.com/smf/index.php?topic=43260.0">http://www.bay12forums.com/smf/index.php?topic=43260.0</a></p> +<p>Some additional resources: +<a class="reference external" href="http://df.magmawiki.com/index.php/Utility:Stonesense/Content_repository">http://df.magmawiki.com/index.php/Utility:Stonesense/Content_repository</a></p> </div> -<div class="section" id="weather"> -<h2><a class="toc-backref" href="#id152">weather</a></h2> -<p>Prints the current weather map by default.</p> -<p>Also lets you change the current weather to 'clear sky', 'rainy' or 'snowing'.</p> -<div class="section" id="id26"> -<h3><a class="toc-backref" href="#id153">Options:</a></h3> -<table class="docutils field-list" frame="void" rules="none"> -<col class="field-name" /> -<col class="field-body" /> -<tbody valign="top"> -<tr class="field"><th class="field-name">snow:</th><td class="field-body">make it snow everywhere.</td> -</tr> -<tr class="field"><th class="field-name">rain:</th><td class="field-body">make it rain.</td> -</tr> -<tr class="field"><th class="field-name">clear:</th><td class="field-body">clear the sky.</td> -</tr> -</tbody> -</table> +<div class="section" id="mapexport"> +<h3><a class="toc-backref" href="#id86">mapexport</a></h3> +<p>Export the current loaded map as a file. This will be eventually usable +with visualizers.</p> +</div> +<div class="section" id="dwarfexport"> +<h3><a class="toc-backref" href="#id87">dwarfexport</a></h3> +<p>Export dwarves to RuneSmith-compatible XML.</p> +</div> +</div> +<div class="section" id="job-management"> +<h2><a class="toc-backref" href="#id88">Job management</a></h2> +<div class="section" id="job"> +<h3><a class="toc-backref" href="#id89">job</a></h3> +<p>Command for general job query and manipulation.</p> +<dl class="docutils"> +<dt>Options:</dt> +<dd><dl class="first last docutils"> +<dt><em>no extra options</em></dt> +<dd>Print details of the current job. The job can be selected +in a workshop, or the unit/jobs screen.</dd> +<dt><strong>list</strong></dt> +<dd>Print details of all jobs in the selected workshop.</dd> +<dt><strong>item-material <item-idx> <material[:subtoken]></strong></dt> +<dd>Replace the exact material id in the job item.</dd> +<dt><strong>item-type <item-idx> <type[:subtype]></strong></dt> +<dd>Replace the exact item type id in the job item.</dd> +</dl> +</dd> +</dl> +</div> +<div class="section" id="job-material"> +<h3><a class="toc-backref" href="#id90">job-material</a></h3> +<p>Alter the material of the selected job.</p> +<p>Invoked as:</p> +<pre class="literal-block"> +job-material <inorganic-token> +</pre> +<p>Intended to be used as a keybinding:</p> +<blockquote> +<ul class="simple"> +<li>In 'q' mode, when a job is highlighted within a workshop or furnace, +changes the material of the job. Only inorganic materials can be used +in this mode.</li> +<li>In 'b' mode, during selection of building components positions the cursor +over the first available choice with the matching material.</li> +</ul> +</blockquote> </div> +<div class="section" id="job-duplicate"> +<h3><a class="toc-backref" href="#id91">job-duplicate</a></h3> +<dl class="docutils"> +<dt>Duplicate the selected job in a workshop:</dt> +<dd><ul class="first last simple"> +<li>In 'q' mode, when a job is highlighted within a workshop or furnace building, +instantly duplicates the job.</li> +</ul> +</dd> +</dl> </div> <div class="section" id="workflow"> -<h2><a class="toc-backref" href="#id154">workflow</a></h2> +<h3><a class="toc-backref" href="#id92">workflow</a></h3> <p>Manage control of repeat jobs.</p> -<div class="section" id="id27"> -<h3><a class="toc-backref" href="#id155">Usage</a></h3> +<p>Usage:</p> +<blockquote> <dl class="docutils"> <dt><tt class="docutils literal">workflow enable <span class="pre">[option...],</span> workflow disable <span class="pre">[option...]</span></tt></dt> <dd><p class="first">If no options are specified, enables or disables the plugin. @@ -1858,9 +1900,9 @@ Otherwise, enables or disables any of the following options:</p> <dt><tt class="docutils literal">workflow unlimit <span class="pre"><constraint-spec></span></tt></dt> <dd>Delete a constraint.</dd> </dl> -</div> +</blockquote> <div class="section" id="function"> -<h3><a class="toc-backref" href="#id156">Function</a></h3> +<h4><a class="toc-backref" href="#id93">Function</a></h4> <p>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.</p> @@ -1871,7 +1913,7 @@ the amount has to drop before jobs are resumed; this is intended to reduce the frequency of jobs being toggled.</p> </div> <div class="section" id="constraint-examples"> -<h3><a class="toc-backref" href="#id157">Constraint examples</a></h3> +<h4><a class="toc-backref" href="#id94">Constraint examples</a></h4> <p>Keep metal bolts within 900-1000, and wood/bone within 150-200.</p> <pre class="literal-block"> workflow amount AMMO:ITEM_AMMO_BOLTS/METAL 1000 100 @@ -1908,20 +1950,20 @@ command. </pre> </div> </div> -<div class="section" id="mapexport"> -<h2><a class="toc-backref" href="#id158">mapexport</a></h2> -<p>Export the current loaded map as a file. This will be eventually usable -with visualizers.</p> </div> -<div class="section" id="dwarfexport"> -<h2><a class="toc-backref" href="#id159">dwarfexport</a></h2> -<p>Export dwarves to RuneSmith-compatible XML.</p> +<div class="section" id="fortress-activity-management"> +<h2><a class="toc-backref" href="#id95">Fortress activity management</a></h2> +<div class="section" id="seedwatch"> +<h3><a class="toc-backref" href="#id96">seedwatch</a></h3> +<p>Tool for turning cooking of seeds and plants on/off depending on how much you +have of them.</p> +<p>See 'seedwatch help' for detailed description.</p> </div> <div class="section" id="zone"> -<h2><a class="toc-backref" href="#id160">zone</a></h2> +<h3><a class="toc-backref" href="#id97">zone</a></h3> <p>Helps a bit with managing activity zones (pens, pastures and pits) and cages.</p> -<div class="section" id="id28"> -<h3><a class="toc-backref" href="#id161">Options:</a></h3> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -1958,9 +2000,9 @@ the cursor are listed.</td> </tr> </tbody> </table> -</div> -<div class="section" id="id29"> -<h3><a class="toc-backref" href="#id162">Filters:</a></h3> +</blockquote> +<p>Filters:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -2015,9 +2057,9 @@ for war/hunt). Negatable.</td> </tr> </tbody> </table> -</div> +</blockquote> <div class="section" id="usage-with-single-units"> -<h3><a class="toc-backref" href="#id163">Usage with single units</a></h3> +<h4><a class="toc-backref" href="#id98">Usage with single units</a></h4> <p>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 @@ -2026,7 +2068,7 @@ and use 'zone assign' to assign them to their new home. Allows pitting your own dwarves, by the way.</p> </div> <div class="section" id="usage-with-filters"> -<h3><a class="toc-backref" href="#id164">Usage with filters</a></h3> +<h4><a class="toc-backref" href="#id99">Usage with filters</a></h4> <p>All filters can be used together with the 'assign' command.</p> <p>Restrictions: It's not possible to assign units who are inside built cages or chained because in most cases that won't be desirable anyways. @@ -2044,14 +2086,14 @@ are not properly added to your own stocks; slaughtering them should work).</p> <p>Most filters can be negated (e.g. 'not grazer' -> race is not a grazer).</p> </div> <div class="section" id="mass-renaming"> -<h3><a class="toc-backref" href="#id165">Mass-renaming</a></h3> +<h4><a class="toc-backref" href="#id100">Mass-renaming</a></h4> <p>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.</p> </div> <div class="section" id="cage-zones"> -<h3><a class="toc-backref" href="#id166">Cage zones</a></h3> +<h4><a class="toc-backref" href="#id101">Cage zones</a></h4> <p>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 @@ -2061,8 +2103,8 @@ all cages you want to use. Then use 'zone set' (like with 'assign') and use would make no sense, but can be used together with 'nick' or 'remnick' and all the usual filters.</p> </div> -<div class="section" id="id30"> -<h3><a class="toc-backref" href="#id167">Examples</a></h3> +<div class="section" id="examples"> +<h4><a class="toc-backref" href="#id102">Examples</a></h4> <dl class="docutils"> <dt><tt class="docutils literal">zone assign all own ALPACA minage 3 maxage 10</tt></dt> <dd>Assign all own alpacas who are between 3 and 10 years old to the selected @@ -2088,7 +2130,7 @@ on the current default zone.</dd> </div> </div> <div class="section" id="autonestbox"> -<h2><a class="toc-backref" href="#id168">autonestbox</a></h2> +<h3><a class="toc-backref" href="#id103">autonestbox</a></h3> <p>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 @@ -2098,8 +2140,8 @@ 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.</p> -<div class="section" id="id31"> -<h3><a class="toc-backref" href="#id169">Options:</a></h3> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -2114,10 +2156,10 @@ frames between runs.</td> </tr> </tbody> </table> -</div> +</blockquote> </div> <div class="section" id="autobutcher"> -<h2><a class="toc-backref" href="#id170">autobutcher</a></h2> +<h3><a class="toc-backref" href="#id104">autobutcher</a></h3> <p>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.</p> <p>Named units will be completely ignored (to protect specific animals from @@ -2130,8 +2172,8 @@ units or with 'zone nick' to mass-rename units in pastures and cages).</p> Once you have too much kids, the youngest will be butchered first. If you don't set any target count the following default will be used: 1 male kid, 5 female kids, 1 male adult, 5 female adults.</p> -<div class="section" id="id32"> -<h3><a class="toc-backref" href="#id171">Options:</a></h3> +<p>Options:</p> +<blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> @@ -2182,9 +2224,8 @@ for future entries.</td> </tr> </tbody> </table> -</div> -<div class="section" id="id33"> -<h3><a class="toc-backref" href="#id172">Examples:</a></h3> +</blockquote> +<p>Examples:</p> <p>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 @@ -2213,9 +2254,7 @@ add some new races with 'watch'. If you simply want to stop it completely use <pre class="literal-block"> autobutcher unwatch ALPACA CAT </pre> -</div> -<div class="section" id="note"> -<h3><a class="toc-backref" href="#id173">Note:</a></h3> +<p><strong>Note:</strong></p> <p>Settings and watchlist are stored in the savegame, so that you can have different settings for each world. If you want to copy your watchlist to another savegame you can use the command list_export:</p> @@ -2227,9 +2266,8 @@ Load the savegame where you want to copy the settings to, run the batch file (fr autobutcher.bat </pre> </div> -</div> <div class="section" id="autolabor"> -<h2><a class="toc-backref" href="#id174">autolabor</a></h2> +<h3><a class="toc-backref" href="#id105">autolabor</a></h3> <p>Automatically manage dwarf labors.</p> <p>When enabled, autolabor periodically checks your dwarves and enables or disables labors. It tries to keep as many dwarves as possible busy but @@ -2242,6 +2280,425 @@ while it is enabled.</p> <p>For detailed usage information, see 'help autolabor'.</p> </div> </div> +<div class="section" id="other"> +<h2><a class="toc-backref" href="#id106">Other</a></h2> +<div class="section" id="catsplosion"> +<h3><a class="toc-backref" href="#id107">catsplosion</a></h3> +<p>Makes cats just <em>multiply</em>. It is not a good idea to run this more than once or +twice.</p> +</div> +<div class="section" id="dfusion"> +<h3><a class="toc-backref" href="#id108">dfusion</a></h3> +<p>This is the DFusion lua plugin system by warmist/darius, running as a DFHack plugin.</p> +<p>See the bay12 thread for details: <a class="reference external" href="http://www.bay12forums.com/smf/index.php?topic=69682.15">http://www.bay12forums.com/smf/index.php?topic=69682.15</a></p> +<p>Confirmed working DFusion plugins:</p> +<table class="docutils field-list" frame="void" rules="none"> +<col class="field-name" /> +<col class="field-body" /> +<tbody valign="top"> +<tr class="field"><th class="field-name">simple_embark:</th><td class="field-body">allows changing the number of dwarves available on embark.</td> +</tr> +</tbody> +</table> +<div class="note"> +<p class="first admonition-title">Note</p> +<ul class="last simple"> +<li>Some of the DFusion plugins aren't completely ported yet. This can lead to crashes.</li> +<li>This is currently working only on Windows.</li> +<li>The game will be suspended while you're using dfusion. Don't panic when it doen't respond.</li> +</ul> +</div> +</div> +</div> +</div> +<div class="section" id="scripts"> +<h1><a class="toc-backref" href="#id109">Scripts</a></h1> +<p>Lua or ruby scripts placed in the hack/scripts/ directory are considered for +execution as if they were native DFHack commands. They are listed at the end +of the 'ls' command output.</p> +<p>Note: scripts in subdirectories of hack/scripts/ can still be called, but will +only be listed by ls if called as 'ls -a'. This is intended as a way to hide +scripts that are obscure, developer-oriented, or should be used as keybindings.</p> +<p>Some notable scripts:</p> +<div class="section" id="fix"> +<h2><a class="toc-backref" href="#id110">fix/*</a></h2> +<p>Scripts in this subdirectory fix various bugs and issues, some of them obscure.</p> +<ul> +<li><p class="first">fix/dead-units</p> +<p>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.</p> +</li> +<li><p class="first">fix/population-cap</p> +<p>Run this after every migrant wave to ensure your population cap is not exceeded. +The issue with the cap is that it is compared to the population number reported +by the last caravan, so once it drops below the cap, migrants continue to come +until that number is updated again.</p> +</li> +<li><p class="first">fix/stable-temp</p> +<p>Instantly sets the temperature of all free-lying items to be in equilibrium with +the environment and stops temperature updates. In order to maintain this efficient +state however, use <tt class="docutils literal">tweak <span class="pre">stable-temp</span></tt> and <tt class="docutils literal">tweak <span class="pre">fast-heat</span></tt>.</p> +</li> +<li><p class="first">fix/item-occupancy</p> +<p>Diagnoses and fixes issues with nonexistant 'items occupying site', usually +caused by autodump bugs or other hacking mishaps.</p> +</li> +</ul> +</div> +<div class="section" id="gui"> +<h2><a class="toc-backref" href="#id111">gui/*</a></h2> +<p>Scripts that implement dialogs inserted into the main game window are put in this +directory.</p> +</div> +<div class="section" id="quicksave"> +<h2><a class="toc-backref" href="#id112">quicksave</a></h2> +<p>If called in dwarf mode, makes DF immediately auto-save the game by setting a flag +normally used in seasonal auto-save.</p> +</div> +<div class="section" id="setfps"> +<h2><a class="toc-backref" href="#id113">setfps</a></h2> +<p>Run <tt class="docutils literal">setfps <number></tt> to set the FPS cap at runtime, in case you want to watch +combat in slow motion or something :)</p> +</div> +<div class="section" id="siren"> +<h2><a class="toc-backref" href="#id114">siren</a></h2> +<p>Wakes up sleeping units, cancels breaks and stops parties either everywhere, +or in the burrows given as arguments. In return, adds bad thoughts about +noise, tiredness and lack of protection. Also, the units with interrupted +breaks will go on break again a lot sooner. The script is intended for +emergencies, e.g. when a siege appears, and all your military is partying.</p> +</div> +<div class="section" id="growcrops"> +<h2><a class="toc-backref" href="#id115">growcrops</a></h2> +<p>Instantly grow seeds inside farming plots.</p> +<p>With no argument, this command list the various seed types currently in +use in your farming plots. +With a seed type, the script will grow 100 of these seeds, ready to be +harvested. You can change the number with a 2nd argument.</p> +<p>For exemple, to grow 40 plump helmet spawn:</p> +<pre class="literal-block"> +growcrops plump 40 +</pre> +</div> +<div class="section" id="removebadthoughts"> +<h2><a class="toc-backref" href="#id116">removebadthoughts</a></h2> +<p>This script remove negative thoughts from your dwarves. Very useful against +tantrum spirals.</p> +<p>With a selected unit in 'v' mode, will clear this unit's mind, otherwise +clear all your fort's units minds.</p> +<p>Individual dwarf happiness may not increase right after this command is run, +but in the short term your dwarves will get much more joyful. +The thoughts are set to be very old, and the game will remove them soon when +you unpause.</p> +<p>With the optional <tt class="docutils literal"><span class="pre">-v</span></tt> parameter, the script will dump the negative thoughts +it removed.</p> +</div> +<div class="section" id="slayrace"> +<h2><a class="toc-backref" href="#id117">slayrace</a></h2> +<p>Kills any unit of a given race.</p> +<p>With no argument, lists the available races.</p> +<p>With the special argument 'him', targets only the selected creature.</p> +<p>Any non-dead non-caged unit of the specified race gets its <tt class="docutils literal">blood_count</tt> +set to 0, which means immediate death at the next game tick. For creatures +such as vampires, also set animal.vanish_countdown to 2.</p> +<p>An alternate mode is selected by adding a 2nd argument to the command, +<tt class="docutils literal">magma</tt>. In this case, a column of 7/7 magma is generated on top of the +targets until they die (Warning: do not call on magma-safe creatures. Also, +using this mode for birds is not recommanded.)</p> +<p>Will target any unit on a revealed tile of the map, including ambushers.</p> +<p>Ex:</p> +<pre class="literal-block"> +slayrace gob +</pre> +<p>To kill a single creature, select the unit with the 'v' cursor and:</p> +<pre class="literal-block"> +slayrace him +</pre> +<p>To purify all elves on the map with fire (may have side-effects):</p> +<pre class="literal-block"> +slayrace elve magma +</pre> +</div> +<div class="section" id="magmasource"> +<h2><a class="toc-backref" href="#id118">magmasource</a></h2> +<p>Create an infinite magma source on a tile.</p> +<p>This script registers a map tile as a magma source, and every 12 game ticks +that tile receives 1 new unit of flowing magma.</p> +<p>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:</p> +<pre class="literal-block"> +magmasource here +</pre> +<p>To add more than 1 unit everytime, call the command again.</p> +<p>To delete one source, place the cursor over its tile and use <tt class="docutils literal"><span class="pre">delete-here</span></tt>. +To remove all placed sources, call <tt class="docutils literal">magmasource stop</tt>.</p> +<p>With no argument, this command shows an help message and list existing sources.</p> +</div> +<div class="section" id="digfort"> +<h2><a class="toc-backref" href="#id119">digfort</a></h2> +<p>A script to designate an area for digging according to a plan in csv format.</p> +<p>This script, inspired from quickfort, can designate an area for digging. +Your plan should be stored in a .csv file like this:</p> +<pre class="literal-block"> +# this is a comment +d;d;u;d;d;skip this tile;d +d;d;d;i +</pre> +<p>Available tile shapes are named after the 'dig' menu shortcuts: +<tt class="docutils literal">d</tt> for dig, <tt class="docutils literal">u</tt> for upstairs, <tt class="docutils literal">d</tt> downstairs, <tt class="docutils literal">i</tt> updown, +<tt class="docutils literal">h</tt> channel, <tt class="docutils literal">r</tt> upward ramp, <tt class="docutils literal">x</tt> remove designation. +Unrecognized characters are ignored (eg the 'skip this tile' in the sample).</p> +<p>Empty lines and data after a <tt class="docutils literal">#</tt> are ignored as comments. +To skip a row in your design, use a single <tt class="docutils literal">;</tt>.</p> +<p>The script takes the plan filename, starting from the root df folder.</p> +</div> +<div class="section" id="superdwarf"> +<h2><a class="toc-backref" href="#id120">superdwarf</a></h2> +<p>Similar to fastdwarf, per-creature.</p> +<p>To make any creature superfast, target it ingame using 'v' and:</p> +<pre class="literal-block"> +superdwarf add +</pre> +<p>Other options available: <tt class="docutils literal">del</tt>, <tt class="docutils literal">clear</tt>, <tt class="docutils literal">list</tt>.</p> +<p>This plugin also shortens the 'sleeping' and 'on break' periods of targets.</p> +</div> +<div class="section" id="drainaquifer"> +<h2><a class="toc-backref" href="#id121">drainaquifer</a></h2> +<p>Remove all 'aquifer' tag from the map blocks. Irreversible.</p> +</div> +<div class="section" id="deathcause"> +<h2><a class="toc-backref" href="#id122">deathcause</a></h2> +<p>Focus a body part ingame, and this script will display the cause of death of +the creature.</p> +</div> +</div> +<div class="section" id="in-game-interface-tools"> +<h1><a class="toc-backref" href="#id123">In-game interface tools</a></h1> +<p>These tools work by displaying dialogs or overlays in the game window, and +are mostly implemented by lua scripts.</p> +<div class="section" id="dwarf-manipulator"> +<h2><a class="toc-backref" href="#id124">Dwarf Manipulator</a></h2> +<p>Implemented by the manipulator plugin. To activate, open the unit screen and +press 'l'.</p> +<p>This tool implements a Dwarf Therapist-like interface within the game UI. The +far left column displays the unit's Happiness (color-coded based on its +value), and the right half of the screen displays each dwarf's labor settings +and skill levels (0-9 for Dabbling thru Professional, A-E for Great thru Grand +Master, and U-Z for Legendary thru Legendary+5). Cells with red backgrounds +denote skills not controlled by labors.</p> +<p>Use the arrow keys or number pad to move the cursor around, holding Shift to +move 10 tiles at a time.</p> +<p>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.</p> +<p>Press Enter to toggle the selected labor for the selected unit, or Shift+Enter +to toggle all labors within the selected category.</p> +<p>Press the <tt class="docutils literal">+-</tt> keys to sort the unit list according to the currently selected +skill/labor, and press the <tt class="docutils literal">*/</tt> keys to sort the unit list by Name, Profession, +Happiness, or Arrival order (using Tab to select which sort method to use here).</p> +<p>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.</p> +<p>The following mouse shortcuts are also available:</p> +<ul class="simple"> +<li>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 or +profession) and right-click to sort it in the opposite direction.</li> +<li>Left-click on a labor cell to toggle that labor. Right-click to move the +cursor onto that cell instead of toggling it.</li> +<li>Left-click on a unit's name or profession to view its properties.</li> +<li>Right-click on a unit's name or profession to zoom to it.</li> +</ul> +<p>Pressing ESC normally returns to the unit screen, but Shift-ESC would exit +directly to the main dwarf mode screen.</p> +</div> +<div class="section" id="id1"> +<h2><a class="toc-backref" href="#id125">Liquids</a></h2> +<p>Implemented by the gui/liquids script. To use, bind to a key and activate in the 'k' mode.</p> +<p>While active, use the suggested keys to switch the usual liquids parameters, and Enter +to select the target area and apply changes.</p> +</div> +<div class="section" id="mechanisms"> +<h2><a class="toc-backref" href="#id126">Mechanisms</a></h2> +<p>Implemented by the gui/mechanims script. To use, bind to a key and activate in the 'q' mode.</p> +<p>Lists mechanisms connected to the building, and their links. Navigating the list centers +the view on the relevant linked buildings.</p> +<p>To exit, press ESC or Enter; ESC recenters on the original building, while Enter leaves +focus on the current one. Shift-Enter has an effect equivalent to pressing Enter, and then +re-entering the mechanisms ui.</p> +</div> +<div class="section" id="id2"> +<h2><a class="toc-backref" href="#id127">Rename</a></h2> +<p>Backed by the rename plugin, the gui/rename script allows entering the desired name +via a simple dialog in the game ui.</p> +<ul> +<li><p class="first"><tt class="docutils literal">gui/rename [building]</tt> in 'q' mode changes the name of a building.</p> +<p>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.</p> +</li> +<li><p class="first"><tt class="docutils literal">gui/rename [unit]</tt> with a unit selected changes the nickname.</p> +</li> +<li><p class="first"><tt class="docutils literal">gui/rename <span class="pre">unit-profession</span></tt> changes the selected unit's custom profession name.</p> +</li> +</ul> +<p>The <tt class="docutils literal">building</tt> or <tt class="docutils literal">unit</tt> options are automatically assumed when in relevant ui state.</p> +</div> +<div class="section" id="room-list"> +<h2><a class="toc-backref" href="#id128">Room List</a></h2> +<p>Implemented by the gui/room-list script. To use, bind to a key and activate in the 'q' mode, +either immediately or after opening the assign owner page.</p> +<p>The script lists other rooms owned by the same owner, or by the unit selected in the assign +list, and allows unassigning them.</p> +</div> +</div> +<div class="section" id="behavior-mods"> +<h1><a class="toc-backref" href="#id129">Behavior Mods</a></h1> +<p>These plugins, when activated via configuration UI or by detecting certain +structures in RAWs, modify the game engine behavior concerning the target +objects to add features not otherwise present.</p> +<div class="section" id="siege-engine"> +<h2><a class="toc-backref" href="#id130">Siege Engine</a></h2> +<p>The siege-engine plugin enables siege engines to be linked to stockpiles, and +aimed at an arbitrary rectangular area across Z levels, instead of the original +four directions. Also, catapults can be ordered to load arbitrary objects, not +just stones.</p> +<p>The configuration front-end to the plugin is implemented by the gui/siege-engine +script. Bind it to a key and activate after selecting a siege engine in 'q' mode.</p> +<p>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.</p> +<p>Pressing 'r' changes into the target selection mode, which works by highlighting two points +with Enter like all designations. When a target area is set, the engine projectiles are +aimed at that area, or units within it (this doesn't actually change the original aiming +code, instead the projectile trajectory parameters are rewritten as soon as it appears).</p> +<p>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.</p> +<p>Pressing 't' switches to a mode for selecting a stockpile to take ammo from.</p> +<p>Exiting from the siege engine script via ESC reverts the view to the state prior to starting +the script. Shift-ESC retains the current viewport, and also exits from the 'q' mode to main +menu.</p> +<div class="admonition-disclaimer admonition"> +<p class="first admonition-title">DISCLAIMER</p> +<p class="last">Siege engines are a very interesting feature, but sadly almost useless in the current state +because they haven't been updated since 2D and can only aim in four directions. This is an +attempt to bring them more up to date until Toady has time to work on it. Actual improvements, +e.g. like making siegers bring their own, are something only Toady can do.</p> +</div> +</div> +<div class="section" id="power-meter"> +<h2><a class="toc-backref" href="#id131">Power Meter</a></h2> +<p>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.</p> +<p>The configuration front-end is implemented by the gui/power-meter script. Bind it to a +key and activate after selecting Pressure Plate in the build menu.</p> +<p>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.</p> +</div> +<div class="section" id="steam-engine"> +<h2><a class="toc-backref" href="#id132">Steam Engine</a></h2> +<p>The steam-engine plugin detects custom workshops with STEAM_ENGINE in +their token, and turns them into real steam engines.</p> +<div class="section" id="rationale"> +<h3><a class="toc-backref" href="#id133">Rationale</a></h3> +<p>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.</p> +<p>Steam engines are an alternative to water reactors that actually makes +sense, and hopefully doesn't lag. Also, unlike e.g. animal treadmills, +it can be done just by combining existing features of the game engine +in a new way with some glue code and a bit of custom logic.</p> +</div> +<div class="section" id="construction"> +<h3><a class="toc-backref" href="#id134">Construction</a></h3> +<p>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.</p> +<div class="admonition-issue admonition"> +<p class="first admonition-title">ISSUE</p> +<p class="last">Since this building is a machine, and machine collapse +code cannot be hooked, it would collapse over true open space. +As a loophole, down stair provides support to machines, while +being passable, so use them.</p> +</div> +<p>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.</p> +<div class="admonition-issue admonition"> +<p class="first admonition-title">ISSUE</p> +<p class="last">Like with collapse above, part of the code involved in +machine connection cannot be hooked. As a result, the workshop +can only immediately connect to machine components built AFTER it. +This also means that engines cannot be chained without intermediate +short axles that can be built later than both of the engines.</p> +</div> +</div> +<div class="section" id="operation"> +<h3><a class="toc-backref" href="#id135">Operation</a></h3> +<p>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.</p> +<div class="note"> +<p class="first admonition-title">Note</p> +<p class="last">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.</p> +</div> +<p>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.</p> +<p>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.</p> +<p>Masterpiece mechanism and chain will decrease the mechanical +power drawn by the engine itself from 10 to 5. Masterpiece +barrel decreases waste rate by 4%. Masterpiece piston and pipe +decrease it by further 4%, and also decrease the whole steam +use rate by 10%.</p> +</div> +<div class="section" id="explosions"> +<h3><a class="toc-backref" href="#id136">Explosions</a></h3> +<p>The engine must be constructed using barrel, pipe and piston +from fire-safe, or in the magma version magma-safe metals.</p> +<p>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.</p> +</div> +<div class="section" id="save-files"> +<h3><a class="toc-backref" href="#id137">Save files</a></h3> +<p>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.</p> +</div> +</div> +<div class="section" id="add-spatter"> +<h2><a class="toc-backref" href="#id138">Add Spatter</a></h2> +<p>This plugin makes reactions with names starting with <tt class="docutils literal">SPATTER_ADD_</tt> +produce contaminants on the items instead of improvements. The produced +contaminants are immune to being washed away by water or destroyed by +the <tt class="docutils literal">clean items</tt> command.</p> +<p>The plugin is intended to give some use to all those poisons that can +be bought from caravans. :)</p> +<p>To be really useful this needs patches from bug 808, <tt class="docutils literal">tweak <span class="pre">fix-dimensions</span></tt> +and <tt class="docutils literal">tweak <span class="pre">advmode-contained</span></tt>.</p> +</div> +</div> </div> </body> </html> diff --git a/depends/clsocket b/depends/clsocket -Subproject d0b2d0750dc2d529a152eba4f3f519f69ff7eab +Subproject 178a4916da838e46e46e769e566e47fff6eff8f diff --git a/depends/protobuf/CMakeLists.txt b/depends/protobuf/CMakeLists.txt index 24c4b275..5034f00f 100644 --- a/depends/protobuf/CMakeLists.txt +++ b/depends/protobuf/CMakeLists.txt @@ -7,10 +7,10 @@ IF(CMAKE_COMPILER_IS_GNUCC) STRING(REGEX MATCHALL "[0-9]+" GCC_VERSION_COMPONENTS ${GCC_VERSION})
LIST(GET GCC_VERSION_COMPONENTS 0 GCC_MAJOR)
LIST(GET GCC_VERSION_COMPONENTS 1 GCC_MINOR)
- IF(GCC_MAJOR LESS 4 OR (GCC_MAJOR EQUAL 4 AND GCC_MINOR LESS 2))
+ #IF(GCC_MAJOR LESS 4 OR (GCC_MAJOR EQUAL 4 AND GCC_MINOR LESS 2))
#GCC is too old
- SET(STL_HASH_OLD_GCC 1)
- ENDIF()
+ # SET(STL_HASH_OLD_GCC 1)
+ #ENDIF()
#SET(CMAKE_CXX_FLAGS "-std=c++0x")
SET(HAVE_HASH_MAP 0)
diff --git a/dfhack.init-example b/dfhack.init-example index 4af4246f..2e656a60 100644 --- a/dfhack.init-example +++ b/dfhack.init-example @@ -16,6 +16,10 @@ keybinding add Ctrl-K autodump-destroy-item # quicksave, only in main dwarfmode screen and menu page keybinding add Ctrl-Alt-S@dwarfmode/Default quicksave +# gui/rename script +keybinding add Ctrl-Shift-N gui/rename +keybinding add Alt-Shift-P "gui/rename unit-profession" + ############################## # Generic adv mode bindings # ############################## @@ -41,4 +45,64 @@ keybinding add Shift-R "job-material RHYOLITE" keybinding add Shift-I "job-material CINNABAR" keybinding add Shift-B "job-material COBALTITE" keybinding add Shift-O "job-material OBSIDIAN" +keybinding add Shift-T "job-material ORTHOCLASE" keybinding add Shift-G "job-material GLASS_GREEN" + +# sort units and items +keybinding add Alt-Shift-N "sort-units name" "sort-items description" +keybinding add Alt-Shift-R "sort-units arrival" +keybinding add Alt-Shift-T "sort-units profession" "sort-items type material" +keybinding add Alt-Shift-Q "sort-units squad_position" "sort-items quality" + +# browse linked mechanisms +keybinding add Ctrl-M@dwarfmode/QueryBuilding/Some gui/mechanisms + +# browse rooms of same owner +keybinding add Alt-R@dwarfmode/QueryBuilding/Some gui/room-list + +# interface for the liquids plugin +keybinding add Alt-L@dwarfmode/LookAround gui/liquids + +# machine power sensitive pressure plate construction +keybinding add Ctrl-Shift-M@dwarfmode/Build/Position/Trap gui/power-meter + +# siege engine control +keybinding add Alt-A@dwarfmode/QueryBuilding/Some/SiegeEngine gui/siege-engine + +############################ +# UI and game logic tweaks # +############################ + +# stabilize the cursor of dwarfmode when switching menus +tweak stable-cursor + +# stop military from considering training as 'patrol duty' +tweak patrol-duty + +# display creature weight in build plate menu as ??K, instead of (???df: Max +tweak readable-build-plate + +# improve FPS by squashing endless item temperature update loops +tweak stable-temp + +# speed up items reaching temp equilibrium with environment by +# capping the rate to no less than 1 degree change per 500 frames +# Note: will also cause stuff to melt faster in magma etc +tweak fast-heat 500 + +# stop stacked liquid/bar/thread/cloth items from lasting forever +# if used in reactions that use only a fraction of the dimension. +tweak fix-dimensions + +# make reactions requiring containers usable in advmode - the issue is +# that the screen asks for those reagents to be selected directly +tweak advmode-contained + +# support Shift-Enter in Trade and Move Goods to Depot screens for faster +# selection; it selects the current item or stack and scrolls down one line +tweak fast-trade + +# stop the right list in military->positions from resetting to top all the time +tweak military-stable-assign +# in same list, color units already assigned to squads in brown & green +tweak military-color-assigned diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt index bbf22611..536f4d34 100644 --- a/library/CMakeLists.txt +++ b/library/CMakeLists.txt @@ -27,6 +27,7 @@ include/Core.h include/ColorText.h include/DataDefs.h include/DataIdentity.h +include/VTableInterpose.h include/LuaWrapper.h include/LuaTools.h include/Error.h @@ -53,6 +54,7 @@ SET(MAIN_SOURCES Core.cpp ColorText.cpp DataDefs.cpp +VTableInterpose.cpp LuaWrapper.cpp LuaTypes.cpp LuaTools.cpp @@ -117,6 +119,7 @@ include/modules/Maps.h include/modules/MapCache.h include/modules/Materials.h include/modules/Notes.h +include/modules/Screen.h include/modules/Translation.h include/modules/Vegetation.h include/modules/Vermin.h @@ -137,6 +140,7 @@ modules/kitchen.cpp modules/Maps.cpp modules/Materials.cpp modules/Notes.cpp +modules/Screen.cpp modules/Translation.cpp modules/Vegetation.cpp modules/Vermin.cpp @@ -282,6 +286,10 @@ SET_TARGET_PROPERTIES(dfhack PROPERTIES LINK_INTERFACE_LIBRARIES "") TARGET_LINK_LIBRARIES(dfhack-client protobuf-lite clsocket) TARGET_LINK_LIBRARIES(dfhack-run dfhack-client) +if(APPLE) + add_custom_command(TARGET dfhack-run COMMAND ${dfhack_SOURCE_DIR}/package/darwin/fix-libs.sh WORKING_DIRECTORY ../ COMMENT "Fixing library dependencies...") +endif() + IF(UNIX) if (APPLE) install(PROGRAMS ${dfhack_SOURCE_DIR}/package/darwin/dfhack diff --git a/library/Console-darwin.cpp b/library/Console-darwin.cpp index c547f841..86cd657a 100644 --- a/library/Console-darwin.cpp +++ b/library/Console-darwin.cpp @@ -275,7 +275,7 @@ namespace DFHack /// Reset color to default void reset_color(void) { - color(Console::COLOR_RESET); + color(COLOR_RESET); if(!rawmode) fflush(dfout_C); } diff --git a/library/Console-linux.cpp b/library/Console-linux.cpp index 882d9527..f32fa1c2 100644 --- a/library/Console-linux.cpp +++ b/library/Console-linux.cpp @@ -277,7 +277,7 @@ namespace DFHack /// Reset color to default void reset_color(void) { - color(Console::COLOR_RESET); + color(COLOR_RESET); if(!rawmode) fflush(dfout_C); } diff --git a/library/Console-windows.cpp b/library/Console-windows.cpp index d4d47303..f0cdda38 100644 --- a/library/Console-windows.cpp +++ b/library/Console-windows.cpp @@ -179,7 +179,7 @@ namespace DFHack void color(int index) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - SetConsoleTextAttribute(hConsole, index == color_ostream::COLOR_RESET ? default_attributes : index); + SetConsoleTextAttribute(hConsole, index == COLOR_RESET ? default_attributes : index); } void reset_color( void ) diff --git a/library/Core.cpp b/library/Core.cpp index 826576b7..8a8d39e0 100644 --- a/library/Core.cpp +++ b/library/Core.cpp @@ -126,8 +126,34 @@ struct Core::Private void Core::cheap_tokenise(string const& input, vector<string> &output) { string *cur = NULL; + size_t i = 0; - for (size_t i = 0; i < input.size(); i++) { + // Check the first non-space character + while (i < input.size() && isspace(input[i])) i++; + + // Special verbatim argument mode? + if (i < input.size() && input[i] == ':') + { + // Read the command + std::string cmd; + i++; + while (i < input.size() && !isspace(input[i])) + cmd.push_back(input[i++]); + if (!cmd.empty()) + output.push_back(cmd); + + // Find the argument + while (i < input.size() && isspace(input[i])) i++; + + if (i < input.size()) + output.push_back(input.substr(i)); + + return; + } + + // Otherwise, parse in the regular quoted mode + for (; i < input.size(); i++) + { unsigned char c = input[i]; if (isspace(c)) { cur = NULL; @@ -219,28 +245,30 @@ static std::string getScriptHelp(std::string path, std::string helpprefix) return "No help available."; } -static std::map<string,string> listScripts(PluginManager *plug_mgr, std::string path) +static void listScripts(PluginManager *plug_mgr, std::map<string,string> &pset, std::string path, bool all, std::string prefix = "") { std::vector<string> files; getdir(path, files); - std::map<string,string> pset; for (size_t i = 0; i < files.size(); i++) { if (hasEnding(files[i], ".lua")) { std::string help = getScriptHelp(path + files[i], "-- "); - pset[files[i].substr(0, files[i].size()-4)] = help; + pset[prefix + files[i].substr(0, files[i].size()-4)] = help; } else if (plug_mgr->eval_ruby && hasEnding(files[i], ".rb")) { std::string help = getScriptHelp(path + files[i], "# "); - pset[files[i].substr(0, files[i].size()-3)] = help; + pset[prefix + files[i].substr(0, files[i].size()-3)] = help; + } + else if (all && !files[i].empty() && files[i][0] != '.') + { + listScripts(plug_mgr, pset, path+files[i]+"/", all, prefix+files[i]+"/"); } } - return pset; } static bool fileExists(std::string path) @@ -335,7 +363,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve con.print("Basic commands:\n" " help|?|man - This text.\n" " help COMMAND - Usage help for the given command.\n" - " ls|dir [PLUGIN] - List available commands. Optionally for single plugin.\n" + " ls|dir [-a] [PLUGIN] - List available commands. Optionally for single plugin.\n" " cls - Clear the console.\n" " fpause - Force DF to pause.\n" " die - Force DF to close immediately\n" @@ -358,7 +386,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve continue; if (pcmd.isHotkeyCommand()) - con.color(Console::COLOR_CYAN); + con.color(COLOR_CYAN); con.print("%s: %s\n",pcmd.name.c_str(), pcmd.description.c_str()); con.reset_color(); if (!pcmd.usage.empty()) @@ -469,6 +497,12 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve } else if(first == "ls" || first == "dir") { + bool all = false; + if (parts.size() && parts[0] == "-a") + { + all = true; + vector_erase_at(parts, 0); + } if(parts.size()) { string & plugname = parts[0]; @@ -481,7 +515,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve { const PluginCommand & pcmd = (plug->operator[](j)); if (pcmd.isHotkeyCommand()) - con.color(Console::COLOR_CYAN); + con.color(COLOR_CYAN); con.print(" %-22s - %s\n",pcmd.name.c_str(), pcmd.description.c_str()); con.reset_color(); } @@ -491,7 +525,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve con.print( "builtin:\n" " help|?|man - This text or help specific to a plugin.\n" - " ls [PLUGIN] - List available commands. Optionally for single plugin.\n" + " ls [-a] [PLUGIN] - List available commands. Optionally for single plugin.\n" " cls - Clear the console.\n" " fpause - Force DF to pause.\n" " die - Force DF to close immediately\n" @@ -519,11 +553,12 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve for(auto iter = out.begin();iter != out.end();iter++) { if ((*iter).recolor) - con.color(Console::COLOR_CYAN); + con.color(COLOR_CYAN); con.print(" %-22s- %s\n",(*iter).name.c_str(), (*iter).description.c_str()); con.reset_color(); } - auto scripts = listScripts(plug_mgr, getHackPath() + "scripts/"); + std::map<string, string> scripts; + listScripts(plug_mgr, scripts, getHackPath() + "scripts/", all); if (!scripts.empty()) { con.print("\nscripts:\n"); @@ -1027,35 +1062,41 @@ int Core::TileUpdate() return true; } -// should always be from simulation thread! -int Core::Update() +int Core::ClaimSuspend(bool force_base) { - if(errorstate) - return -1; + auto tid = this_thread::get_id(); + lock_guard<mutex> lock(d->AccessMutex); - // Pretend this thread has suspended the core in the usual way + if (force_base || d->df_suspend_depth <= 0) { - lock_guard<mutex> lock(d->AccessMutex); - assert(d->df_suspend_depth == 0); - d->df_suspend_thread = this_thread::get_id(); - d->df_suspend_depth = 1000; - } - // Initialize the core - bool first_update = false; - - if(!started) + d->df_suspend_thread = tid; + d->df_suspend_depth = 1000000; + return 1000000; + } + else { - first_update = true; - Init(); - if(errorstate) - return -1; - Lua::Core::Reset(con, "core init"); + assert(d->df_suspend_thread == tid); + return ++d->df_suspend_depth; } +} - color_ostream_proxy out(con); +void Core::DisclaimSuspend(int level) +{ + auto tid = this_thread::get_id(); + lock_guard<mutex> lock(d->AccessMutex); + assert(d->df_suspend_depth == level && d->df_suspend_thread == tid); + + if (level == 1000000) + d->df_suspend_depth = 0; + else + --d->df_suspend_depth; +} + +void Core::doUpdate(color_ostream &out, bool first_update) +{ Lua::Core::Reset(out, "DF code execution"); if (first_update) @@ -1129,15 +1170,36 @@ int Core::Update() // Execute per-frame handlers onUpdate(out); - // Release the fake suspend lock + out << std::flush; +} + +// should always be from simulation thread! +int Core::Update() +{ + if(errorstate) + return -1; + + color_ostream_proxy out(con); + + // Pretend this thread has suspended the core in the usual way, + // and run various processing hooks. { - lock_guard<mutex> lock(d->AccessMutex); + CoreSuspendClaimer suspend(true); - assert(d->df_suspend_depth == 1000); - d->df_suspend_depth = 0; - } + // Initialize the core + bool first_update = false; - out << std::flush; + if(!started) + { + first_update = true; + Init(); + if(errorstate) + return -1; + Lua::Core::Reset(con, "core init"); + } + + doUpdate(out, first_update); + } // wake waiting tools // do not allow more tools to join in while we process stuff here @@ -1158,7 +1220,7 @@ int Core::Update() // destroy condition delete nc; // check lua stack depth - Lua::Core::Reset(con, "suspend"); + Lua::Core::Reset(out, "suspend"); } return 0; @@ -1198,6 +1260,7 @@ int Core::Shutdown ( void ) if(errorstate) return true; errorstate = 1; + CoreSuspendClaimer suspend; if(plug_mgr) { delete plug_mgr; @@ -1232,7 +1295,7 @@ bool Core::ncurses_wgetch(int in, int & out) // FIXME: copypasta, push into a method! if(df::global::ui && df::global::gview) { - df::viewscreen * ws = Gui::GetCurrentScreen(); + df::viewscreen * ws = Gui::getCurViewscreen(); if (strict_virtual_cast<df::viewscreen_dwarfmodest>(ws) && df::global::ui->main.mode != ui_sidebar_mode::Hotkeys && df::global::ui->main.hotkeys[idx].cmd == df::ui_hotkey::T_cmd::None) @@ -1548,6 +1611,56 @@ void ClassNameCheck::getKnownClassNames(std::vector<std::string> &names) names.push_back(*it); } +bool Process::patchMemory(void *target, const void* src, size_t count) +{ + uint8_t *sptr = (uint8_t*)target; + uint8_t *eptr = sptr + count; + + // Find the valid memory ranges + std::vector<t_memrange> ranges; + getMemRanges(ranges); + + unsigned start = 0; + while (start < ranges.size() && ranges[start].end <= sptr) + start++; + if (start >= ranges.size() || ranges[start].start > sptr) + return false; + + unsigned end = start+1; + while (end < ranges.size() && ranges[end].start < eptr) + { + if (ranges[end].start != ranges[end-1].end) + return false; + end++; + } + if (ranges[end-1].end < eptr) + return false; + + // Verify current permissions + for (unsigned i = start; i < end; i++) + if (!ranges[i].valid || !(ranges[i].read || ranges[i].execute) || ranges[i].shared) + return false; + + // Apply writable permissions & update + bool ok = true; + + for (unsigned i = start; i < end && ok; i++) + { + t_memrange perms = ranges[i]; + perms.write = perms.read = true; + if (!setPermisions(perms, perms)) + ok = false; + } + + if (ok) + memmove(target, src, count); + + for (unsigned i = start; i < end && ok; i++) + setPermisions(ranges[i], ranges[i]); + + return ok; +} + /******************************************************************************* M O D U L E S *******************************************************************************/ diff --git a/library/DataDefs.cpp b/library/DataDefs.cpp index 7f0bacc9..fa2aacf7 100644 --- a/library/DataDefs.cpp +++ b/library/DataDefs.cpp @@ -35,6 +35,7 @@ distribution. // must be last due to MS stupidity #include "DataDefs.h" #include "DataIdentity.h" +#include "VTableInterpose.h" #include "MiscUtils.h" @@ -214,6 +215,15 @@ virtual_identity::virtual_identity(size_t size, TAllocateFn alloc, { } +virtual_identity::~virtual_identity() +{ + // Remove interpose entries, so that they don't try accessing this object later + for (auto it = interpose_list.begin(); it != interpose_list.end(); ++it) + if (it->second) + it->second->on_host_delete(this); + interpose_list.clear(); +} + /* Vtable name to identity lookup. */ static std::map<std::string, virtual_identity*> name_lookup; @@ -364,7 +374,7 @@ void DFHack::bitfieldToString(std::vector<std::string> *pvec, const void *p, unsigned size, const bitfield_item_info *items) { for (unsigned i = 0; i < size; i++) { - int value = getBitfieldField(p, i, std::min(1,items[i].size)); + int value = getBitfieldField(p, i, std::max(1,items[i].size)); if (value) { std::string name = format_key(items[i].name, i); diff --git a/library/LuaApi.cpp b/library/LuaApi.cpp index b0a085ec..b2d41dc1 100644 --- a/library/LuaApi.cpp +++ b/library/LuaApi.cpp @@ -39,6 +39,7 @@ distribution. #include "modules/World.h" #include "modules/Gui.h" +#include "modules/Screen.h" #include "modules/Job.h" #include "modules/Translation.h" #include "modules/Units.h" @@ -76,6 +77,10 @@ distribution. #include "df/job_material_category.h" #include "df/burrow.h" #include "df/building_civzonest.h" +#include "df/region_map_entry.h" +#include "df/flow_info.h" +#include "df/unit_misc_trait.h" +#include "df/proj_itemst.h" #include <lua.h> #include <lauxlib.h> @@ -84,6 +89,8 @@ distribution. using namespace DFHack; using namespace DFHack::LuaWrapper; +using Screen::Pen; + void dfhack_printerr(lua_State *S, const std::string &str); void Lua::Push(lua_State *state, const Units::NoblePosition &pos) @@ -179,6 +186,68 @@ static df::coord CheckCoordXYZ(lua_State *state, int base, bool vararg = false) return p; } +template<class T> +static bool get_int_field(lua_State *L, T *pf, int idx, const char *name, int defval) +{ + lua_getfield(L, idx, name); + bool nil = lua_isnil(L, -1); + if (nil) *pf = T(defval); + else if (lua_isnumber(L, -1)) *pf = T(lua_tointeger(L, -1)); + else luaL_error(L, "Field %s is not a number.", name); + lua_pop(L, 1); + return !nil; +} + +static bool get_char_field(lua_State *L, char *pf, int idx, const char *name, char defval) +{ + lua_getfield(L, idx, name); + + if (lua_type(L, -1) == LUA_TSTRING) + { + *pf = lua_tostring(L, -1)[0]; + lua_pop(L, 1); + return true; + } + else + { + lua_pop(L, 1); + return get_int_field(L, pf, idx, name, defval); + } +} + +static void decode_pen(lua_State *L, Pen &pen, int idx) +{ + idx = lua_absindex(L, idx); + + get_char_field(L, &pen.ch, idx, "ch", 0); + + get_int_field(L, &pen.fg, idx, "fg", 7); + get_int_field(L, &pen.bg, idx, "bg", 0); + + lua_getfield(L, idx, "bold"); + if (lua_isnil(L, -1)) + { + pen.bold = (pen.fg & 8) != 0; + pen.fg &= 7; + } + else pen.bold = lua_toboolean(L, -1); + lua_pop(L, 1); + + get_int_field(L, &pen.tile, idx, "tile", 0); + + bool tcolor = get_int_field(L, &pen.tile_fg, idx, "tile_fg", 7); + tcolor = get_int_field(L, &pen.tile_bg, idx, "tile_bg", 0) || tcolor; + + if (tcolor) + pen.tile_mode = Pen::TileColor; + else + { + lua_getfield(L, idx, "tile_color"); + pen.tile_mode = (lua_toboolean(L, -1) ? Pen::CharColor : Pen::AsIs); + lua_pop(L, 1); + } +} + /************************************************** * Per-world persistent configuration storage API * **************************************************/ @@ -661,6 +730,7 @@ static std::string getOSType() } static std::string getDFVersion() { return Core::getInstance().vinfo->getVersion(); } +static uint32_t getTickCount() { return Core::getInstance().p->getTickCount(); } static std::string getDFPath() { return Core::getInstance().p->getPath(); } static std::string getHackPath() { return Core::getInstance().getHackPath(); } @@ -672,6 +742,7 @@ static const LuaWrapper::FunctionReg dfhack_module[] = { WRAP(getOSType), WRAP(getDFVersion), WRAP(getDFPath), + WRAP(getTickCount), WRAP(getHackPath), WRAP(isWorldLoaded), WRAP(isMapLoaded), @@ -684,12 +755,16 @@ static const LuaWrapper::FunctionReg dfhack_module[] = { static const LuaWrapper::FunctionReg dfhack_gui_module[] = { WRAPM(Gui, getCurViewscreen), WRAPM(Gui, getFocusString), + WRAPM(Gui, getCurFocus), WRAPM(Gui, getSelectedWorkshopJob), WRAPM(Gui, getSelectedJob), WRAPM(Gui, getSelectedUnit), WRAPM(Gui, getSelectedItem), + WRAPM(Gui, getSelectedBuilding), WRAPM(Gui, showAnnouncement), + WRAPM(Gui, showZoomAnnouncement), WRAPM(Gui, showPopupAnnouncement), + WRAPM(Gui, showAutoAnnouncement), { NULL, NULL } }; @@ -741,14 +816,24 @@ static const LuaWrapper::FunctionReg dfhack_units_module[] = { WRAPM(Units, getVisibleName), WRAPM(Units, getIdentity), WRAPM(Units, getNemesis), + WRAPM(Units, isCrazed), + WRAPM(Units, isOpposedToLife), + WRAPM(Units, hasExtravision), + WRAPM(Units, isBloodsucker), + WRAPM(Units, isMischievous), + WRAPM(Units, getMiscTrait), WRAPM(Units, isDead), WRAPM(Units, isAlive), WRAPM(Units, isSane), WRAPM(Units, isDwarf), WRAPM(Units, isCitizen), WRAPM(Units, getAge), + WRAPM(Units, getEffectiveSkill), + WRAPM(Units, computeMovementSpeed), WRAPM(Units, getProfessionName), WRAPM(Units, getCasteProfessionName), + WRAPM(Units, getProfessionColor), + WRAPM(Units, getCasteProfessionColor), { NULL, NULL } }; @@ -802,6 +887,18 @@ static bool items_moveToInventory return Items::moveToInventory(mc, item, unit, mode, body_part); } +static bool items_remove(df::item *item, bool no_uncat) +{ + MapExtras::MapCache mc; + return Items::remove(mc, item, no_uncat); +} + +static df::proj_itemst *items_makeProjectile(df::item *item) +{ + MapExtras::MapCache mc; + return Items::makeProjectile(mc, item); +} + static const LuaWrapper::FunctionReg dfhack_items_module[] = { WRAPM(Items, getGeneralRef), WRAPM(Items, getSpecificRef), @@ -813,6 +910,8 @@ static const LuaWrapper::FunctionReg dfhack_items_module[] = { WRAPN(moveToContainer, items_moveToContainer), WRAPN(moveToBuilding, items_moveToBuilding), WRAPN(moveToInventory, items_moveToInventory), + WRAPN(makeProjectile, items_makeProjectile), + WRAPN(remove, items_remove), { NULL, NULL } }; @@ -843,9 +942,17 @@ static const LuaWrapper::FunctionReg dfhack_maps_module[] = { WRAPM(Maps, getGlobalInitFeature), WRAPM(Maps, getLocalInitFeature), WRAPM(Maps, canWalkBetween), + WRAPM(Maps, spawnFlow), { NULL, NULL } }; +static int maps_isValidTilePos(lua_State *L) +{ + auto pos = CheckCoordXYZ(L, 1, true); + lua_pushboolean(L, Maps::isValidTilePos(pos)); + return 1; +} + static int maps_getTileBlock(lua_State *L) { auto pos = CheckCoordXYZ(L, 1, true); @@ -853,6 +960,13 @@ static int maps_getTileBlock(lua_State *L) return 1; } +static int maps_ensureTileBlock(lua_State *L) +{ + auto pos = CheckCoordXYZ(L, 1, true); + Lua::PushDFObject(L, Maps::ensureTileBlock(pos)); + return 1; +} + static int maps_getRegionBiome(lua_State *L) { auto pos = CheckCoordXY(L, 1, true); @@ -863,12 +977,13 @@ static int maps_getRegionBiome(lua_State *L) static int maps_getTileBiomeRgn(lua_State *L) { auto pos = CheckCoordXYZ(L, 1, true); - Lua::PushPosXY(L, Maps::getTileBiomeRgn(pos)); - return 1; + return Lua::PushPosXY(L, Maps::getTileBiomeRgn(pos)); } static const luaL_Reg dfhack_maps_funcs[] = { + { "isValidTilePos", maps_isValidTilePos }, { "getTileBlock", maps_getTileBlock }, + { "ensureTileBlock", maps_ensureTileBlock }, { "getRegionBiome", maps_getRegionBiome }, { "getTileBiomeRgn", maps_getTileBiomeRgn }, { NULL, NULL } @@ -919,6 +1034,7 @@ static bool buildings_containsTile(df::building *bld, int x, int y, bool room) { } static const LuaWrapper::FunctionReg dfhack_buildings_module[] = { + WRAPM(Buildings, setOwner), WRAPM(Buildings, allocInstance), WRAPM(Buildings, checkFreeTiles), WRAPM(Buildings, countExtentTiles), @@ -969,7 +1085,9 @@ static int buildings_getCorrectSize(lua_State *state) return 5; } -static int buildings_setSize(lua_State *state) +namespace { + +int buildings_setSize(lua_State *state) { auto bld = Lua::CheckDFObject<df::building>(state, 1); df::coord2d size(luaL_optint(state, 2, 1), luaL_optint(state, 3, 1)); @@ -990,11 +1108,13 @@ static int buildings_setSize(lua_State *state) return 1; } +} + static const luaL_Reg dfhack_buildings_funcs[] = { { "findAtTile", buildings_findAtTile }, { "findCivzonesAt", buildings_findCivzonesAt }, { "getCorrectSize", buildings_getCorrectSize }, - { "setSize", buildings_setSize }, + { "setSize", &Lua::CallWithCatchWrapper<buildings_setSize> }, { NULL, NULL } }; @@ -1019,6 +1139,204 @@ static const luaL_Reg dfhack_constructions_funcs[] = { { NULL, NULL } }; +/***** Screen module *****/ + +static const LuaWrapper::FunctionReg dfhack_screen_module[] = { + WRAPM(Screen, inGraphicsMode), + WRAPM(Screen, clear), + WRAPM(Screen, invalidate), + { NULL, NULL } +}; + +static int screen_getMousePos(lua_State *L) +{ + auto pos = Screen::getMousePos(); + lua_pushinteger(L, pos.x); + lua_pushinteger(L, pos.y); + return 2; +} + +static int screen_getWindowSize(lua_State *L) +{ + auto pos = Screen::getWindowSize(); + lua_pushinteger(L, pos.x); + lua_pushinteger(L, pos.y); + return 2; +} + +static int screen_paintTile(lua_State *L) +{ + Pen pen; + decode_pen(L, pen, 1); + int x = luaL_checkint(L, 2); + int y = luaL_checkint(L, 3); + if (lua_gettop(L) >= 4 && !lua_isnil(L, 4)) + { + if (lua_type(L, 4) == LUA_TSTRING) + pen.ch = lua_tostring(L, 4)[0]; + else + pen.ch = luaL_checkint(L, 4); + } + if (lua_gettop(L) >= 5 && !lua_isnil(L, 5)) + pen.tile = luaL_checkint(L, 5); + lua_pushboolean(L, Screen::paintTile(pen, x, y)); + return 1; +} + +static int screen_readTile(lua_State *L) +{ + int x = luaL_checkint(L, 1); + int y = luaL_checkint(L, 2); + Pen pen = Screen::readTile(x, y); + + if (!pen.valid()) + { + lua_pushnil(L); + } + else + { + lua_newtable(L); + lua_pushinteger(L, pen.ch); lua_setfield(L, -2, "ch"); + lua_pushinteger(L, pen.fg); lua_setfield(L, -2, "fg"); + lua_pushinteger(L, pen.bg); lua_setfield(L, -2, "bg"); + lua_pushboolean(L, pen.bold); lua_setfield(L, -2, "bold"); + + if (pen.tile) + { + lua_pushinteger(L, pen.tile); lua_setfield(L, -2, "tile"); + + switch (pen.tile_mode) { + case Pen::CharColor: + lua_pushboolean(L, true); lua_setfield(L, -2, "tile_color"); + break; + case Pen::TileColor: + lua_pushinteger(L, pen.tile_fg); lua_setfield(L, -2, "tile_fg"); + lua_pushinteger(L, pen.tile_bg); lua_setfield(L, -2, "tile_bg"); + break; + default: + break; + } + } + } + + return 1; +} + +static int screen_paintString(lua_State *L) +{ + Pen pen; + decode_pen(L, pen, 1); + int x = luaL_checkint(L, 2); + int y = luaL_checkint(L, 3); + const char *text = luaL_checkstring(L, 4); + lua_pushboolean(L, Screen::paintString(pen, x, y, text)); + return 1; +} + +static int screen_fillRect(lua_State *L) +{ + Pen pen; + decode_pen(L, pen, 1); + int x1 = luaL_checkint(L, 2); + int y1 = luaL_checkint(L, 3); + int x2 = luaL_checkint(L, 4); + int y2 = luaL_checkint(L, 5); + lua_pushboolean(L, Screen::fillRect(pen, x1, y1, x2, y2)); + return 1; +} + +static int screen_findGraphicsTile(lua_State *L) +{ + auto str = luaL_checkstring(L, 1); + int x = luaL_checkint(L, 2); + int y = luaL_checkint(L, 3); + int tile, tile_gs; + if (Screen::findGraphicsTile(str, x, y, &tile, &tile_gs)) + { + lua_pushinteger(L, tile); + lua_pushinteger(L, tile_gs); + return 2; + } + else + { + lua_pushnil(L); + return 1; + } +} + +namespace { + +int screen_show(lua_State *L) +{ + df::viewscreen *before = NULL; + if (lua_gettop(L) >= 2) + before = Lua::CheckDFObject<df::viewscreen>(L, 2); + + df::viewscreen *screen = dfhack_lua_viewscreen::get_pointer(L, 1, true); + + bool ok = Screen::show(screen, before); + + // If it is a table, get_pointer created a new object. Don't leak it. + if (!ok && lua_istable(L, 1)) + delete screen; + + lua_pushboolean(L, ok); + return 1; +} + +static int screen_dismiss(lua_State *L) +{ + df::viewscreen *screen = dfhack_lua_viewscreen::get_pointer(L, 1, false); + Screen::dismiss(screen); + return 0; +} + +static int screen_isDismissed(lua_State *L) +{ + df::viewscreen *screen = dfhack_lua_viewscreen::get_pointer(L, 1, false); + lua_pushboolean(L, Screen::isDismissed(screen)); + return 1; +} + +static int screen_doSimulateInput(lua_State *L) +{ + auto screen = Lua::CheckDFObject<df::viewscreen>(L, 1); + luaL_checktype(L, 2, LUA_TTABLE); + + if (!screen) + luaL_argerror(L, 1, "NULL screen"); + + int sz = lua_rawlen(L, 2); + std::set<df::interface_key> keys; + + for (int j = 1; j <= sz; j++) + { + lua_rawgeti(L, 2, j); + keys.insert((df::interface_key)lua_tointeger(L, -1)); + lua_pop(L, 1); + } + + screen->feed(&keys); + return 0; +} + +} + +static const luaL_Reg dfhack_screen_funcs[] = { + { "getMousePos", screen_getMousePos }, + { "getWindowSize", screen_getWindowSize }, + { "paintTile", screen_paintTile }, + { "readTile", screen_readTile }, + { "paintString", screen_paintString }, + { "fillRect", screen_fillRect }, + { "findGraphicsTile", screen_findGraphicsTile }, + { "show", &Lua::CallWithCatchWrapper<screen_show> }, + { "dismiss", screen_dismiss }, + { "isDismissed", screen_isDismissed }, + { "_doSimulateInput", screen_doSimulateInput }, + { NULL, NULL } +}; + /***** Internal module *****/ static void *checkaddr(lua_State *L, int idx, bool allow_null = false) @@ -1124,6 +1442,17 @@ static int internal_getMemRanges(lua_State *L) return 1; } +static int internal_patchMemory(lua_State *L) +{ + void *dest = checkaddr(L, 1); + void *src = checkaddr(L, 2); + int size = luaL_checkint(L, 3); + if (size < 0) luaL_argerror(L, 1, "negative size"); + bool ok = Core::getInstance().p->patchMemory(dest, src, size); + lua_pushboolean(L, ok); + return 1; +} + static int internal_memmove(lua_State *L) { void *dest = checkaddr(L, 1); @@ -1214,6 +1543,7 @@ static const luaL_Reg dfhack_internal_funcs[] = { { "setAddress", internal_setAddress }, { "getVTable", internal_getVTable }, { "getMemRanges", internal_getMemRanges }, + { "patchMemory", internal_patchMemory }, { "memmove", internal_memmove }, { "memcmp", internal_memcmp }, { "memscan", internal_memscan }, @@ -1240,5 +1570,6 @@ void OpenDFHackApi(lua_State *state) OpenModule(state, "burrows", dfhack_burrows_module, dfhack_burrows_funcs); OpenModule(state, "buildings", dfhack_buildings_module, dfhack_buildings_funcs); OpenModule(state, "constructions", dfhack_constructions_module); + OpenModule(state, "screen", dfhack_screen_module, dfhack_screen_funcs); OpenModule(state, "internal", dfhack_internal_module, dfhack_internal_funcs); } diff --git a/library/LuaTools.cpp b/library/LuaTools.cpp index 28571a0f..8fce0076 100644 --- a/library/LuaTools.cpp +++ b/library/LuaTools.cpp @@ -68,6 +68,11 @@ lua_State *DFHack::Lua::Core::State = NULL; void dfhack_printerr(lua_State *S, const std::string &str); +inline bool is_null_userdata(lua_State *L, int idx) +{ + return lua_islightuserdata(L, idx) && !lua_touserdata(L, idx); +} + inline void AssertCoreSuspend(lua_State *state) { assert(!Lua::IsCoreContext(state) || DFHack::Core::getInstance().isSuspended()); @@ -252,7 +257,7 @@ static int lua_dfhack_color(lua_State *S) { int cv = luaL_optint(S, 1, -1); - if (cv < -1 || cv > color_ostream::COLOR_MAX) + if (cv < -1 || cv > COLOR_MAX) luaL_argerror(S, 1, "invalid color value"); color_ostream *out = Lua::GetOutput(S); @@ -1206,6 +1211,39 @@ static int dfhack_open_plugin(lua_State *L) return 0; } +static int dfhack_curry_wrap(lua_State *L) +{ + int nargs = lua_gettop(L); + int ncurry = lua_tointeger(L, lua_upvalueindex(1)); + int scount = nargs + ncurry; + + luaL_checkstack(L, ncurry, "stack overflow in curry"); + + // Insert values in O(N+M) by first shifting the existing data + lua_settop(L, scount); + for (int i = 0; i < nargs; i++) + lua_copy(L, nargs-i, scount-i); + for (int i = 1; i <= ncurry; i++) + lua_copy(L, lua_upvalueindex(i+1), i); + + lua_callk(L, scount-1, LUA_MULTRET, 0, lua_gettop); + + return lua_gettop(L); +} + +static int dfhack_curry(lua_State *L) +{ + luaL_checkany(L, 1); + if (lua_isnil(L, 1)) + luaL_argerror(L, 1, "nil function in curry"); + if (lua_gettop(L) == 1) + return 1; + lua_pushinteger(L, lua_gettop(L)); + lua_insert(L, 1); + lua_pushcclosure(L, dfhack_curry_wrap, lua_gettop(L)); + return 1; +} + bool Lua::IsCoreContext(lua_State *state) { // This uses a private field of the lua state to @@ -1229,6 +1267,7 @@ static const luaL_Reg dfhack_funcs[] = { { "call_with_finalizer", dfhack_call_with_finalizer }, { "with_suspend", lua_dfhack_with_suspend }, { "open_plugin", dfhack_open_plugin }, + { "curry", dfhack_curry }, { NULL, NULL } }; @@ -1244,14 +1283,123 @@ static const luaL_Reg dfhack_coro_funcs[] = { static int DFHACK_EVENT_META_TOKEN = 0; -int DFHack::Lua::NewEvent(lua_State *state) +namespace { + struct EventObject { + int item_count; + Lua::Event::Owner *owner; + }; +} + +void DFHack::Lua::Event::New(lua_State *state, Owner *owner) { - lua_newtable(state); + auto obj = (EventObject *)lua_newuserdata(state, sizeof(EventObject)); + obj->item_count = 0; + obj->owner = owner; + lua_rawgetp(state, LUA_REGISTRYINDEX, &DFHACK_EVENT_META_TOKEN); lua_setmetatable(state, -2); + lua_newtable(state); + lua_setuservalue(state, -2); +} + +void DFHack::Lua::Event::SetPrivateCallback(lua_State *L, int event) +{ + lua_getuservalue(L, event); + lua_swap(L); + lua_rawsetp(L, -2, NULL); + lua_pop(L, 1); +} + +static int dfhack_event_new(lua_State *L) +{ + Lua::Event::New(L); + return 1; +} + +static int dfhack_event_len(lua_State *L) +{ + luaL_checktype(L, 1, LUA_TUSERDATA); + auto obj = (EventObject *)lua_touserdata(L, 1); + lua_pushinteger(L, obj->item_count); return 1; } +static int dfhack_event_tostring(lua_State *L) +{ + luaL_checktype(L, 1, LUA_TUSERDATA); + auto obj = (EventObject *)lua_touserdata(L, 1); + lua_pushfstring(L, "<event: %d listeners>", obj->item_count); + return 1; +} + +static int dfhack_event_index(lua_State *L) +{ + luaL_checktype(L, 1, LUA_TUSERDATA); + lua_getuservalue(L, 1); + lua_pushvalue(L, 2); + lua_rawget(L, -2); + return 1; +} + +static int dfhack_event_next(lua_State *L) +{ + luaL_checktype(L, 1, LUA_TUSERDATA); + lua_getuservalue(L, 1); + lua_pushvalue(L, 2); + while (lua_next(L, -2)) + { + if (is_null_userdata(L, -2)) + lua_pop(L, 1); + else + return 2; + } + lua_pushnil(L); + return 1; +} + +static int dfhack_event_pairs(lua_State *L) +{ + luaL_checktype(L, 1, LUA_TUSERDATA); + lua_pushcfunction(L, dfhack_event_next); + lua_pushvalue(L, 1); + lua_pushnil(L); + return 3; +} + +static int dfhack_event_newindex(lua_State *L) +{ + luaL_checktype(L, 1, LUA_TUSERDATA); + if (is_null_userdata(L, 2)) + luaL_argerror(L, 2, "Key NULL is reserved in events."); + + lua_settop(L, 3); + lua_getuservalue(L, 1); + bool new_nil = lua_isnil(L, 3); + + lua_pushvalue(L, 2); + lua_rawget(L, 4); + bool old_nil = lua_isnil(L, -1); + lua_settop(L, 4); + + lua_pushvalue(L, 2); + lua_pushvalue(L, 3); + lua_rawset(L, 4); + + int delta = 0; + if (old_nil && !new_nil) delta = 1; + else if (new_nil && !old_nil) delta = -1; + + if (delta != 0) + { + auto obj = (EventObject *)lua_touserdata(L, 1); + obj->item_count += delta; + if (obj->owner) + obj->owner->on_count_changed(obj->item_count, delta); + } + + return 0; +} + static void do_invoke_event(lua_State *L, int argbase, int num_args, int errorfun) { for (int i = 0; i < num_args; i++) @@ -1292,7 +1440,7 @@ static void dfhack_event_invoke(lua_State *L, int base, bool from_c) while (lua_next(L, event)) { // Skip the NULL key in the main loop - if (lua_islightuserdata(L, -2) && !lua_touserdata(L, -2)) + if (is_null_userdata(L, -2)) lua_pop(L, 1); else do_invoke_event(L, argbase, num_args, errorfun); @@ -1303,14 +1451,20 @@ static void dfhack_event_invoke(lua_State *L, int base, bool from_c) static int dfhack_event_call(lua_State *state) { - luaL_checktype(state, 1, LUA_TTABLE); + luaL_checktype(state, 1, LUA_TUSERDATA); luaL_checkstack(state, lua_gettop(state)+2, "stack overflow in event dispatch"); + auto obj = (EventObject *)lua_touserdata(state, 1); + if (obj->owner) + obj->owner->on_invoked(state, lua_gettop(state)-1, false); + + lua_getuservalue(state, 1); + lua_replace(state, 1); dfhack_event_invoke(state, 0, false); return 0; } -void DFHack::Lua::InvokeEvent(color_ostream &out, lua_State *state, void *key, int num_args) +void DFHack::Lua::Event::Invoke(color_ostream &out, lua_State *state, void *key, int num_args) { AssertCoreSuspend(state); @@ -1325,7 +1479,7 @@ void DFHack::Lua::InvokeEvent(color_ostream &out, lua_State *state, void *key, i lua_rawgetp(state, LUA_REGISTRYINDEX, key); - if (!lua_istable(state, -1)) + if (!lua_isuserdata(state, -1)) { if (!lua_isnil(state, -1)) out.printerr("Invalid event object in Lua::InvokeEvent"); @@ -1333,22 +1487,29 @@ void DFHack::Lua::InvokeEvent(color_ostream &out, lua_State *state, void *key, i return; } + auto obj = (EventObject *)lua_touserdata(state, -1); lua_insert(state, base+1); + if (obj->owner) + obj->owner->on_invoked(state, num_args, true); + + lua_getuservalue(state, base+1); + lua_replace(state, base+1); + color_ostream *cur_out = Lua::GetOutput(state); set_dfhack_output(state, &out); dfhack_event_invoke(state, base, true); set_dfhack_output(state, cur_out); } -void DFHack::Lua::MakeEvent(lua_State *state, void *key) +void DFHack::Lua::Event::Make(lua_State *state, void *key, Owner *owner) { lua_rawgetp(state, LUA_REGISTRYINDEX, key); if (lua_isnil(state, -1)) { lua_pop(state, 1); - NewEvent(state); + New(state, owner); } lua_dup(state); @@ -1358,7 +1519,7 @@ void DFHack::Lua::MakeEvent(lua_State *state, void *key) void DFHack::Lua::Notification::invoke(color_ostream &out, int nargs) { assert(state); - InvokeEvent(out, state, key, nargs); + Event::Invoke(out, state, key, nargs); } void DFHack::Lua::Notification::bind(lua_State *state, void *key) @@ -1369,12 +1530,12 @@ void DFHack::Lua::Notification::bind(lua_State *state, void *key) void DFHack::Lua::Notification::bind(lua_State *state, const char *name) { - MakeEvent(state, this); + Event::Make(state, this); if (handler) { PushFunctionWrapper(state, 0, name, handler); - lua_rawsetp(state, -2, NULL); + Event::SetPrivateCallback(state, -2); } this->state = state; @@ -1419,6 +1580,9 @@ lua_State *DFHack::Lua::Open(color_ostream &out, lua_State *state) lua_rawsetp(state, LUA_REGISTRYINDEX, &DFHACK_BASE_G_TOKEN); lua_setfield(state, -2, "BASE_G"); + lua_pushstring(state, DFHACK_VERSION); + lua_setfield(state, -2, "VERSION"); + lua_pushboolean(state, IsCoreContext(state)); lua_setfield(state, -2, "is_core_context"); @@ -1435,11 +1599,26 @@ lua_State *DFHack::Lua::Open(color_ostream &out, lua_State *state) lua_newtable(state); lua_pushcfunction(state, dfhack_event_call); lua_setfield(state, -2, "__call"); - lua_pushcfunction(state, Lua::NewEvent); - lua_setfield(state, -2, "new"); + lua_pushcfunction(state, dfhack_event_len); + lua_setfield(state, -2, "__len"); + lua_pushcfunction(state, dfhack_event_tostring); + lua_setfield(state, -2, "__tostring"); + lua_pushcfunction(state, dfhack_event_index); + lua_setfield(state, -2, "__index"); + lua_pushcfunction(state, dfhack_event_newindex); + lua_setfield(state, -2, "__newindex"); + lua_pushcfunction(state, dfhack_event_pairs); + lua_setfield(state, -2, "__pairs"); lua_dup(state); lua_rawsetp(state, LUA_REGISTRYINDEX, &DFHACK_EVENT_META_TOKEN); - lua_setfield(state, -2, "event"); + + lua_newtable(state); + lua_pushcfunction(state, dfhack_event_new); + lua_setfield(state, -2, "new"); + lua_dup(state); + lua_setfield(state, -3, "__metatable"); + lua_setfield(state, -3, "event"); + lua_pop(state, 1); // Initialize the dfhack global luaL_setfuncs(state, dfhack_funcs, 0); @@ -1599,7 +1778,7 @@ void DFHack::Lua::Core::onStateChange(color_ostream &out, int code) { } Lua::Push(State, code); - Lua::InvokeEvent(out, State, (void*)onStateChange, 1); + Lua::Event::Invoke(out, State, (void*)onStateChange, 1); } static void run_timers(color_ostream &out, lua_State *L, @@ -1635,7 +1814,9 @@ void DFHack::Lua::Core::onUpdate(color_ostream &out) lua_rawgetp(State, LUA_REGISTRYINDEX, &DFHACK_TIMEOUTS_TOKEN); run_timers(out, State, frame_timers, frame[1], ++frame_idx); - run_timers(out, State, tick_timers, frame[1], world->frame_counter); + + if (world) + run_timers(out, State, tick_timers, frame[1], world->frame_counter); } void DFHack::Lua::Core::Init(color_ostream &out) @@ -1653,7 +1834,7 @@ void DFHack::Lua::Core::Init(color_ostream &out) // Register events lua_rawgetp(State, LUA_REGISTRYINDEX, &DFHACK_DFHACK_TOKEN); - MakeEvent(State, (void*)onStateChange); + Event::Make(State, (void*)onStateChange); lua_setfield(State, -2, "onStateChange"); lua_pushcfunction(State, dfhack_timeout); diff --git a/library/LuaTypes.cpp b/library/LuaTypes.cpp index 8548c5d0..9f2689fa 100644 --- a/library/LuaTypes.cpp +++ b/library/LuaTypes.cpp @@ -37,6 +37,7 @@ distribution. #include "DataDefs.h" #include "DataIdentity.h" #include "LuaWrapper.h" +#include "LuaTools.h" #include "DataFuncs.h" #include "MiscUtils.h" @@ -285,6 +286,9 @@ void container_identity::lua_item_read(lua_State *state, int fname_idx, void *pt void container_identity::lua_item_write(lua_State *state, int fname_idx, void *ptr, int idx, int val_index) { + if (is_readonly()) + field_error(state, fname_idx, "container is read-only", "write"); + auto id = (type_identity*)lua_touserdata(state, UPVAL_ITEM_ID); void *pitem = item_pointer(id, ptr, idx); id->lua_write(state, fname_idx, pitem, val_index); @@ -890,7 +894,7 @@ static int meta_bitfield_len(lua_State *state) static void read_bitfield(lua_State *state, uint8_t *ptr, bitfield_identity *id, int idx) { - int size = id->getBits()[idx].size; + int size = std::max(1, id->getBits()[idx].size); int value = getBitfieldField(ptr, idx, size); if (size <= 1) @@ -947,7 +951,7 @@ static int meta_bitfield_newindex(lua_State *state) } int idx = check_container_index(state, id->getNumBits(), 2, iidx, "write"); - int size = id->getBits()[idx].size; + int size = std::max(1, id->getBits()[idx].size); if (lua_isboolean(state, 3) || lua_isnil(state, 3)) setBitfieldField(ptr, idx, size, lua_toboolean(state, 3)); @@ -1064,6 +1068,27 @@ int LuaWrapper::method_wrapper_core(lua_State *state, function_identity_base *id return 1; } +int Lua::CallWithCatch(lua_State *state, int (*fn)(lua_State*), const char *context) +{ + if (!context) + context = "native code"; + + try { + return fn(state); + } + catch (Error::NullPointer &e) { + const char *vn = e.varname(); + return luaL_error(state, "%s: NULL pointer: %s", context, vn ? vn : "?"); + } + catch (Error::InvalidArgument &e) { + const char *vn = e.expr(); + return luaL_error(state, "%s: Invalid argument; expected: %s", context, vn ? vn : "?"); + } + catch (std::exception &e) { + return luaL_error(state, "%s: C++ exception: %s", context, e.what()); + } +} + /** * Push a closure invoking the given function. */ diff --git a/library/PluginManager.cpp b/library/PluginManager.cpp index ff752431..ceb644e6 100644 --- a/library/PluginManager.cpp +++ b/library/PluginManager.cpp @@ -108,6 +108,50 @@ struct Plugin::RefAutoinc ~RefAutoinc(){ lock->lock_sub(); }; }; +struct Plugin::LuaCommand { + Plugin *owner; + std::string name; + int (*command)(lua_State *state); + + LuaCommand(Plugin *owner, std::string name) + : owner(owner), name(name), command(NULL) {} +}; + +struct Plugin::LuaFunction { + Plugin *owner; + std::string name; + function_identity_base *identity; + bool silent; + + LuaFunction(Plugin *owner, std::string name) + : owner(owner), name(name), identity(NULL), silent(false) {} +}; + +struct Plugin::LuaEvent : public Lua::Event::Owner { + LuaFunction handler; + Lua::Notification *event; + bool active; + int count; + + LuaEvent(Plugin *owner, std::string name) + : handler(owner,name), event(NULL), active(false), count(0) + { + handler.silent = true; + } + + void on_count_changed(int new_cnt, int delta) { + RefAutoinc lock(handler.owner->access); + count = new_cnt; + if (event) + event->on_count_changed(new_cnt, delta); + } + void on_invoked(lua_State *state, int nargs, bool from_c) { + RefAutoinc lock(handler.owner->access); + if (event) + event->on_invoked(state, nargs, from_c); + } +}; + Plugin::Plugin(Core * core, const std::string & filepath, const std::string & _filename, PluginManager * pm) { filename = filepath; @@ -142,19 +186,26 @@ Plugin::~Plugin() bool Plugin::load(color_ostream &con) { - RefAutolock lock(access); - if(state == PS_BROKEN) - { - return false; - } - else if(state == PS_LOADED) { - return true; + RefAutolock lock(access); + if(state == PS_LOADED) + { + return true; + } + else if(state != PS_UNLOADED) + { + return false; + } + state = PS_LOADING; } + // enter suspend + CoreSuspender suspend; + // open the library, etc DFLibrary * plug = OpenPlugin(filename.c_str()); if(!plug) { con.printerr("Can't load plugin %s\n", filename.c_str()); + RefAutolock lock(access); state = PS_BROKEN; return false; } @@ -164,6 +215,7 @@ bool Plugin::load(color_ostream &con) { con.printerr("Plugin %s has no name or version.\n", filename.c_str()); ClosePlugin(plug); + RefAutolock lock(access); state = PS_BROKEN; return false; } @@ -172,9 +224,11 @@ bool Plugin::load(color_ostream &con) con.printerr("Plugin %s was not built for this version of DFHack.\n" "Plugin: %s, DFHack: %s\n", *plug_name, *plug_version, DFHACK_VERSION); ClosePlugin(plug); + RefAutolock lock(access); state = PS_BROKEN; return false; } + RefAutolock lock(access); plugin_init = (command_result (*)(color_ostream &, std::vector <PluginCommand> &)) LookupPlugin(plug, "plugin_init"); if(!plugin_init) { @@ -226,6 +280,11 @@ bool Plugin::unload(color_ostream &con) } // wait for all calls to finish access->wait(); + state = PS_UNLOADING; + access->unlock(); + // enter suspend + CoreSuspender suspend; + access->lock(); // notify plugin about shutdown, if it has a shutdown function command_result cr = CR_OK; if(plugin_shutdown) @@ -439,7 +498,11 @@ void Plugin::index_lua(DFLibrary *lib) cmd->handler.identity = evlist->event->get_handler(); cmd->event = evlist->event; if (cmd->active) + { cmd->event->bind(Lua::Core::State, cmd); + if (cmd->count > 0) + cmd->event->on_count_changed(cmd->count, 0); + } } } } @@ -467,7 +530,7 @@ int Plugin::lua_cmd_wrapper(lua_State *state) luaL_error(state, "plugin command %s() has been unloaded", (cmd->owner->name+"."+cmd->name).c_str()); - return cmd->command(state); + return Lua::CallWithCatch(state, cmd->command, cmd->name.c_str()); } int Plugin::lua_fun_wrapper(lua_State *state) @@ -477,8 +540,13 @@ int Plugin::lua_fun_wrapper(lua_State *state) RefAutoinc lock(cmd->owner->access); if (!cmd->identity) + { + if (cmd->silent) + return 0; + luaL_error(state, "plugin function %s() has been unloaded", (cmd->owner->name+"."+cmd->name).c_str()); + } return LuaWrapper::method_wrapper_core(state, cmd->identity); } @@ -506,14 +574,14 @@ void Plugin::open_lua(lua_State *state, int table) { for (auto it = lua_events.begin(); it != lua_events.end(); ++it) { - Lua::MakeEvent(state, it->second); + Lua::Event::Make(state, it->second, it->second); push_function(state, &it->second->handler); - lua_rawsetp(state, -2, NULL); + Lua::Event::SetPrivateCallback(state, -2); it->second->active = true; if (it->second->event) - it->second->event->bind(state, it->second); + it->second->event->bind(Lua::Core::State, it->second); lua_setfield(state, table, it->first.c_str()); } diff --git a/library/Process-darwin.cpp b/library/Process-darwin.cpp index 5a97d9e0..3893cfc5 100644 --- a/library/Process-darwin.cpp +++ b/library/Process-darwin.cpp @@ -27,6 +27,7 @@ distribution. #include <errno.h> #include <unistd.h> #include <sys/mman.h> +#include <sys/time.h> #include <mach-o/dyld.h> @@ -262,6 +263,13 @@ bool Process::getThreadIDs(vector<uint32_t> & threads ) return true; } +uint32_t Process::getTickCount() +{ + struct timeval tp; + gettimeofday(&tp, NULL); + return (tp.tv_sec * 1000) + (tp.tv_usec / 1000); +} + string Process::getPath() { char path[1024]; diff --git a/library/Process-linux.cpp b/library/Process-linux.cpp index fe864784..1fecbab7 100644 --- a/library/Process-linux.cpp +++ b/library/Process-linux.cpp @@ -27,6 +27,7 @@ distribution. #include <errno.h> #include <unistd.h> #include <sys/mman.h> +#include <sys/time.h> #include <string> #include <vector> @@ -126,6 +127,9 @@ void Process::getMemRanges( vector<t_memrange> & ranges ) char permissions[5]; // r/-, w/-, x/-, p/s, 0 FILE *mapFile = ::fopen("/proc/self/maps", "r"); + if (!mapFile) + return; + size_t start, end, offset, device1, device2, node; while (fgets(buffer, 1024, mapFile)) @@ -147,6 +151,8 @@ void Process::getMemRanges( vector<t_memrange> & ranges ) temp.valid = true; ranges.push_back(temp); } + + fclose(mapFile); } uint32_t Process::getBase() @@ -192,6 +198,13 @@ bool Process::getThreadIDs(vector<uint32_t> & threads ) return true; } +uint32_t Process::getTickCount() +{ + struct timeval tp; + gettimeofday(&tp, NULL); + return (tp.tv_sec * 1000) + (tp.tv_usec / 1000); +} + string Process::getPath() { const char * cwd_name = "/proc/self/cwd"; diff --git a/library/Process-windows.cpp b/library/Process-windows.cpp index 7eb6ff5f..db58c4d3 100644 --- a/library/Process-windows.cpp +++ b/library/Process-windows.cpp @@ -410,6 +410,11 @@ string Process::doReadClassName (void * vptr) return raw; } +uint32_t Process::getTickCount() +{ + return GetTickCount(); +} + string Process::getPath() { HMODULE hmod; diff --git a/library/RemoteClient.cpp b/library/RemoteClient.cpp index 4d30988c..09861ad5 100644 --- a/library/RemoteClient.cpp +++ b/library/RemoteClient.cpp @@ -394,7 +394,7 @@ command_result RemoteFunctionBase::execute(color_ostream &out, //out.print("Received %d:%d\n", header.id, header.size); - if (header.id == RPC_REPLY_FAIL) + if ((DFHack::DFHackReplyCode)header.id == RPC_REPLY_FAIL) return header.size == CR_OK ? CR_FAILURE : command_result(header.size); if (header.size < 0 || header.size > RPCMessageHeader::MAX_MESSAGE_SIZE) diff --git a/library/RemoteServer.cpp b/library/RemoteServer.cpp index 53428f2b..06a9f859 100644 --- a/library/RemoteServer.cpp +++ b/library/RemoteServer.cpp @@ -250,7 +250,7 @@ void ServerConnection::threadFn() break; } - if (header.id == RPC_REQUEST_QUIT) + if ((DFHack::DFHackReplyCode)header.id == RPC_REQUEST_QUIT) break; if (header.size < 0 || header.size > RPCMessageHeader::MAX_MESSAGE_SIZE) diff --git a/library/RemoteTools.cpp b/library/RemoteTools.cpp index 95c495e9..b371d60f 100644 --- a/library/RemoteTools.cpp +++ b/library/RemoteTools.cpp @@ -287,7 +287,7 @@ void DFHack::describeUnit(BasicUnitInfo *info, df::unit *unit, if (mask && mask->profession()) { - if (unit->profession >= 0) + if (unit->profession >= (df::profession)0) info->set_profession(unit->profession); if (!unit->custom_profession.empty()) info->set_custom_profession(unit->custom_profession); diff --git a/library/VTableInterpose.cpp b/library/VTableInterpose.cpp new file mode 100644 index 00000000..48ae6109 --- /dev/null +++ b/library/VTableInterpose.cpp @@ -0,0 +1,513 @@ +/* +https://github.com/peterix/dfhack +Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#include "Internal.h" + +#include <string> +#include <vector> +#include <map> + +#include "MemAccess.h" +#include "Core.h" +#include "VersionInfo.h" +#include "VTableInterpose.h" + +#include "MiscUtils.h" + +using namespace DFHack; + +/* + * Code for accessing method pointers directly. Very compiler-specific. + */ + +#if defined(_MSC_VER) + +struct MSVC_MPTR { + void *method; + intptr_t this_shift; +}; + +static uint32_t *follow_jmp(void *ptr) +{ + uint8_t *p = (uint8_t*)ptr; + + for (;;) + { + switch (*p) + { + case 0xE9: + p += 5 + *(int32_t*)(p+1); + break; + case 0xEB: + p += 2 + *(int8_t*)(p+1); + break; + default: + return (uint32_t*)p; + } + } +} + +bool DFHack::is_vmethod_pointer_(void *pptr) +{ + auto pobj = (MSVC_MPTR*)pptr; + if (!pobj->method) return false; + + // MSVC implements pointers to vmethods via thunks. + // This expects that they all follow a very specific pattern. + auto pval = follow_jmp(pobj->method); + switch (pval[0]) { + case 0x20FF018BU: // mov eax, [ecx]; jmp [eax] + case 0x60FF018BU: // mov eax, [ecx]; jmp [eax+0x??] + case 0xA0FF018BU: // mov eax, [ecx]; jmp [eax+0x????????] + return true; + default: + return false; + } +} + +int DFHack::vmethod_pointer_to_idx_(void *pptr) +{ + auto pobj = (MSVC_MPTR*)pptr; + if (!pobj->method || pobj->this_shift != 0) return -1; + + auto pval = follow_jmp(pobj->method); + switch (pval[0]) { + case 0x20FF018BU: // mov eax, [ecx]; jmp [eax] + return 0; + case 0x60FF018BU: // mov eax, [ecx]; jmp [eax+0x??] + return ((int8_t)pval[1])/sizeof(void*); + case 0xA0FF018BU: // mov eax, [ecx]; jmp [eax+0x????????] + return ((int32_t)pval[1])/sizeof(void*); + default: + return -1; + } +} + +void* DFHack::method_pointer_to_addr_(void *pptr) +{ + if (is_vmethod_pointer_(pptr)) return NULL; + auto pobj = (MSVC_MPTR*)pptr; + return pobj->method; +} + +void DFHack::addr_to_method_pointer_(void *pptr, void *addr) +{ + auto pobj = (MSVC_MPTR*)pptr; + pobj->method = addr; + pobj->this_shift = 0; +} + +#elif defined(__GXX_ABI_VERSION) + +struct GCC_MPTR { + intptr_t method; + intptr_t this_shift; +}; + +bool DFHack::is_vmethod_pointer_(void *pptr) +{ + auto pobj = (GCC_MPTR*)pptr; + return (pobj->method & 1) != 0; +} + +int DFHack::vmethod_pointer_to_idx_(void *pptr) +{ + auto pobj = (GCC_MPTR*)pptr; + if ((pobj->method & 1) == 0 || pobj->this_shift != 0) + return -1; + return (pobj->method-1)/sizeof(void*); +} + +void* DFHack::method_pointer_to_addr_(void *pptr) +{ + auto pobj = (GCC_MPTR*)pptr; + if ((pobj->method & 1) != 0 || pobj->this_shift != 0) + return NULL; + return (void*)pobj->method; +} + +void DFHack::addr_to_method_pointer_(void *pptr, void *addr) +{ + auto pobj = (GCC_MPTR*)pptr; + pobj->method = (intptr_t)addr; + pobj->this_shift = 0; +} + +#else +#error Unknown compiler type +#endif + +void *virtual_identity::get_vmethod_ptr(int idx) +{ + assert(idx >= 0); + void **vtable = (void**)vtable_ptr; + if (!vtable) return NULL; + return vtable[idx]; +} + +bool virtual_identity::set_vmethod_ptr(int idx, void *ptr) +{ + assert(idx >= 0); + void **vtable = (void**)vtable_ptr; + if (!vtable) return NULL; + return Core::getInstance().p->patchMemory(&vtable[idx], &ptr, sizeof(void*)); +} + +/* + VMethod interposing data structures. + + In order to properly support adding and removing hooks, + it is necessary to track them. This is what this class + is for. The task is further complicated by propagating + hooks to child classes that use exactly the same original + vmethod implementation. + + Every applied link contains in the saved_chain field a + pointer to the next vmethod body that should be called + by the hook the link represents. This is the actual + control flow structure that needs to be maintained. + + There also are connections between link objects themselves, + which constitute the bookkeeping for doing that. Finally, + every link is associated with a fixed virtual_identity host, + which represents the point in the class hierarchy where + the hook is applied. + + When there are no subclasses (i.e. only one host), the + structures look like this: + + +--------------+ +------------+ + | link1 |-next------->| link2 |-next=NULL + |s_c: original |<-------prev-|s_c: $link1 |<--+ + +--------------+ +------------+ | + | + host->interpose_list[vmethod_idx] ------+ + vtable: $link2 + + The original vtable entry is stored in the saved_chain of the + first link. The interpose_list map points to the last one. + The hooks are called in order: link2 -> link1 -> original. + + When there are subclasses that use the same vmethod, but don't + hook it, the topmost link gets a set of the child_hosts, and + the hosts have the link added to their interpose_list: + + +--------------+ +----------------+ + | link0 @host0 |<--+-interpose_list-| host1 | + | |-child_hosts-+----->| vtable: $link | + +--------------+ | | +----------------+ + | | + | | +----------------+ + +-interpose_list-| host2 | + +----->| vtable: $link | + +----------------+ + + When a child defines its own hook, the child_hosts link is + severed and replaced with a child_next pointer to the new + hook. The hook still points back the chain with prev. + All child links to subclasses of host2 are migrated from + link1 to link2. + + +--------------+-next=NULL +--------------+-next=NULL + | link1 @host1 |-child_next------->| link2 @host2 |-child_*--->subclasses + | |<-------------prev-|s_c: $link1 | + +--------------+<-------+ +--------------+<-------+ + | | + +--------------+ | +--------------+ | + | host1 |-i_list-+ | host2 |-i_list-+ + |vtable: $link1| |vtable: $link2| + +--------------+ +--------------+ + + */ + +void VMethodInterposeLinkBase::set_chain(void *chain) +{ + saved_chain = chain; + addr_to_method_pointer_(chain_mptr, chain); +} + +VMethodInterposeLinkBase::VMethodInterposeLinkBase(virtual_identity *host, int vmethod_idx, void *interpose_method, void *chain_mptr, int priority) + : host(host), vmethod_idx(vmethod_idx), interpose_method(interpose_method), + chain_mptr(chain_mptr), priority(priority), + applied(false), saved_chain(NULL), next(NULL), prev(NULL) +{ + if (vmethod_idx < 0 || interpose_method == NULL) + { + fprintf(stderr, "Bad VMethodInterposeLinkBase arguments: %d %08x\n", + vmethod_idx, unsigned(interpose_method)); + fflush(stderr); + abort(); + } +} + +VMethodInterposeLinkBase::~VMethodInterposeLinkBase() +{ + if (is_applied()) + remove(); +} + +VMethodInterposeLinkBase *VMethodInterposeLinkBase::get_first_interpose(virtual_identity *id) +{ + auto item = id->interpose_list[vmethod_idx]; + if (!item) + return NULL; + + if (item->host != id) + return NULL; + while (item->prev && item->prev->host == id) + item = item->prev; + + return item; +} + +void VMethodInterposeLinkBase::find_child_hosts(virtual_identity *cur, void *vmptr) +{ + auto &children = cur->getChildren(); + + for (size_t i = 0; i < children.size(); i++) + { + auto child = static_cast<virtual_identity*>(children[i]); + auto base = get_first_interpose(child); + + if (base) + { + assert(base->prev == NULL); + + if (base->saved_chain != vmptr) + continue; + + child_next.insert(base); + } + else + { + void *cptr = child->get_vmethod_ptr(vmethod_idx); + if (cptr != vmptr) + continue; + + child_hosts.insert(child); + find_child_hosts(child, vmptr); + } + } +} + +void VMethodInterposeLinkBase::on_host_delete(virtual_identity *from) +{ + if (from == host) + { + // When in own host, fully delete + remove(); + } + else + { + // Otherwise, drop the link to that child: + assert(child_hosts.count(from) != 0 && + from->interpose_list[vmethod_idx] == this); + + // Find and restore the original vmethod ptr + auto last = this; + while (last->prev) last = last->prev; + + from->set_vmethod_ptr(vmethod_idx, last->saved_chain); + + // Unlink the chains + child_hosts.erase(from); + from->interpose_list[vmethod_idx] = NULL; + } +} + +bool VMethodInterposeLinkBase::apply(bool enable) +{ + if (!enable) + { + remove(); + return true; + } + + if (is_applied()) + return true; + if (!host->vtable_ptr) + return false; + + // Retrieve the current vtable entry + VMethodInterposeLinkBase *old_link = host->interpose_list[vmethod_idx]; + VMethodInterposeLinkBase *next_link = NULL; + + while (old_link && old_link->host == host && old_link->priority > priority) + { + next_link = old_link; + old_link = old_link->prev; + } + + void *old_ptr = next_link ? next_link->saved_chain : host->get_vmethod_ptr(vmethod_idx); + assert(old_ptr != NULL && (!old_link || old_link->interpose_method == old_ptr)); + + // Apply the new method ptr + set_chain(old_ptr); + + if (next_link) + { + next_link->set_chain(interpose_method); + } + else if (!host->set_vmethod_ptr(vmethod_idx, interpose_method)) + { + set_chain(NULL); + return false; + } + + // Push the current link into the home host + applied = true; + prev = old_link; + next = next_link; + + if (next_link) + next_link->prev = this; + else + host->interpose_list[vmethod_idx] = this; + + child_hosts.clear(); + child_next.clear(); + + if (old_link && old_link->host == host) + { + // If the old link is home, just push into the plain chain + assert(old_link->next == next_link); + old_link->next = this; + + // Child links belong to the topmost local entry + child_hosts.swap(old_link->child_hosts); + child_next.swap(old_link->child_next); + } + else if (next_link) + { + if (old_link) + { + assert(old_link->child_next.count(next_link)); + old_link->child_next.erase(next_link); + old_link->child_next.insert(this); + } + } + else + { + // If creating a new local chain, find children with same vmethod + find_child_hosts(host, old_ptr); + + if (old_link) + { + // Enter the child chain set + assert(old_link->child_hosts.count(host)); + old_link->child_hosts.erase(host); + old_link->child_next.insert(this); + + // Subtract our own children from the parent's sets + for (auto it = child_next.begin(); it != child_next.end(); ++it) + old_link->child_next.erase(*it); + for (auto it = child_hosts.begin(); it != child_hosts.end(); ++it) + old_link->child_hosts.erase(*it); + } + } + + assert (!next_link || (child_next.empty() && child_hosts.empty())); + + // Chain subclass hooks + for (auto it = child_next.begin(); it != child_next.end(); ++it) + { + auto nlink = *it; + assert(nlink->saved_chain == old_ptr && nlink->prev == old_link); + nlink->set_chain(interpose_method); + nlink->prev = this; + } + + // Chain passive subclass hosts + for (auto it = child_hosts.begin(); it != child_hosts.end(); ++it) + { + auto nhost = *it; + assert(nhost->interpose_list[vmethod_idx] == old_link); + nhost->set_vmethod_ptr(vmethod_idx, interpose_method); + nhost->interpose_list[vmethod_idx] = this; + } + + return true; +} + +void VMethodInterposeLinkBase::remove() +{ + if (!is_applied()) + return; + + // Remove the link from prev to this + if (prev) + { + if (prev->host == host) + prev->next = next; + else + { + prev->child_next.erase(this); + + if (next) + prev->child_next.insert(next); + else + prev->child_hosts.insert(host); + } + } + + if (next) + { + next->set_chain(saved_chain); + next->prev = prev; + + assert(child_next.empty() && child_hosts.empty()); + } + else + { + // Remove from the list in the identity and vtable + host->interpose_list[vmethod_idx] = prev; + host->set_vmethod_ptr(vmethod_idx, saved_chain); + + for (auto it = child_next.begin(); it != child_next.end(); ++it) + { + auto nlink = *it; + assert(nlink->saved_chain == interpose_method && nlink->prev == this); + nlink->set_chain(saved_chain); + nlink->prev = prev; + if (prev) + prev->child_next.insert(nlink); + } + + for (auto it = child_hosts.begin(); it != child_hosts.end(); ++it) + { + auto nhost = *it; + assert(nhost->interpose_list[vmethod_idx] == this); + nhost->interpose_list[vmethod_idx] = prev; + nhost->set_vmethod_ptr(vmethod_idx, saved_chain); + if (prev) + prev->child_hosts.insert(nhost); + } + } + + applied = false; + prev = next = NULL; + child_next.clear(); + child_hosts.clear(); + set_chain(NULL); +} diff --git a/library/include/BitArray.h b/library/include/BitArray.h index fd9bd98f..ff68ea1d 100644 --- a/library/include/BitArray.h +++ b/library/include/BitArray.h @@ -64,7 +64,7 @@ namespace DFHack if (newsize == size) return; uint8_t* mem = (uint8_t *) realloc(bits, newsize); - if(!mem) + if(!mem && newsize != 0) throw std::bad_alloc(); bits = mem; if (newsize > size) @@ -207,7 +207,7 @@ namespace DFHack else { T* mem = (T*) realloc(m_data, sizeof(T)*new_size); - if(!mem) + if(!mem && new_size != 0) throw std::bad_alloc(); m_data = mem; } diff --git a/library/include/ColorText.h b/library/include/ColorText.h index 0cc286dc..50d1f362 100644 --- a/library/include/ColorText.h +++ b/library/include/ColorText.h @@ -41,30 +41,32 @@ namespace dfproto namespace DFHack { + enum color_value + { + COLOR_RESET = -1, + COLOR_BLACK = 0, + COLOR_BLUE, + COLOR_GREEN, + COLOR_CYAN, + COLOR_RED, + COLOR_MAGENTA, + COLOR_BROWN, + COLOR_GREY, + COLOR_DARKGREY, + COLOR_LIGHTBLUE, + COLOR_LIGHTGREEN, + COLOR_LIGHTCYAN, + COLOR_LIGHTRED, + COLOR_LIGHTMAGENTA, + COLOR_YELLOW, + COLOR_WHITE, + COLOR_MAX = COLOR_WHITE + }; + class DFHACK_EXPORT color_ostream : public std::ostream { public: - enum color_value - { - COLOR_RESET = -1, - COLOR_BLACK = 0, - COLOR_BLUE, - COLOR_GREEN, - COLOR_CYAN, - COLOR_RED, - COLOR_MAGENTA, - COLOR_BROWN, - COLOR_GREY, - COLOR_DARKGREY, - COLOR_LIGHTBLUE, - COLOR_LIGHTGREEN, - COLOR_LIGHTCYAN, - COLOR_LIGHTRED, - COLOR_LIGHTMAGENTA, - COLOR_YELLOW, - COLOR_WHITE, - COLOR_MAX = COLOR_WHITE - }; + typedef DFHack::color_value color_value; private: color_value cur_color; diff --git a/library/include/Core.h b/library/include/Core.h index d25beef5..e1f1cf3f 100644 --- a/library/include/Core.h +++ b/library/include/Core.h @@ -174,6 +174,10 @@ namespace DFHack struct Private; Private *d; + friend class CoreSuspendClaimer; + int ClaimSuspend(bool force_base); + void DisclaimSuspend(int level); + bool Init(); int Update (void); int TileUpdate (void); @@ -181,6 +185,7 @@ namespace DFHack int DFH_SDL_Event(SDL::Event* event); bool ncurses_wgetch(int in, int & out); + void doUpdate(color_ostream &out, bool first_update); void onUpdate(color_ostream &out); void onStateChange(color_ostream &out, state_change_event event); @@ -249,4 +254,20 @@ namespace DFHack CoreSuspender(Core *core) : core(core) { core->Suspend(); } ~CoreSuspender() { core->Resume(); } }; + + /** Claims the current thread already has the suspend lock. + * Strictly for use in callbacks from DF. + */ + class CoreSuspendClaimer { + Core *core; + int level; + public: + CoreSuspendClaimer(bool base = false) : core(&Core::getInstance()) { + level = core->ClaimSuspend(base); + } + CoreSuspendClaimer(Core *core, bool base = false) : core(core) { + level = core->ClaimSuspend(base); + } + ~CoreSuspendClaimer() { core->DisclaimSuspend(level); } + }; } diff --git a/library/include/DataDefs.h b/library/include/DataDefs.h index 1d485156..0966c7f3 100644 --- a/library/include/DataDefs.h +++ b/library/include/DataDefs.h @@ -28,6 +28,7 @@ distribution. #include <sstream> #include <vector> #include <map> +#include <set> #include "Core.h" #include "BitArray.h" @@ -292,6 +293,8 @@ namespace DFHack typedef virtual_class *virtual_ptr; #endif + class DFHACK_EXPORT VMethodInterposeLinkBase; + class DFHACK_EXPORT virtual_identity : public struct_identity { static std::map<void*, virtual_identity*> known; @@ -299,6 +302,9 @@ namespace DFHack void *vtable_ptr; + friend class VMethodInterposeLinkBase; + std::map<int,VMethodInterposeLinkBase*> interpose_list; + protected: virtual void doInit(Core *core); @@ -306,10 +312,14 @@ namespace DFHack bool can_allocate() { return struct_identity::can_allocate() && (vtable_ptr != NULL); } + void *get_vmethod_ptr(int index); + bool set_vmethod_ptr(int index, void *ptr); + public: virtual_identity(size_t size, TAllocateFn alloc, const char *dfhack_name, const char *original_name, virtual_identity *parent, const struct_field_info *fields); + ~virtual_identity(); virtual identity_type type() { return IDTYPE_CLASS; } @@ -337,6 +347,8 @@ namespace DFHack : (this == get(instance_ptr)); } + template<class P> static P get_vmethod_ptr(P selector); + public: bool can_instantiate() { return can_allocate(); } virtual_ptr instantiate() { return can_instantiate() ? (virtual_ptr)do_allocate() : NULL; } @@ -506,7 +518,7 @@ namespace DFHack { template<class T> inline const char *enum_item_raw_key(T val) { typedef df::enum_traits<T> traits; - return traits::is_valid(val) ? traits::key_table[val - traits::first_item_value] : NULL; + return traits::is_valid(val) ? traits::key_table[(short)val - traits::first_item_value] : NULL; } /** @@ -695,6 +707,9 @@ namespace DFHack { // Global object pointers #include "df/global_objects.h" +#define DF_GLOBAL_VALUE(name,defval) (df::global::name ? *df::global::name : defval) +#define DF_GLOBAL_FIELD(name,fname,defval) (df::global::name ? df::global::name->fname : defval) + // A couple of headers that have to be included at once #include "df/coord2d.h" #include "df/coord.h" diff --git a/library/include/DataFuncs.h b/library/include/DataFuncs.h index 637a532f..01a798e3 100644 --- a/library/include/DataFuncs.h +++ b/library/include/DataFuncs.h @@ -75,106 +75,133 @@ namespace df { cur_lua_ostream_argument name(state); #define INSTANTIATE_RETURN_TYPE(FArgs) \ - template<FW_TARGSC class RT> struct return_type<RT (*) FArgs> { typedef RT type; }; \ - template<FW_TARGSC class RT, class CT> struct return_type<RT (CT::*) FArgs> { typedef RT type; }; + template<FW_TARGSC class RT> struct return_type<RT (*) FArgs> { \ + typedef RT type; \ + static const bool is_method = false; \ + }; \ + template<FW_TARGSC class RT, class CT> struct return_type<RT (CT::*) FArgs> { \ + typedef RT type; \ + typedef CT class_type; \ + static const bool is_method = true; \ + }; -#define INSTANTIATE_WRAPPERS(Count, FArgs, Args, Loads) \ +#define INSTANTIATE_WRAPPERS2(Count, FArgs, Args, Loads) \ template<FW_TARGS> struct function_wrapper<void (*) FArgs, true> { \ - static const bool is_method = false; \ static const int num_args = Count; \ static void execute(lua_State *state, int base, void (*cb) FArgs) { Loads; INVOKE_VOID(cb Args); } \ }; \ template<FW_TARGSC class RT> struct function_wrapper<RT (*) FArgs, false> { \ - static const bool is_method = false; \ static const int num_args = Count; \ static void execute(lua_State *state, int base, RT (*cb) FArgs) { Loads; INVOKE_RV(cb Args); } \ }; \ template<FW_TARGSC class CT> struct function_wrapper<void (CT::*) FArgs, true> { \ - static const bool is_method = true; \ static const int num_args = Count+1; \ static void execute(lua_State *state, int base, void (CT::*cb) FArgs) { \ LOAD_CLASS() Loads; INVOKE_VOID((self->*cb) Args); } \ }; \ template<FW_TARGSC class RT, class CT> struct function_wrapper<RT (CT::*) FArgs, false> { \ - static const bool is_method = true; \ static const int num_args = Count+1; \ static void execute(lua_State *state, int base, RT (CT::*cb) FArgs) { \ LOAD_CLASS(); Loads; INVOKE_RV((self->*cb) Args); } \ }; +#define INSTANTIATE_WRAPPERS(Count, FArgs, OFArgs, Args, OArgs, Loads) \ + INSTANTIATE_WRAPPERS2(Count, FArgs, Args, Loads) \ + INSTANTIATE_WRAPPERS2(Count, OFArgs, OArgs, LOAD_OSTREAM(out); Loads) + #define FW_TARGSC #define FW_TARGS INSTANTIATE_RETURN_TYPE(()) -INSTANTIATE_WRAPPERS(0, (), (), ;) -INSTANTIATE_WRAPPERS(0, (OSTREAM_ARG), (out), LOAD_OSTREAM(out);) +INSTANTIATE_WRAPPERS(0, (), (OSTREAM_ARG), (), (out), ;) #undef FW_TARGS #undef FW_TARGSC #define FW_TARGSC FW_TARGS, #define FW_TARGS class A1 INSTANTIATE_RETURN_TYPE((A1)) -INSTANTIATE_WRAPPERS(1, (A1), (vA1), LOAD_ARG(A1);) -INSTANTIATE_WRAPPERS(1, (OSTREAM_ARG,A1), (out,vA1), LOAD_OSTREAM(out); LOAD_ARG(A1);) +INSTANTIATE_WRAPPERS(1, (A1), (OSTREAM_ARG,A1), (vA1), (out,vA1), LOAD_ARG(A1);) #undef FW_TARGS #define FW_TARGS class A1, class A2 INSTANTIATE_RETURN_TYPE((A1,A2)) -INSTANTIATE_WRAPPERS(2, (A1,A2), (vA1,vA2), LOAD_ARG(A1); LOAD_ARG(A2);) -INSTANTIATE_WRAPPERS(2, (OSTREAM_ARG,A1,A2), (out,vA1,vA2), - LOAD_OSTREAM(out); LOAD_ARG(A1); LOAD_ARG(A2);) +INSTANTIATE_WRAPPERS(2, (A1,A2), (OSTREAM_ARG,A1,A2), (vA1,vA2), (out,vA1,vA2), + LOAD_ARG(A1); LOAD_ARG(A2);) #undef FW_TARGS #define FW_TARGS class A1, class A2, class A3 INSTANTIATE_RETURN_TYPE((A1,A2,A3)) -INSTANTIATE_WRAPPERS(3, (A1,A2,A3), (vA1,vA2,vA3), LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3);) -INSTANTIATE_WRAPPERS(3, (OSTREAM_ARG,A1,A2,A3), (out,vA1,vA2,vA3), - LOAD_OSTREAM(out); LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3);) +INSTANTIATE_WRAPPERS(3, (A1,A2,A3), (OSTREAM_ARG,A1,A2,A3), (vA1,vA2,vA3), (out,vA1,vA2,vA3), + LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3);) #undef FW_TARGS #define FW_TARGS class A1, class A2, class A3, class A4 INSTANTIATE_RETURN_TYPE((A1,A2,A3,A4)) -INSTANTIATE_WRAPPERS(4, (A1,A2,A3,A4), (vA1,vA2,vA3,vA4), +INSTANTIATE_WRAPPERS(4, (A1,A2,A3,A4), (OSTREAM_ARG,A1,A2,A3,A4), + (vA1,vA2,vA3,vA4), (out,vA1,vA2,vA3,vA4), LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); LOAD_ARG(A4);) -INSTANTIATE_WRAPPERS(4, (OSTREAM_ARG,A1,A2,A3,A4), (out,vA1,vA2,vA3,vA4), - LOAD_OSTREAM(out); LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); LOAD_ARG(A4);) #undef FW_TARGS #define FW_TARGS class A1, class A2, class A3, class A4, class A5 INSTANTIATE_RETURN_TYPE((A1,A2,A3,A4,A5)) -INSTANTIATE_WRAPPERS(5, (A1,A2,A3,A4,A5), (vA1,vA2,vA3,vA4,vA5), - LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); LOAD_ARG(A4); LOAD_ARG(A5);) -INSTANTIATE_WRAPPERS(5, (OSTREAM_ARG,A1,A2,A3,A4,A5), (out,vA1,vA2,vA3,vA4,vA5), - LOAD_OSTREAM(out); LOAD_ARG(A1); LOAD_ARG(A2); - LOAD_ARG(A3); LOAD_ARG(A4); LOAD_ARG(A5);) +INSTANTIATE_WRAPPERS(5, (A1,A2,A3,A4,A5), (OSTREAM_ARG,A1,A2,A3,A4,A5), + (vA1,vA2,vA3,vA4,vA5), (out,vA1,vA2,vA3,vA4,vA5), + LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); LOAD_ARG(A4); + LOAD_ARG(A5);) #undef FW_TARGS #define FW_TARGS class A1, class A2, class A3, class A4, class A5, class A6 INSTANTIATE_RETURN_TYPE((A1,A2,A3,A4,A5,A6)) -INSTANTIATE_WRAPPERS(6, (A1,A2,A3,A4,A5,A6), (vA1,vA2,vA3,vA4,vA5,vA6), - LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); - LOAD_ARG(A4); LOAD_ARG(A5); LOAD_ARG(A6);) -INSTANTIATE_WRAPPERS(6, (OSTREAM_ARG,A1,A2,A3,A4,A5,A6), (out,vA1,vA2,vA3,vA4,vA5,vA6), - LOAD_OSTREAM(out); LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); - LOAD_ARG(A4); LOAD_ARG(A5); LOAD_ARG(A6);) +INSTANTIATE_WRAPPERS(6, (A1,A2,A3,A4,A5,A6), (OSTREAM_ARG,A1,A2,A3,A4,A5,A6), + (vA1,vA2,vA3,vA4,vA5,vA6), (out,vA1,vA2,vA3,vA4,vA5,vA6), + LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); LOAD_ARG(A4); + LOAD_ARG(A5); LOAD_ARG(A6);) #undef FW_TARGS #define FW_TARGS class A1, class A2, class A3, class A4, class A5, class A6, class A7 INSTANTIATE_RETURN_TYPE((A1,A2,A3,A4,A5,A6,A7)) -INSTANTIATE_WRAPPERS(7, (A1,A2,A3,A4,A5,A6,A7), (vA1,vA2,vA3,vA4,vA5,vA6,vA7), - LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); - LOAD_ARG(A4); LOAD_ARG(A5); LOAD_ARG(A6); - LOAD_ARG(A7);) -INSTANTIATE_WRAPPERS(7, (OSTREAM_ARG,A1,A2,A3,A4,A5,A6,A7), (out,vA1,vA2,vA3,vA4,vA5,vA6,vA7), - LOAD_OSTREAM(out); LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); - LOAD_ARG(A4); LOAD_ARG(A5); LOAD_ARG(A6); LOAD_ARG(A7);) +INSTANTIATE_WRAPPERS(7, (A1,A2,A3,A4,A5,A6,A7), (OSTREAM_ARG,A1,A2,A3,A4,A5,A6,A7), + (vA1,vA2,vA3,vA4,vA5,vA6,vA7), (out,vA1,vA2,vA3,vA4,vA5,vA6,vA7), + LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); LOAD_ARG(A4); + LOAD_ARG(A5); LOAD_ARG(A6); LOAD_ARG(A7);) #undef FW_TARGS #define FW_TARGS class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8 INSTANTIATE_RETURN_TYPE((A1,A2,A3,A4,A5,A6,A7,A8)) +INSTANTIATE_WRAPPERS(8, (A1,A2,A3,A4,A5,A6,A7,A8), (OSTREAM_ARG,A1,A2,A3,A4,A5,A6,A7,A8), + (vA1,vA2,vA3,vA4,vA5,vA6,vA7,vA8), (out,vA1,vA2,vA3,vA4,vA5,vA6,vA7,vA8), + LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); LOAD_ARG(A4); + LOAD_ARG(A5); LOAD_ARG(A6); LOAD_ARG(A7); LOAD_ARG(A8);) +#undef FW_TARGS + +#define FW_TARGS class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9 +INSTANTIATE_RETURN_TYPE((A1,A2,A3,A4,A5,A6,A7,A8,A9)) +INSTANTIATE_WRAPPERS(9, (A1,A2,A3,A4,A5,A6,A7,A8,A9), + (OSTREAM_ARG,A1,A2,A3,A4,A5,A6,A7,A8,A9), + (vA1,vA2,vA3,vA4,vA5,vA6,vA7,vA8,vA9), + (out,vA1,vA2,vA3,vA4,vA5,vA6,vA7,vA8,vA9), + LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); LOAD_ARG(A4); + LOAD_ARG(A5); LOAD_ARG(A6); LOAD_ARG(A7); LOAD_ARG(A8); + LOAD_ARG(A9);) +#undef FW_TARGS + +#define FW_TARGS class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10 +INSTANTIATE_RETURN_TYPE((A1,A2,A3,A4,A5,A6,A7,A8,A9,A10)) +INSTANTIATE_WRAPPERS(10, (A1,A2,A3,A4,A5,A6,A7,A8,A9,A10), + (OSTREAM_ARG,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10), + (vA1,vA2,vA3,vA4,vA5,vA6,vA7,vA8,vA9,vA10), + (out,vA1,vA2,vA3,vA4,vA5,vA6,vA7,vA8,vA9,vA10), + LOAD_ARG(A1); LOAD_ARG(A2); LOAD_ARG(A3); LOAD_ARG(A4); + LOAD_ARG(A5); LOAD_ARG(A6); LOAD_ARG(A7); LOAD_ARG(A8); + LOAD_ARG(A9); LOAD_ARG(A10);) +#undef FW_TARGS + +#define FW_TARGS class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11 +INSTANTIATE_RETURN_TYPE((A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11)) #undef FW_TARGS #undef FW_TARGSC #undef INSTANTIATE_WRAPPERS +#undef INSTANTIATE_WRAPPERS2 #undef INVOKE_VOID #undef INVOKE_RV #undef LOAD_CLASS diff --git a/library/include/DataIdentity.h b/library/include/DataIdentity.h index dcd0ae97..21dc68d1 100644 --- a/library/include/DataIdentity.h +++ b/library/include/DataIdentity.h @@ -115,6 +115,8 @@ namespace DFHack virtual void lua_item_read(lua_State *state, int fname_idx, void *ptr, int idx); virtual void lua_item_write(lua_State *state, int fname_idx, void *ptr, int idx, int val_index); + virtual bool is_readonly() { return false; } + virtual bool resize(void *ptr, int size) { return false; } virtual bool erase(void *ptr, int index) { return false; } virtual bool insert(void *ptr, int index, void *pitem) { return false; } @@ -343,6 +345,33 @@ namespace df } }; + template<class T> + class ro_stl_container_identity : public container_identity { + const char *name; + + public: + ro_stl_container_identity(const char *name, type_identity *item, enum_identity *ienum = NULL) + : container_identity(sizeof(T), &allocator_fn<T>, item, ienum), name(name) + {} + + std::string getFullName(type_identity *item) { + return name + container_identity::getFullName(item); + } + + virtual bool is_readonly() { return true; } + virtual bool resize(void *ptr, int size) { return false; } + virtual bool erase(void *ptr, int size) { return false; } + virtual bool insert(void *ptr, int idx, void *item) { return false; } + + protected: + virtual int item_count(void *ptr, CountMode) { return ((T*)ptr)->size(); } + virtual void *item_pointer(type_identity *item, void *ptr, int idx) { + auto iter = (*(T*)ptr).begin(); + for (; idx > 0; idx--) ++iter; + return (void*)&*iter; + } + }; + class bit_array_identity : public bit_container_identity { public: /* @@ -361,7 +390,7 @@ namespace df } virtual bool resize(void *ptr, int size) { - ((container*)ptr)->resize(size); + ((container*)ptr)->resize(size*8); return true; } @@ -517,6 +546,10 @@ namespace df static container_identity *get(); }; + template<class T> struct identity_traits<std::set<T> > { + static container_identity *get(); + }; + template<> struct identity_traits<BitArray<int> > { static bit_array_identity identity; static bit_container_identity *get() { return &identity; } @@ -580,6 +613,13 @@ namespace df } template<class T> + inline container_identity *identity_traits<std::set<T> >::get() { + typedef std::set<T> container; + static ro_stl_container_identity<container> identity("set", identity_traits<T>::get()); + return &identity; + } + + template<class T> inline bit_container_identity *identity_traits<BitArray<T> >::get() { static bit_array_identity identity(identity_traits<T>::get()); return &identity; diff --git a/library/include/LuaTools.h b/library/include/LuaTools.h index d3c7a65d..3330e23e 100644 --- a/library/include/LuaTools.h +++ b/library/include/LuaTools.h @@ -192,6 +192,16 @@ namespace DFHack {namespace Lua { } /** + * Call through to the function with try/catch for C++ exceptions. + */ + DFHACK_EXPORT int CallWithCatch(lua_State *, int (*fn)(lua_State*), const char *context = NULL); + + template<int (*cb)(lua_State*)> + int CallWithCatchWrapper(lua_State *state) { + return CallWithCatch(state, cb); + } + + /** * Invoke lua function via pcall. Returns true if success. * If an error is signalled, and perr is true, it is printed and popped from the stack. */ @@ -277,6 +287,11 @@ namespace DFHack {namespace Lua { PushDFObject(state, ptr); } + template<class T> inline void SetField(lua_State *L, T val, int idx, const char *name) { + if (idx < 0) idx = lua_absindex(L, idx); + Push(L, val); lua_setfield(L, idx, name); + } + template<class T> void PushVector(lua_State *state, const T &pvec, bool addn = false) { @@ -300,9 +315,18 @@ namespace DFHack {namespace Lua { DFHACK_EXPORT bool IsCoreContext(lua_State *state); - DFHACK_EXPORT int NewEvent(lua_State *state); - DFHACK_EXPORT void MakeEvent(lua_State *state, void *key); - DFHACK_EXPORT void InvokeEvent(color_ostream &out, lua_State *state, void *key, int num_args); + namespace Event { + struct DFHACK_EXPORT Owner { + virtual ~Owner() {} + virtual void on_count_changed(int new_cnt, int delta) {} + virtual void on_invoked(lua_State *state, int nargs, bool from_c) {} + }; + + DFHACK_EXPORT void New(lua_State *state, Owner *owner = NULL); + DFHACK_EXPORT void Make(lua_State *state, void *key, Owner *owner = NULL); + DFHACK_EXPORT void SetPrivateCallback(lua_State *state, int ev_idx); + DFHACK_EXPORT void Invoke(color_ostream &out, lua_State *state, void *key, int num_args); + } class StackUnwinder { lua_State *state; @@ -355,18 +379,24 @@ namespace DFHack {namespace Lua { } } - class DFHACK_EXPORT Notification { + class DFHACK_EXPORT Notification : public Event::Owner { lua_State *state; void *key; function_identity_base *handler; + int count; public: Notification(function_identity_base *handler = NULL) - : state(NULL), key(NULL), handler(handler) {} + : state(NULL), key(NULL), handler(handler), count(0) {} + int get_listener_count() { return count; } lua_State *get_state() { return state; } function_identity_base *get_handler() { return handler; } + lua_State *state_if_count() { return (count > 0) ? state : NULL; } + + void on_count_changed(int new_cnt, int) { count = new_cnt; } + void invoke(color_ostream &out, int nargs); void bind(lua_State *state, const char *name); @@ -378,7 +408,7 @@ namespace DFHack {namespace Lua { static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ void name(color_ostream &out) { \ handler(out); \ - if (name##_event.get_state()) { \ + if (name##_event.state_if_count()) { \ name##_event.invoke(out, 0); \ } \ } @@ -387,7 +417,7 @@ namespace DFHack {namespace Lua { static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ void name(color_ostream &out, arg_type1 arg1) { \ handler(out, arg1); \ - if (auto state = name##_event.get_state()) { \ + if (auto state = name##_event.state_if_count()) { \ DFHack::Lua::Push(state, arg1); \ name##_event.invoke(out, 1); \ } \ @@ -397,7 +427,7 @@ namespace DFHack {namespace Lua { static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ void name(color_ostream &out, arg_type1 arg1, arg_type2 arg2) { \ handler(out, arg1, arg2); \ - if (auto state = name##_event.get_state()) { \ + if (auto state = name##_event.state_if_count()) { \ DFHack::Lua::Push(state, arg1); \ DFHack::Lua::Push(state, arg2); \ name##_event.invoke(out, 2); \ @@ -408,7 +438,7 @@ namespace DFHack {namespace Lua { static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ void name(color_ostream &out, arg_type1 arg1, arg_type2 arg2, arg_type3 arg3) { \ handler(out, arg1, arg2, arg3); \ - if (auto state = name##_event.get_state()) { \ + if (auto state = name##_event.state_if_count()) { \ DFHack::Lua::Push(state, arg1); \ DFHack::Lua::Push(state, arg2); \ DFHack::Lua::Push(state, arg3); \ @@ -420,7 +450,7 @@ namespace DFHack {namespace Lua { static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ void name(color_ostream &out, arg_type1 arg1, arg_type2 arg2, arg_type3 arg3, arg_type4 arg4) { \ handler(out, arg1, arg2, arg3, arg4); \ - if (auto state = name##_event.get_state()) { \ + if (auto state = name##_event.state_if_count()) { \ DFHack::Lua::Push(state, arg1); \ DFHack::Lua::Push(state, arg2); \ DFHack::Lua::Push(state, arg3); \ @@ -433,7 +463,7 @@ namespace DFHack {namespace Lua { static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ void name(color_ostream &out, arg_type1 arg1, arg_type2 arg2, arg_type3 arg3, arg_type4 arg4, arg_type5 arg5) { \ handler(out, arg1, arg2, arg3, arg4, arg5); \ - if (auto state = name##_event.get_state()) { \ + if (auto state = name##_event.state_if_count()) { \ DFHack::Lua::Push(state, arg1); \ DFHack::Lua::Push(state, arg2); \ DFHack::Lua::Push(state, arg3); \ diff --git a/library/include/MemAccess.h b/library/include/MemAccess.h index c51df3c6..a226018a 100644 --- a/library/include/MemAccess.h +++ b/library/include/MemAccess.h @@ -281,8 +281,14 @@ namespace DFHack /// get the DF Process FilePath std::string getPath(); + /// millisecond tick count, exactly as DF uses + uint32_t getTickCount(); + /// modify permisions of memory range bool setPermisions(const t_memrange & range,const t_memrange &trgrange); + + /// write a possibly read-only memory area + bool patchMemory(void *target, const void* src, size_t count); private: VersionInfo * my_descriptor; PlatformSpecific *d; diff --git a/library/include/PluginManager.h b/library/include/PluginManager.h index 22171a15..38f0e2e5 100644 --- a/library/include/PluginManager.h +++ b/library/include/PluginManager.h @@ -128,7 +128,9 @@ namespace DFHack { PS_UNLOADED, PS_LOADED, - PS_BROKEN + PS_BROKEN, + PS_LOADING, + PS_UNLOADING }; friend class PluginManager; friend class RPCService; @@ -173,31 +175,16 @@ namespace DFHack PluginManager * parent; plugin_state state; - struct LuaCommand { - Plugin *owner; - std::string name; - int (*command)(lua_State *state); - LuaCommand(Plugin *owner, std::string name) : owner(owner), name(name) {} - }; + struct LuaCommand; std::map<std::string, LuaCommand*> lua_commands; static int lua_cmd_wrapper(lua_State *state); - struct LuaFunction { - Plugin *owner; - std::string name; - function_identity_base *identity; - LuaFunction(Plugin *owner, std::string name) : owner(owner), name(name) {} - }; + struct LuaFunction; std::map<std::string, LuaFunction*> lua_functions; static int lua_fun_wrapper(lua_State *state); void push_function(lua_State *state, LuaFunction *fn); - struct LuaEvent { - LuaFunction handler; - Lua::Notification *event; - bool active; - LuaEvent(Plugin *owner, std::string name) : handler(owner,name), active(false) {} - }; + struct LuaEvent; std::map<std::string, LuaEvent*> lua_events; void index_lua(DFLibrary *lib); diff --git a/library/include/RemoteTools.h b/library/include/RemoteTools.h index 65884bad..e87e8026 100644 --- a/library/include/RemoteTools.h +++ b/library/include/RemoteTools.h @@ -88,7 +88,7 @@ namespace DFHack { typedef df::enum_traits<T> traits; int base = traits::first_item; - int size = traits::last_item - base + 1; + int size = (int)traits::last_item - base + 1; describeEnum(pf, base, size, traits::key_table); } diff --git a/library/include/VTableInterpose.h b/library/include/VTableInterpose.h new file mode 100644 index 00000000..aeb407a8 --- /dev/null +++ b/library/include/VTableInterpose.h @@ -0,0 +1,190 @@ +/* +https://github.com/peterix/dfhack +Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#pragma once + +#include "DataFuncs.h" + +namespace DFHack +{ + template<bool> struct StaticAssert; + template<> struct StaticAssert<true> {}; + +#define STATIC_ASSERT(condition) { StaticAssert<(condition)>(); } + + /* Wrapping around compiler-specific representation of pointers to methods. */ + +#if defined(_MSC_VER) +#define METHOD_POINTER_SIZE (sizeof(void*)*2) +#elif defined(__GXX_ABI_VERSION) +#define METHOD_POINTER_SIZE (sizeof(void*)*2) +#else +#error Unknown compiler type +#endif + +#define ASSERT_METHOD_POINTER(type) \ + STATIC_ASSERT(df::return_type<type>::is_method && sizeof(type)==METHOD_POINTER_SIZE); + + DFHACK_EXPORT bool is_vmethod_pointer_(void*); + DFHACK_EXPORT int vmethod_pointer_to_idx_(void*); + DFHACK_EXPORT void* method_pointer_to_addr_(void*); + DFHACK_EXPORT void addr_to_method_pointer_(void*,void*); + + template<class T> bool is_vmethod_pointer(T ptr) { + ASSERT_METHOD_POINTER(T); + return is_vmethod_pointer_(&ptr); + } + template<class T> int vmethod_pointer_to_idx(T ptr) { + ASSERT_METHOD_POINTER(T); + return vmethod_pointer_to_idx_(&ptr); + } + template<class T> void *method_pointer_to_addr(T ptr) { + ASSERT_METHOD_POINTER(T); + return method_pointer_to_addr_(&ptr); + } + template<class T> T addr_to_method_pointer(void *addr) { + ASSERT_METHOD_POINTER(T); + T rv; + addr_to_method_pointer_(&rv, addr); + return rv; + } + + /* Access to vmethod pointers from the vtable. */ + + template<class P> + P virtual_identity::get_vmethod_ptr(P selector) + { + typedef typename df::return_type<P>::class_type host_class; + virtual_identity &identity = host_class::_identity; + int idx = vmethod_pointer_to_idx(selector); + return addr_to_method_pointer<P>(identity.get_vmethod_ptr(idx)); + } + + /* VMethod interpose API. + + This API allows replacing an entry in the original vtable + with code defined by DFHack, while retaining ability to + call the original code. The API can be safely used from + plugins, and multiple hooks for the same vmethod are + automatically chained (subclass before superclass; at same + level highest priority called first; undefined order otherwise). + + Usage: + + struct my_hack : df::someclass { + typedef df::someclass interpose_base; + + DEFINE_VMETHOD_INTERPOSE(void, foo, (int arg)) { + // If needed by the code, claim the suspend lock. + // DO NOT USE THE USUAL CoreSuspender, OR IT WILL DEADLOCK! + // CoreSuspendClaimer suspend; + ... + INTERPOSE_NEXT(foo)(arg) // call the original + ... + } + }; + + IMPLEMENT_VMETHOD_INTERPOSE(my_hack, foo); + or + IMPLEMENT_VMETHOD_INTERPOSE_PRIO(my_hack, foo, priority); + + void init() { + if (!INTERPOSE_HOOK(my_hack, foo).apply()) + error(); + } + + void shutdown() { + INTERPOSE_HOOK(my_hack, foo).remove(); + } + */ + +#define DEFINE_VMETHOD_INTERPOSE(rtype, name, args) \ + typedef rtype (interpose_base::*interpose_ptr_##name)args; \ + static DFHack::VMethodInterposeLink<interpose_base,interpose_ptr_##name> interpose_##name; \ + rtype interpose_fn_##name args + +#define IMPLEMENT_VMETHOD_INTERPOSE_PRIO(class,name,priority) \ + DFHack::VMethodInterposeLink<class::interpose_base,class::interpose_ptr_##name> \ + class::interpose_##name(&class::interpose_base::name, &class::interpose_fn_##name, priority); + +#define IMPLEMENT_VMETHOD_INTERPOSE(class,name) IMPLEMENT_VMETHOD_INTERPOSE_PRIO(class,name,0) + +#define INTERPOSE_NEXT(name) (this->*interpose_##name.chain) +#define INTERPOSE_HOOK(class, name) (class::interpose_##name) + + class DFHACK_EXPORT VMethodInterposeLinkBase { + /* + These link objects try to: + 1) Allow multiple hooks into the same vmethod + 2) Auto-remove hooks when a plugin is unloaded. + */ + friend class virtual_identity; + + virtual_identity *host; // Class with the vtable + int vmethod_idx; + void *interpose_method; // Pointer to the code of the interposing method + void *chain_mptr; // Pointer to the chain field below + int priority; + + bool applied; + void *saved_chain; // Previous pointer to the code + VMethodInterposeLinkBase *next, *prev; // Other hooks for the same method + + // inherited vtable members + std::set<virtual_identity*> child_hosts; + std::set<VMethodInterposeLinkBase*> child_next; + + void set_chain(void *chain); + void on_host_delete(virtual_identity *host); + + VMethodInterposeLinkBase *get_first_interpose(virtual_identity *id); + void find_child_hosts(virtual_identity *cur, void *vmptr); + public: + VMethodInterposeLinkBase(virtual_identity *host, int vmethod_idx, void *interpose_method, void *chain_mptr, int priority); + ~VMethodInterposeLinkBase(); + + bool is_applied() { return applied; } + bool apply(bool enable = true); + void remove(); + }; + + template<class Base, class Ptr> + class VMethodInterposeLink : public VMethodInterposeLinkBase { + public: + Ptr chain; + + operator Ptr () { return chain; } + + template<class Ptr2> + VMethodInterposeLink(Ptr target, Ptr2 src, int priority) + : VMethodInterposeLinkBase( + &Base::_identity, + vmethod_pointer_to_idx(target), + method_pointer_to_addr(src), + &chain, + priority + ) + { src = target; /* check compatibility */ } + }; +} diff --git a/library/include/modules/Buildings.h b/library/include/modules/Buildings.h index 6e0a2205..639df686 100644 --- a/library/include/modules/Buildings.h +++ b/library/include/modules/Buildings.h @@ -93,6 +93,11 @@ DFHACK_EXPORT bool Read (const uint32_t index, t_building & building); DFHACK_EXPORT bool ReadCustomWorkshopTypes(std::map <uint32_t, std::string> & btypes); /** + * Sets the owner unit for the building. + */ +DFHACK_EXPORT bool setOwner(df::building *building, df::unit *owner); + +/** * Find the building located at the specified tile. * Does not work on civzones. */ diff --git a/library/include/modules/Gui.h b/library/include/modules/Gui.h index e7155c43..b06408f6 100644 --- a/library/include/modules/Gui.h +++ b/library/include/modules/Gui.h @@ -32,6 +32,7 @@ distribution. #include "DataDefs.h" #include "df/init.h" #include "df/ui.h" +#include "df/announcement_type.h" namespace df { struct viewscreen; @@ -55,8 +56,6 @@ namespace DFHack */ namespace Gui { - inline df::viewscreen *getCurViewscreen() { return Core::getTopViewscreen(); } - DFHACK_EXPORT std::string getFocusString(df::viewscreen *top); // Full-screen item details view @@ -92,13 +91,38 @@ namespace DFHack DFHACK_EXPORT bool any_item_hotkey(df::viewscreen *top); DFHACK_EXPORT df::item *getSelectedItem(color_ostream &out, bool quiet = false); + // A building is selected via 'q', 't' or 'i' (civzone) + DFHACK_EXPORT bool any_building_hotkey(df::viewscreen *top); + DFHACK_EXPORT df::building *getSelectedBuilding(color_ostream &out, bool quiet = false); + // Show a plain announcement, or a titan-style popup message DFHACK_EXPORT void showAnnouncement(std::string message, int color = 7, bool bright = true); + DFHACK_EXPORT void showZoomAnnouncement(df::announcement_type type, df::coord pos, std::string message, int color = 7, bool bright = true); DFHACK_EXPORT void showPopupAnnouncement(std::string message, int color = 7, bool bright = true); + // Show an announcement with effects determined by announcements.txt + DFHACK_EXPORT void showAutoAnnouncement(df::announcement_type type, df::coord pos, std::string message, int color = 7, bool bright = true); + /* * Cursor and window coords */ + DFHACK_EXPORT df::coord getViewportPos(); + DFHACK_EXPORT df::coord getCursorPos(); + + static const int AREA_MAP_WIDTH = 23; + static const int MENU_WIDTH = 30; + + struct DwarfmodeDims { + int map_x1, map_x2, menu_x1, menu_x2, area_x1, area_x2; + int y1, y2; + bool menu_on, area_on, menu_forced; + }; + + DFHACK_EXPORT DwarfmodeDims getDwarfmodeViewDims(); + + DFHACK_EXPORT void resetDwarfmodeView(bool pause = false); + DFHACK_EXPORT bool revealInDwarfmodeMap(df::coord pos, bool center = false); + DFHACK_EXPORT bool getViewCoords (int32_t &x, int32_t &y, int32_t &z); DFHACK_EXPORT bool setViewCoords (const int32_t x, const int32_t y, const int32_t z); @@ -113,7 +137,11 @@ namespace DFHack * Gui screens */ /// Get the current top-level view-screen - DFHACK_EXPORT df::viewscreen * GetCurrentScreen(); + DFHACK_EXPORT df::viewscreen *getCurViewscreen(bool skip_dismissed = false); + + inline std::string getCurFocus(bool skip_dismissed = false) { + return getFocusString(getCurViewscreen(skip_dismissed)); + } /// get the size of the window buffer DFHACK_EXPORT bool getWindowSize(int32_t & width, int32_t & height); diff --git a/library/include/modules/Items.h b/library/include/modules/Items.h index 4236f068..81c8e128 100644 --- a/library/include/modules/Items.h +++ b/library/include/modules/Items.h @@ -44,6 +44,7 @@ distribution. namespace df { struct itemdef; + struct proj_itemst; } namespace MapExtras { @@ -155,5 +156,11 @@ DFHACK_EXPORT bool moveToContainer(MapExtras::MapCache &mc, df::item *item, df:: DFHACK_EXPORT bool moveToBuilding(MapExtras::MapCache &mc, df::item *item, df::building_actual *building,int16_t use_mode); DFHACK_EXPORT bool moveToInventory(MapExtras::MapCache &mc, df::item *item, df::unit *unit, df::unit_inventory_item::T_mode mode = df::unit_inventory_item::Carried, int body_part = -1); + +/// Makes the item removed and marked for garbage collection +DFHACK_EXPORT bool remove(MapExtras::MapCache &mc, df::item *item, bool no_uncat = false); + +/// Detaches the items from its current location and turns it into a projectile +DFHACK_EXPORT df::proj_itemst *makeProjectile(MapExtras::MapCache &mc, df::item *item); } } diff --git a/library/include/modules/MapCache.h b/library/include/modules/MapCache.h index 109a20a4..262e70bb 100644 --- a/library/include/modules/MapCache.h +++ b/library/include/modules/MapCache.h @@ -253,6 +253,8 @@ public: bool is_valid() { return valid; } df::map_block *getRaw() { return block; } + bool Allocate(); + MapCache *getParent() { return parent; } private: @@ -262,6 +264,8 @@ private: MapCache *parent; df::map_block *block; + void init(); + int biomeIndexAt(df::coord2d p); bool valid; @@ -347,6 +351,12 @@ class DFHACK_EXPORT MapCache return BlockAt(df::coord(coord.x>>4,coord.y>>4,coord.z)); } + bool ensureBlockAt(df::coord coord) + { + Block *b = BlockAtTile(coord); + return b ? b->Allocate() : false; + } + df::tiletype baseTiletypeAt (DFCoord tilecoord) { Block *b = BlockAtTile(tilecoord); diff --git a/library/include/modules/Maps.h b/library/include/modules/Maps.h index e63eef73..869b2158 100644 --- a/library/include/modules/Maps.h +++ b/library/include/modules/Maps.h @@ -50,6 +50,7 @@ distribution. #include "df/tile_dig_designation.h" #include "df/tile_traffic.h" #include "df/feature_init.h" +#include "df/flow_type.h" /** * \defgroup grp_maps Maps module and its types @@ -232,14 +233,19 @@ extern DFHACK_EXPORT void getSize(uint32_t& x, uint32_t& y, uint32_t& z); /// get the position of the map on world map extern DFHACK_EXPORT void getPosition(int32_t& x, int32_t& y, int32_t& z); +extern DFHACK_EXPORT bool isValidTilePos(int32_t x, int32_t y, int32_t z); +inline bool isValidTilePos(df::coord pos) { return isValidTilePos(pos.x, pos.y, pos.z); } + /** * Get the map block or NULL if block is not valid */ extern DFHACK_EXPORT df::map_block * getBlock (int32_t blockx, int32_t blocky, int32_t blockz); extern DFHACK_EXPORT df::map_block * getTileBlock (int32_t x, int32_t y, int32_t z); +extern DFHACK_EXPORT df::map_block * ensureTileBlock (int32_t x, int32_t y, int32_t z); inline df::map_block * getBlock (df::coord pos) { return getBlock(pos.x, pos.y, pos.z); } inline df::map_block * getTileBlock (df::coord pos) { return getTileBlock(pos.x, pos.y, pos.z); } +inline df::map_block * ensureTileBlock (df::coord pos) { return ensureTileBlock(pos.x, pos.y, pos.z); } extern DFHACK_EXPORT df::tiletype *getTileType(int32_t x, int32_t y, int32_t z); extern DFHACK_EXPORT df::tile_designation *getTileDesignation(int32_t x, int32_t y, int32_t z); @@ -258,7 +264,7 @@ inline df::tile_occupancy *getTileOccupancy(df::coord pos) { /** * Returns biome info about the specified world region. */ -DFHACK_EXPORT df::world_data::T_region_map *getRegionBiome(df::coord2d rgn_pos); +DFHACK_EXPORT df::region_map_entry *getRegionBiome(df::coord2d rgn_pos); /** * Returns biome world region coordinates for the given tile within given block. @@ -272,6 +278,8 @@ inline df::coord2d getTileBiomeRgn(df::coord pos) { // Enables per-frame updates for liquid flow and/or temperature. DFHACK_EXPORT void enableBlockUpdates(df::map_block *blk, bool flow = false, bool temperature = false); +DFHACK_EXPORT df::flow_info *spawnFlow(df::coord pos, df::flow_type type, int mat_type = 0, int mat_index = -1, int density = 100); + /// sorts the block event vector into multiple vectors by type /// mineral veins, what's under ice, blood smears and mud extern DFHACK_EXPORT bool SortBlockEvents(df::map_block *block, diff --git a/library/include/modules/Materials.h b/library/include/modules/Materials.h index 76c89de3..fb5a6353 100644 --- a/library/include/modules/Materials.h +++ b/library/include/modules/Materials.h @@ -131,6 +131,11 @@ namespace DFHack bool findPlant(const std::string &token, const std::string &subtoken); bool findCreature(const std::string &token, const std::string &subtoken); + bool findProduct(df::material *material, const std::string &name); + bool findProduct(const MaterialInfo &info, const std::string &name) { + return findProduct(info.material, name); + } + std::string getToken(); std::string toString(uint16_t temp = 10015, bool named = true); diff --git a/library/include/modules/Screen.h b/library/include/modules/Screen.h new file mode 100644 index 00000000..fdad6c8a --- /dev/null +++ b/library/include/modules/Screen.h @@ -0,0 +1,200 @@ +/* +https://github.com/peterix/dfhack +Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#pragma once +#include "Export.h" +#include "Module.h" +#include "BitArray.h" +#include "ColorText.h" +#include <string> + +#include "DataDefs.h" +#include "df/graphic.h" +#include "df/viewscreen.h" + +namespace df +{ + struct job; + struct item; + struct unit; + struct building; +} + +/** + * \defgroup grp_screen utilities for painting to the screen + * @ingroup grp_screen + */ + +namespace DFHack +{ + class Core; + + /** + * The Screen module + * \ingroup grp_modules + * \ingroup grp_screen + */ + namespace Screen + { + /// Data structure describing all properties a screen tile can have + struct Pen { + // Ordinary text symbol + char ch; + int8_t fg, bg; + bool bold; + + // Graphics tile + int tile; + enum TileMode { + AsIs, // Tile colors used without modification + CharColor, // The fg/bg pair is used + TileColor // The fields below are used + } tile_mode; + int8_t tile_fg, tile_bg; + + bool valid() const { return tile >= 0; } + bool empty() const { return ch == 0 && tile == 0; } + + Pen(char ch = 0, int8_t fg = 7, int8_t bg = 0, int tile = 0, bool color_tile = false) + : ch(ch), fg(fg&7), bg(bg), bold(!!(fg&8)), + tile(tile), tile_mode(color_tile ? CharColor : AsIs), tile_fg(0), tile_bg(0) + {} + Pen(char ch, int8_t fg, int8_t bg, bool bold, int tile = 0, bool color_tile = false) + : ch(ch), fg(fg), bg(bg), bold(bold), + tile(tile), tile_mode(color_tile ? CharColor : AsIs), tile_fg(0), tile_bg(0) + {} + Pen(char ch, int8_t fg, int8_t bg, int tile, int8_t tile_fg, int8_t tile_bg) + : ch(ch), fg(fg&7), bg(bg), bold(!!(fg&8)), + tile(tile), tile_mode(TileColor), tile_fg(tile_fg), tile_bg(tile_bg) + {} + Pen(char ch, int8_t fg, int8_t bg, bool bold, int tile, int8_t tile_fg, int8_t tile_bg) + : ch(ch), fg(fg), bg(bg), bold(bold), + tile(tile), tile_mode(TileColor), tile_fg(tile_fg), tile_bg(tile_bg) + {} + }; + + DFHACK_EXPORT df::coord2d getMousePos(); + DFHACK_EXPORT df::coord2d getWindowSize(); + + /// Returns the state of [GRAPHICS:YES/NO] + DFHACK_EXPORT bool inGraphicsMode(); + + /// Paint one screen tile with the given pen + DFHACK_EXPORT bool paintTile(const Pen &pen, int x, int y); + + /// Retrieves one screen tile from the buffer + DFHACK_EXPORT Pen readTile(int x, int y); + + /// Paint a string onto the screen. Ignores ch and tile of pen. + DFHACK_EXPORT bool paintString(const Pen &pen, int x, int y, const std::string &text); + + /// Fills a rectangle with one pen. Possibly more efficient than a loop over paintTile. + DFHACK_EXPORT bool fillRect(const Pen &pen, int x1, int y1, int x2, int y2); + + /// Draws a standard dark gray window border with a title string + DFHACK_EXPORT bool drawBorder(const std::string &title); + + /// Wipes the screen to full black + DFHACK_EXPORT bool clear(); + + /// Requests repaint + DFHACK_EXPORT bool invalidate(); + + /// Find a loaded graphics tile from graphics raws. + DFHACK_EXPORT bool findGraphicsTile(const std::string &page, int x, int y, int *ptile, int *pgs = NULL); + + // Push and remove viewscreens + DFHACK_EXPORT bool show(df::viewscreen *screen, df::viewscreen *before = NULL); + DFHACK_EXPORT void dismiss(df::viewscreen *screen, bool to_first = false); + DFHACK_EXPORT bool isDismissed(df::viewscreen *screen); + } + + class DFHACK_EXPORT dfhack_viewscreen : public df::viewscreen { + df::coord2d last_size; + void check_resize(); + + protected: + bool text_input_mode; + + public: + dfhack_viewscreen(); + virtual ~dfhack_viewscreen(); + + static bool is_instance(df::viewscreen *screen); + static dfhack_viewscreen *try_cast(df::viewscreen *screen); + + virtual void logic(); + virtual void render(); + + virtual int8_t movies_okay() { return 1; } + virtual bool key_conflict(df::interface_key key); + + virtual bool is_lua_screen() { return false; } + + virtual std::string getFocusString() = 0; + virtual void onShow() {}; + virtual void onDismiss() {}; + virtual df::unit *getSelectedUnit() { return NULL; } + virtual df::item *getSelectedItem() { return NULL; } + virtual df::job *getSelectedJob() { return NULL; } + virtual df::building *getSelectedBuilding() { return NULL; } + }; + + class DFHACK_EXPORT dfhack_lua_viewscreen : public dfhack_viewscreen { + std::string focus; + + void update_focus(lua_State *L, int idx); + + bool safe_call_lua(int (*pf)(lua_State *), int args, int rvs); + static dfhack_lua_viewscreen *get_self(lua_State *L); + + static int do_destroy(lua_State *L); + static int do_render(lua_State *L); + static int do_notify(lua_State *L); + static int do_input(lua_State *L); + + public: + dfhack_lua_viewscreen(lua_State *L, int table_idx); + virtual ~dfhack_lua_viewscreen(); + + static df::viewscreen *get_pointer(lua_State *L, int idx, bool make); + + virtual bool is_lua_screen() { return true; } + virtual std::string getFocusString() { return focus; } + + virtual void render(); + virtual void logic(); + virtual void help(); + virtual void resize(int w, int h); + virtual void feed(std::set<df::interface_key> *keys); + + virtual void onShow(); + virtual void onDismiss(); + + virtual df::unit *getSelectedUnit(); + virtual df::item *getSelectedItem(); + virtual df::job *getSelectedJob(); + virtual df::building *getSelectedBuilding(); + }; +} diff --git a/library/include/modules/Units.h b/library/include/modules/Units.h index 7bf4f101..65f0b58a 100644 --- a/library/include/modules/Units.h +++ b/library/include/modules/Units.h @@ -32,6 +32,10 @@ distribution. #include "modules/Items.h" #include "DataDefs.h" #include "df/unit.h" +#include "df/misc_trait_type.h" +#include "df/physical_attribute_type.h" +#include "df/mental_attribute_type.h" +#include "df/job_skill.h" namespace df { @@ -41,6 +45,7 @@ namespace df struct historical_entity; struct entity_position_assignment; struct entity_position; + struct unit_misc_trait; } /** @@ -208,6 +213,18 @@ DFHACK_EXPORT df::language_name *getVisibleName(df::unit *unit); DFHACK_EXPORT df::assumed_identity *getIdentity(df::unit *unit); DFHACK_EXPORT df::nemesis_record *getNemesis(df::unit *unit); +DFHACK_EXPORT bool isHidingCurse(df::unit *unit); +DFHACK_EXPORT int getPhysicalAttrValue(df::unit *unit, df::physical_attribute_type attr); +DFHACK_EXPORT int getMentalAttrValue(df::unit *unit, df::mental_attribute_type attr); + +DFHACK_EXPORT bool isCrazed(df::unit *unit); +DFHACK_EXPORT bool isOpposedToLife(df::unit *unit); +DFHACK_EXPORT bool hasExtravision(df::unit *unit); +DFHACK_EXPORT bool isBloodsucker(df::unit *unit); +DFHACK_EXPORT bool isMischievous(df::unit *unit); + +DFHACK_EXPORT df::unit_misc_trait *getMiscTrait(df::unit *unit, df::misc_trait_type type, bool create = false); + DFHACK_EXPORT bool isDead(df::unit *unit); DFHACK_EXPORT bool isAlive(df::unit *unit); DFHACK_EXPORT bool isSane(df::unit *unit); @@ -216,6 +233,9 @@ DFHACK_EXPORT bool isDwarf(df::unit *unit); DFHACK_EXPORT double getAge(df::unit *unit, bool true_age = false); +DFHACK_EXPORT int getEffectiveSkill(df::unit *unit, df::job_skill skill_id); +DFHACK_EXPORT int computeMovementSpeed(df::unit *unit); + struct NoblePosition { df::historical_entity *entity; df::entity_position_assignment *assignment; @@ -226,6 +246,9 @@ DFHACK_EXPORT bool getNoblePositions(std::vector<NoblePosition> *pvec, df::unit DFHACK_EXPORT std::string getProfessionName(df::unit *unit, bool ignore_noble = false, bool plural = false); DFHACK_EXPORT std::string getCasteProfessionName(int race, int caste, df::profession pid, bool plural = false); + +DFHACK_EXPORT int8_t getProfessionColor(df::unit *unit, bool ignore_noble = false); +DFHACK_EXPORT int8_t getCasteProfessionColor(int race, int caste, df::profession pid); } } #endif diff --git a/library/lua/class.lua b/library/lua/class.lua new file mode 100644 index 00000000..7b142e49 --- /dev/null +++ b/library/lua/class.lua @@ -0,0 +1,150 @@ +-- A trivial reloadable class system + +local _ENV = mkmodule('class') + +-- Metatable template for a class +class_obj = {} or class_obj + +-- Methods shared by all classes +common_methods = {} or common_methods + +-- Forbidden names for class fields and methods. +reserved_names = { super = true, ATTRS = true } + +-- Attribute table metatable +attrs_meta = {} or attrs_meta + +-- Create or updates a class; a class has metamethods and thus own metatable. +function defclass(class,parent) + class = class or {} + + local meta = getmetatable(class) + if not meta then + meta = {} + setmetatable(class, meta) + end + + for k,v in pairs(class_obj) do meta[k] = v end + + meta.__index = parent or common_methods + + local attrs = rawget(class, 'ATTRS') or {} + setmetatable(attrs, attrs_meta) + + rawset(class, 'super', parent) + rawset(class, 'ATTRS', attrs) + rawset(class, '__index', rawget(class, '__index') or class) + + return class +end + +-- An instance uses the class as metatable +function mkinstance(class,table) + table = table or {} + setmetatable(table, class) + return table +end + +-- Patch the stubs in the global environment +dfhack.BASE_G.defclass = _ENV.defclass +dfhack.BASE_G.mkinstance = _ENV.mkinstance + +-- Just verify the name, and then set. +function class_obj:__newindex(name,val) + if reserved_names[name] or common_methods[name] then + error('Method name '..name..' is reserved.') + end + rawset(self, name, val) +end + +function attrs_meta:__call(attrs) + for k,v in pairs(attrs) do + self[k] = v + end +end + +local function apply_attrs(obj, attrs, init_table) + for k,v in pairs(attrs) do + if v == DEFAULT_NIL then + v = nil + end + obj[k] = init_table[k] or v + end +end + +local function invoke_before_rec(self, class, method, ...) + local meta = getmetatable(class) + if meta then + local fun = rawget(class, method) + if fun then + fun(self, ...) + end + + invoke_before_rec(self, meta.__index, method, ...) + end +end + +local function invoke_after_rec(self, class, method, ...) + local meta = getmetatable(class) + if meta then + invoke_after_rec(self, meta.__index, method, ...) + + local fun = rawget(class, method) + if fun then + fun(self, ...) + end + end +end + +local function init_attrs_rec(obj, class, init_table) + local meta = getmetatable(class) + if meta then + init_attrs_rec(obj, meta.__index, init_table) + apply_attrs(obj, rawget(class, 'ATTRS'), init_table) + end +end + +-- Call metamethod constructs the object +function class_obj:__call(init_table) + -- The table is assumed to be a scratch temporary. + -- If it is not, copy it yourself before calling. + init_table = init_table or {} + + local obj = mkinstance(self) + + -- This initialization sequence is broadly based on how the + -- Common Lisp initialize-instance generic function works. + + -- preinit screens input arguments in subclass to superclass order + invoke_before_rec(obj, self, 'preinit', init_table) + -- initialize the instance table from init table + init_attrs_rec(obj, self, init_table) + -- init in superclass -> subclass + invoke_after_rec(obj, self, 'init', init_table) + -- postinit in superclass -> subclass + invoke_after_rec(obj, self, 'postinit', init_table) + + return obj +end + +-- Common methods for all instances: + +function common_methods:callback(method, ...) + return dfhack.curry(self[method], self, ...) +end + +function common_methods:assign(data) + for k,v in pairs(data) do + self[k] = v + end +end + +function common_methods:invoke_before(method, ...) + return invoke_before_rec(self, getmetatable(self), method, ...) +end + +function common_methods:invoke_after(method, ...) + return invoke_after_rec(self, getmetatable(self), method, ...) +end + +return _ENV diff --git a/library/lua/dfhack.lua b/library/lua/dfhack.lua index 86ea1459..ce3be5a8 100644 --- a/library/lua/dfhack.lua +++ b/library/lua/dfhack.lua @@ -46,6 +46,7 @@ end -- Error handling safecall = dfhack.safecall +curry = dfhack.curry function dfhack.pcall(f, ...) return xpcall(f, dfhack.onerror, ...) @@ -83,7 +84,7 @@ function mkmodule(module,env) error("Not a table in package.loaded["..module.."]") end end - local plugname = string.match(module,'^plugins%.(%w+)$') + local plugname = string.match(module,'^plugins%.([%w%-]+)$') if plugname then dfhack.open_plugin(pkg,plugname) end @@ -102,11 +103,32 @@ function reload(module) dofile(path) end +-- Trivial classes + +function rawset_default(target,source) + for k,v in pairs(source) do + if rawget(target,k) == nil then + rawset(target,k,v) + end + end +end + +DEFAULT_NIL = DEFAULT_NIL or {} -- Unique token + +function defclass(...) + return require('class').defclass(...) +end + +function mkinstance(...) + return require('class').mkinstance(...) +end + -- Misc functions function printall(table) - if type(table) == 'table' or df.isvalid(table) == 'ref' then - for k,v in pairs(table) do + local ok,f,t,k = pcall(pairs,table) + if ok then + for k,v in f,t,k do print(string.format("%-23s\t = %s",tostring(k),tostring(v))) end end @@ -135,14 +157,23 @@ function xyz2pos(x,y,z) end end -function rawset_default(target,source) - for k,v in pairs(source) do - if rawget(target,k) == nil then - rawset(target,k,v) +function pos2xy(pos) + if pos then + local x = pos.x + if x and x ~= -30000 then + return x, pos.y end end end +function xy2pos(x,y) + if x then + return {x=x,y=y} + else + return {x=-30000,y=-30000} + end +end + function safe_index(obj,idx,...) if obj == nil or idx == nil then return nil @@ -160,10 +191,6 @@ end -- String conversions -function dfhack.event:__tostring() - return "<event>" -end - function dfhack.persistent:__tostring() return "<persistent "..self.entry_id..":"..self.key.."=\"" ..self.value.."\":"..table.concat(self.ints,",")..">" diff --git a/library/lua/gui.lua b/library/lua/gui.lua new file mode 100644 index 00000000..6eaa9860 --- /dev/null +++ b/library/lua/gui.lua @@ -0,0 +1,420 @@ +-- Viewscreen implementation utility collection. + +local _ENV = mkmodule('gui') + +local dscreen = dfhack.screen + +USE_GRAPHICS = dscreen.inGraphicsMode() + +CLEAR_PEN = {ch=32,fg=0,bg=0} + +function simulateInput(screen,...) + local keys = {} + local function push_key(arg) + local kv = arg + if type(arg) == 'string' then + kv = df.interface_key[arg] + if kv == nil then + error('Invalid keycode: '..arg) + end + end + if type(kv) == 'number' then + keys[#keys+1] = kv + end + end + for i = 1,select('#',...) do + local arg = select(i,...) + if arg ~= nil then + local t = type(arg) + if type(arg) == 'table' then + for k,v in pairs(arg) do + if v == true then + push_key(k) + else + push_key(v) + end + end + else + push_key(arg) + end + end + end + dscreen._doSimulateInput(screen, keys) +end + +function mkdims_xy(x1,y1,x2,y2) + return { x1=x1, y1=y1, x2=x2, y2=y2, width=x2-x1+1, height=y2-y1+1 } +end +function mkdims_wh(x1,y1,w,h) + return { x1=x1, y1=y1, x2=x1+w-1, y2=y1+h-1, width=w, height=h } +end +function inset(rect,dx1,dy1,dx2,dy2) + return mkdims_xy( + rect.x1+dx1, rect.y1+dy1, + rect.x2-(dx2 or dx1), rect.y2-(dy2 or dy1) + ) +end +function is_in_rect(rect,x,y) + return x and y and x >= rect.x1 and x <= rect.x2 and y >= rect.y1 and y <= rect.y2 +end + +local function to_pen(default, pen, bg, bold) + if pen == nil then + return default or {} + elseif type(pen) ~= 'table' then + return {fg=pen,bg=bg,bold=bold} + else + return pen + end +end + +---------------------------- +-- Clipped painter object -- +---------------------------- + +Painter = defclass(Painter, nil) + +function Painter:init(args) + local rect = args.rect or mkdims_wh(0,0,dscreen.getWindowSize()) + local crect = args.clip_rect or rect + self:assign{ + x = rect.x1, y = rect.y1, + x1 = rect.x1, clip_x1 = crect.x1, + y1 = rect.y1, clip_y1 = crect.y1, + x2 = rect.x2, clip_x2 = crect.x2, + y2 = rect.y2, clip_y2 = crect.y2, + width = rect.x2-rect.x1+1, + height = rect.y2-rect.y1+1, + cur_pen = to_pen(nil, args.pen or COLOR_GREY) + } +end + +function Painter.new(rect, pen) + return Painter{ rect = rect, pen = pen } +end + +function Painter:isValidPos() + return self.x >= self.clip_x1 and self.x <= self.clip_x2 + and self.y >= self.clip_y1 and self.y <= self.clip_y2 +end + +function Painter:viewport(x,y,w,h) + if type(x) == 'table' then + x,y,w,h = x.x1, x.y1, x.width, x.height + end + local x1,y1 = self.x1+x, self.y1+y + local x2,y2 = x1+w-1, y1+h-1 + local vp = { + -- Logical viewport + x1 = x1, y1 = y1, x2 = x2, y2 = y2, + width = w, height = h, + -- Actual clipping rect + clip_x1 = math.max(self.clip_x1, x1), + clip_y1 = math.max(self.clip_y1, y1), + clip_x2 = math.min(self.clip_x2, x2), + clip_y2 = math.min(self.clip_y2, y2), + -- Pen + cur_pen = self.cur_pen + } + return mkinstance(Painter, vp):seek(0,0) +end + +function Painter:localX() + return self.x - self.x1 +end + +function Painter:localY() + return self.y - self.y1 +end + +function Painter:seek(x,y) + if x then self.x = self.x1 + x end + if y then self.y = self.y1 + y end + return self +end + +function Painter:advance(dx,dy) + if dx then self.x = self.x + dx end + if dy then self.y = self.y + dy end + return self +end + +function Painter:newline(dx) + self.y = self.y + 1 + self.x = self.x1 + (dx or 0) + return self +end + +function Painter:pen(pen,...) + self.cur_pen = to_pen(self.cur_pen, pen, ...) + return self +end + +function Painter:color(fg,bold,bg) + self.cur_pen = copyall(self.cur_pen) + self.cur_pen.fg = fg + self.cur_pen.bold = bold + if bg then self.cur_pen.bg = bg end + return self +end + +function Painter:clear() + dscreen.fillRect(CLEAR_PEN, self.clip_x1, self.clip_y1, self.clip_x2, self.clip_y2) + return self +end + +function Painter:fill(x1,y1,x2,y2,pen,bg,bold) + if type(x1) == 'table' then + x1, y1, x2, y2, pen, bg, bold = x1.x1, x1.y1, x1.x2, x1.y2, y1, x2, y2 + end + x1 = math.max(x1+self.x1,self.clip_x1) + y1 = math.max(y1+self.y1,self.clip_y1) + x2 = math.min(x2+self.x1,self.clip_x2) + y2 = math.min(y2+self.y1,self.clip_y2) + dscreen.fillRect(to_pen(self.cur_pen,pen,bg,bold),x1,y1,x2,y2) + return self +end + +function Painter:char(char,pen,...) + if self:isValidPos() then + dscreen.paintTile(to_pen(self.cur_pen, pen, ...), self.x, self.y, char) + end + return self:advance(1, nil) +end + +function Painter:tile(char,tile,pen,...) + if self:isValidPos() then + dscreen.paintTile(to_pen(self.cur_pen, pen, ...), self.x, self.y, char, tile) + end + return self:advance(1, nil) +end + +function Painter:string(text,pen,...) + if self.y >= self.clip_y1 and self.y <= self.clip_y2 then + local dx = 0 + if self.x < self.clip_x1 then + dx = self.clip_x1 - self.x + end + local len = #text + if self.x + len - 1 > self.clip_x2 then + len = self.clip_x2 - self.x + 1 + end + if len > dx then + dscreen.paintString( + to_pen(self.cur_pen, pen, ...), + self.x+dx, self.y, + string.sub(text,dx+1,len) + ) + end + end + return self:advance(#text, nil) +end + +------------------------ +-- Base screen object -- +------------------------ + +Screen = defclass(Screen) + +Screen.text_input_mode = false + +function Screen:postinit() + self:updateLayout() +end + +Screen.isDismissed = dscreen.isDismissed + +function Screen:isShown() + return self._native ~= nil +end + +function Screen:isActive() + return self:isShown() and not self:isDismissed() +end + +function Screen:invalidate() + dscreen.invalidate() +end + +function Screen:getWindowSize() + return dscreen.getWindowSize() +end + +function Screen:getMousePos() + return dscreen.getMousePos() +end + +function Screen:renderParent() + if self._native and self._native.parent then + self._native.parent:render() + else + dscreen.clear() + end +end + +function Screen:sendInputToParent(...) + if self._native and self._native.parent then + simulateInput(self._native.parent, ...) + end +end + +function Screen:show(below) + if self._native then + error("This screen is already on display") + end + self:onAboutToShow(below) + if not dscreen.show(self, below) then + error('Could not show screen') + end +end + +function Screen:onAboutToShow() +end + +function Screen:onShow() + self:updateLayout() +end + +function Screen:dismiss() + if self._native then + dscreen.dismiss(self) + end +end + +function Screen:onDismiss() +end + +function Screen:onDestroy() +end + +function Screen:onResize(w,h) + self:updateLayout() +end + +function Screen:updateLayout() +end + +------------------------ +-- Framed screen object -- +------------------------ + +-- Plain grey-colored frame. +GREY_FRAME = { + frame_pen = { ch = ' ', fg = COLOR_BLACK, bg = COLOR_GREY }, + title_pen = { fg = COLOR_BLACK, bg = COLOR_WHITE }, + signature_pen = { fg = COLOR_BLACK, bg = COLOR_GREY }, +} + +-- The usual boundary used by the DF screens. Often has fancy pattern in tilesets. +BOUNDARY_FRAME = { + frame_pen = { ch = 0xDB, fg = COLOR_DARKGREY, bg = COLOR_BLACK }, + title_pen = { fg = COLOR_BLACK, bg = COLOR_GREY }, + signature_pen = { fg = COLOR_BLACK, bg = COLOR_DARKGREY }, +} + +GREY_LINE_FRAME = { + frame_pen = { ch = 206, fg = COLOR_GREY, bg = COLOR_BLACK }, + h_frame_pen = { ch = 205, fg = COLOR_GREY, bg = COLOR_BLACK }, + v_frame_pen = { ch = 186, fg = COLOR_GREY, bg = COLOR_BLACK }, + lt_frame_pen = { ch = 201, fg = COLOR_GREY, bg = COLOR_BLACK }, + lb_frame_pen = { ch = 200, fg = COLOR_GREY, bg = COLOR_BLACK }, + rt_frame_pen = { ch = 187, fg = COLOR_GREY, bg = COLOR_BLACK }, + rb_frame_pen = { ch = 188, fg = COLOR_GREY, bg = COLOR_BLACK }, + title_pen = { fg = COLOR_BLACK, bg = COLOR_GREY }, + signature_pen = { fg = COLOR_DARKGREY, bg = COLOR_BLACK }, +} + +function paint_frame(x1,y1,x2,y2,style,title) + local pen = style.frame_pen + dscreen.paintTile(style.lt_frame_pen or pen, x1, y1) + dscreen.paintTile(style.rt_frame_pen or pen, x2, y1) + dscreen.paintTile(style.lb_frame_pen or pen, x1, y2) + dscreen.paintTile(style.rb_frame_pen or pen, x2, y2) + dscreen.fillRect(style.t_frame_pen or style.h_frame_pen or pen,x1+1,y1,x2-1,y1) + dscreen.fillRect(style.b_frame_pen or style.h_frame_pen or pen,x1+1,y2,x2-1,y2) + dscreen.fillRect(style.l_frame_pen or style.v_frame_pen or pen,x1,y1+1,x1,y2-1) + dscreen.fillRect(style.r_frame_pen or style.v_frame_pen or pen,x2,y1+1,x2,y2-1) + dscreen.paintString(style.signature_pen or style.title_pen or pen,x2-7,y2,"DFHack") + + if title then + local x = math.max(0,math.floor((x2-x1-3-#title)/2)) + x1 + local tstr = ' '..title..' ' + if #tstr > x2-x1-1 then + tstr = string.sub(tstr,1,x2-x1-1) + end + dscreen.paintString(style.title_pen or pen, x, y1, tstr) + end +end + +FramedScreen = defclass(FramedScreen, Screen) + +FramedScreen.ATTRS{ + frame_style = BOUNDARY_FRAME, + frame_title = DEFAULT_NIL, + frame_width = DEFAULT_NIL, + frame_height = DEFAULT_NIL, +} + +local function hint_coord(gap,hint) + if hint and hint > 0 then + return math.min(hint,gap) + elseif hint and hint < 0 then + return math.max(0,gap-hint) + else + return math.floor(gap/2) + end +end + +function FramedScreen:getWantedFrameSize() + return self.frame_width, self.frame_height +end + +function FramedScreen:updateFrameSize() + local sw, sh = dscreen.getWindowSize() + local iw, ih = sw-2, sh-2 + local fw, fh = self:getWantedFrameSize() + local width = math.min(fw or iw, iw) + local height = math.min(fh or ih, ih) + local gw, gh = iw-width, ih-height + local x1, y1 = hint_coord(gw,self.frame_xhint), hint_coord(gh,self.frame_yhint) + self.frame_rect = mkdims_wh(x1+1,y1+1,width,height) + self.frame_opaque = (gw == 0 and gh == 0) +end + +function FramedScreen:updateLayout() + self:updateFrameSize() +end + +function FramedScreen:getWindowSize() + local rect = self.frame_rect + return rect.width, rect.height +end + +function FramedScreen:getMousePos() + local rect = self.frame_rect + local x,y = dscreen.getMousePos() + if is_in_rect(rect,x,y) then + return x-rect.x1, y-rect.y1 + end +end + +function FramedScreen:onRender() + local rect = self.frame_rect + local x1,y1,x2,y2 = rect.x1-1, rect.y1-1, rect.x2+1, rect.y2+1 + + if self.frame_opaque then + dscreen.clear() + else + self:renderParent() + dscreen.fillRect(CLEAR_PEN,x1,y1,x2,y2) + end + + paint_frame(x1,y1,x2,y2,self.frame_style,self.frame_title) + + self:onRenderBody(Painter.new(rect)) +end + +function FramedScreen:onRenderBody(dc) +end + +return _ENV diff --git a/library/lua/gui/dialogs.lua b/library/lua/gui/dialogs.lua new file mode 100644 index 00000000..b1a96a55 --- /dev/null +++ b/library/lua/gui/dialogs.lua @@ -0,0 +1,268 @@ +-- Some simple dialog screens + +local _ENV = mkmodule('gui.dialogs') + +local gui = require('gui') +local utils = require('utils') + +local dscreen = dfhack.screen + +MessageBox = defclass(MessageBox, gui.FramedScreen) + +MessageBox.focus_path = 'MessageBox' + +MessageBox.ATTRS{ + frame_style = gui.GREY_LINE_FRAME, + -- new attrs + text = {}, + on_accept = DEFAULT_NIL, + on_cancel = DEFAULT_NIL, + on_close = DEFAULT_NIL, + text_pen = DEFAULT_NIL, +} + +function MessageBox:preinit(info) + if type(info.text) == 'string' then + info.text = utils.split_string(info.text, "\n") + end +end + +function MessageBox:getWantedFrameSize() + local text = self.text + local w = #(self.frame_title or '') + 4 + w = math.max(w, 20) + w = math.max(self.frame_width or w, w) + for _, l in ipairs(text) do + w = math.max(w, #l) + end + local h = #text+1 + if h > 1 then + h = h+1 + end + return w+2, #text+2 +end + +function MessageBox:onRenderBody(dc) + if #self.text > 0 then + dc:newline(1):pen(self.text_pen or COLOR_GREY) + for _, l in ipairs(self.text or {}) do + dc:string(l):newline(1) + end + end + + if self.on_accept then + local x,y = self.frame_rect.x1+1, self.frame_rect.y2+1 + dscreen.paintString({fg=COLOR_LIGHTGREEN},x,y,'ESC') + dscreen.paintString({fg=COLOR_GREY},x+3,y,'/') + dscreen.paintString({fg=COLOR_LIGHTGREEN},x+4,y,'y') + end +end + +function MessageBox:onDestroy() + if self.on_close then + self.on_close() + end +end + +function MessageBox:onInput(keys) + if keys.MENU_CONFIRM then + self:dismiss() + if self.on_accept then + self.on_accept() + end + elseif keys.LEAVESCREEN or (keys.SELECT and not self.on_accept) then + self:dismiss() + if self.on_cancel then + self.on_cancel() + end + end +end + +function showMessage(title, text, tcolor, on_close) + MessageBox{ + frame_title = title, + text = text, + text_pen = tcolor, + on_close = on_close + }:show() +end + +function showYesNoPrompt(title, text, tcolor, on_accept, on_cancel) + MessageBox{ + frame_title = title, + text = text, + text_pen = tcolor, + on_accept = on_accept, + on_cancel = on_cancel, + }:show() +end + +InputBox = defclass(InputBox, MessageBox) + +InputBox.focus_path = 'InputBox' + +InputBox.ATTRS{ + input = '', + input_pen = DEFAULT_NIL, + on_input = DEFAULT_NIL, +} + +function InputBox:preinit(info) + info.on_accept = nil +end + +function InputBox:getWantedFrameSize() + local mw, mh = InputBox.super.getWantedFrameSize(self) + return mw, mh+2 +end + +function InputBox:onRenderBody(dc) + InputBox.super.onRenderBody(self, dc) + + dc:newline(1) + dc:pen(self.input_pen or COLOR_LIGHTCYAN) + dc:fill(1,dc:localY(),dc.width-2,dc:localY()) + + local cursor = '_' + if math.floor(dfhack.getTickCount()/300) % 2 == 0 then + cursor = ' ' + end + local txt = self.input .. cursor + if #txt > dc.width-2 then + txt = string.char(27)..string.sub(txt, #txt-dc.width+4) + end + dc:string(txt) +end + +function InputBox:onInput(keys) + if keys.SELECT then + self:dismiss() + if self.on_input then + self.on_input(self.input) + end + elseif keys.LEAVESCREEN then + self:dismiss() + if self.on_cancel then + self.on_cancel() + end + elseif keys._STRING then + if keys._STRING == 0 then + self.input = string.sub(self.input, 1, #self.input-1) + else + self.input = self.input .. string.char(keys._STRING) + end + end +end + +function showInputPrompt(title, text, tcolor, input, on_input, on_cancel, min_width) + InputBox{ + frame_title = title, + text = text, + text_pen = tcolor, + input = input, + on_input = on_input, + on_cancel = on_cancel, + frame_width = min_width, + }:show() +end + +ListBox = defclass(ListBox, MessageBox) + +ListBox.focus_path = 'ListBox' + +ListBox.ATTRS{ + selection = 0, + choices = {}, + select_pen = DEFAULT_NIL, + on_input = DEFAULT_NIL +} + +function InputBox:preinit(info) + info.on_accept = nil +end + +function ListBox:init(info) + self.page_top = 0 +end + +function ListBox:getWantedFrameSize() + local mw, mh = ListBox.super.getWantedFrameSize(self) + return mw, mh+#self.choices +end + +function ListBox:onRenderBody(dc) + ListBox.super.onRenderBody(self, dc) + + dc:newline(1) + + if self.selection>dc.height-3 then + self.page_top=self.selection-(dc.height-3) + elseif self.selection<self.page_top and self.selection >0 then + self.page_top=self.selection-1 + end + for i,entry in ipairs(self.choices) do + if type(entry)=="table" then + entry=entry[1] + end + if i>self.page_top then + if i == self.selection then + dc:pen(self.select_pen or COLOR_LIGHTCYAN) + else + dc:pen(self.text_pen or COLOR_GREY) + end + dc:string(entry) + dc:newline(1) + end + end +end + +function ListBox:moveCursor(delta) + local newsel=self.selection+delta + if #self.choices ~=0 then + if newsel<1 or newsel>#self.choices then + newsel=newsel % #self.choices + end + end + self.selection=newsel +end + +function ListBox:onInput(keys) + if keys.SELECT then + self:dismiss() + local choice=self.choices[self.selection] + if self.on_input then + self.on_input(self.selection,choice) + end + + if choice and choice[2] then + choice[2](choice,self.selection) -- maybe reverse the arguments? + end + elseif keys.LEAVESCREEN then + self:dismiss() + if self.on_cancel then + self.on_cancel() + end + elseif keys.CURSOR_UP then + self:moveCursor(-1) + elseif keys.CURSOR_DOWN then + self:moveCursor(1) + elseif keys.CURSOR_UP_FAST then + self:moveCursor(-10) + elseif keys.CURSOR_DOWN_FAST then + self:moveCursor(10) + end +end + +function showListPrompt(title, text, tcolor, choices, on_input, on_cancel, min_width) + ListBox{ + frame_title = title, + text = text, + text_pen = tcolor, + choices = choices, + on_input = on_input, + on_cancel = on_cancel, + frame_width = min_width, + }:show() +end + +return _ENV diff --git a/library/lua/gui/dwarfmode.lua b/library/lua/gui/dwarfmode.lua new file mode 100644 index 00000000..ba3cfbe6 --- /dev/null +++ b/library/lua/gui/dwarfmode.lua @@ -0,0 +1,387 @@ +-- Support for messing with the dwarfmode screen + +local _ENV = mkmodule('gui.dwarfmode') + +local gui = require('gui') +local utils = require('utils') + +local dscreen = dfhack.screen + +local g_cursor = df.global.cursor +local g_sel_rect = df.global.selection_rect +local world_map = df.global.world.map + +AREA_MAP_WIDTH = 23 +MENU_WIDTH = 30 + +function getPanelLayout() + local sw, sh = dscreen.getWindowSize() + local view_height = sh-2 + local view_rb = sw-1 + local area_x2 = sw-AREA_MAP_WIDTH-2 + local menu_x2 = sw-MENU_WIDTH-2 + local menu_x1 = area_x2-MENU_WIDTH-1 + local area_pos = df.global.ui_area_map_width + local menu_pos = df.global.ui_menu_width + local rv = {} + + if area_pos < 3 then + rv.area_map = gui.mkdims_xy(area_x2+1,1,view_rb-1,view_height) + view_rb = area_x2 + end + if menu_pos < area_pos or df.global.ui.main.mode ~= 0 then + if menu_pos >= area_pos then + rv.menu_forced = true + menu_pos = area_pos-1 + end + local menu_x = menu_x2 + if menu_pos < 2 then menu_x = menu_x1 end + rv.menu = gui.mkdims_xy(menu_x+1,1,view_rb-1,view_height) + view_rb = menu_x + end + rv.area_pos = area_pos + rv.menu_pos = menu_pos + rv.map = gui.mkdims_xy(1,1,view_rb-1,view_height) + return rv +end + +function getCursorPos() + if g_cursor.x ~= -30000 then + return copyall(g_cursor) + end +end + +function setCursorPos(cursor) + df.global.cursor = cursor +end + +function clearCursorPos() + df.global.cursor = xyz2pos(nil) +end + +function getSelection() + local p1, p2 + if g_sel_rect.start_x ~= -30000 then + p1 = xyz2pos(g_sel_rect.start_x, g_sel_rect.start_y, g_sel_rect.start_z) + end + if g_sel_rect.end_x ~= -30000 then + p2 = xyz2pos(g_sel_rect.end_x, g_sel_rect.end_y, g_sel_rect.end_z) + end + return p1, p2 +end + +function setSelectionStart(pos) + g_sel_rect.start_x = pos.x + g_sel_rect.start_y = pos.y + g_sel_rect.start_z = pos.z +end + +function setSelectionEnd(pos) + g_sel_rect.end_x = pos.x + g_sel_rect.end_y = pos.y + g_sel_rect.end_z = pos.z +end + +function clearSelection() + g_sel_rect.start_x = -30000 + g_sel_rect.start_y = -30000 + g_sel_rect.start_z = -30000 + g_sel_rect.end_x = -30000 + g_sel_rect.end_y = -30000 + g_sel_rect.end_z = -30000 +end + +function getSelectionRange(p1, p2) + local r1 = xyz2pos( + math.min(p1.x, p2.x), math.min(p1.y, p2.y), math.min(p1.z, p2.z) + ) + local r2 = xyz2pos( + math.max(p1.x, p2.x), math.max(p1.y, p2.y), math.max(p1.z, p2.z) + ) + local sz = xyz2pos( + r2.x - r1.x + 1, r2.y - r1.y + 1, r2.z - r1.z + 1 + ) + return r1, sz, r2 +end + +Viewport = defclass(Viewport) + +function Viewport.make(map,x,y,z) + local self = gui.mkdims_wh(x,y,map.width,map.height) + self.z = z + return mkinstance(Viewport, self) +end + +function Viewport.get(layout) + return Viewport.make( + (layout or getPanelLayout()).map, + df.global.window_x, + df.global.window_y, + df.global.window_z + ) +end + +function Viewport:resize(layout) + return Viewport.make( + (layout or getPanelLayout()).map, + self.x1, self.y1, self.z + ) +end + +function Viewport:set() + local vp = self:clip() + df.global.window_x = vp.x1 + df.global.window_y = vp.y1 + df.global.window_z = vp.z + return vp +end + +function Viewport:getPos() + return xyz2pos(self.x1, self.y1, self.z) +end + +function Viewport:getSize() + return xy2pos(self.width, self.height) +end + +function Viewport:clip(x,y,z) + return self:make( + math.max(0, math.min(x or self.x1, world_map.x_count-self.width)), + math.max(0, math.min(y or self.y1, world_map.y_count-self.height)), + math.max(0, math.min(z or self.z, world_map.z_count-1)) + ) +end + +function Viewport:isVisibleXY(target,gap) + gap = gap or 0 + + return math.max(target.x-gap,0) >= self.x1 + and math.min(target.x+gap,world_map.x_count-1) <= self.x2 + and math.max(target.y-gap,0) >= self.y1 + and math.min(target.y+gap,world_map.y_count-1) <= self.y2 +end + +function Viewport:isVisible(target,gap) + gap = gap or 0 + + return self:isVisibleXY(target,gap) and target.z == self.z +end + +function Viewport:tileToScreen(coord) + return xyz2pos(coord.x - self.x1, coord.y - self.y1, coord.z - self.z) +end + +function Viewport:getCenter() + return xyz2pos( + math.floor((self.x2+self.x1)/2), + math.floor((self.y2+self.y1)/2), + self.z + ) +end + +function Viewport:centerOn(target) + return self:clip( + target.x - math.floor(self.width/2), + target.y - math.floor(self.height/2), + target.z + ) +end + +function Viewport:scrollTo(target,gap) + gap = math.max(0, gap or 5) + if gap*2 >= math.min(self.width, self.height) then + gap = math.floor(math.min(self.width, self.height)/2) + end + local x = math.min(self.x1, target.x-gap) + x = math.max(x, target.x+gap+1-self.width) + local y = math.min(self.y1, target.y-gap) + y = math.max(y, target.y+gap+1-self.height) + return self:clip(x, y, target.z) +end + +function Viewport:reveal(target,gap,max_scroll,scroll_gap,scroll_z) + gap = math.max(0, gap or 5) + if self:isVisible(target, gap) then + return self + end + + max_scroll = math.max(0, max_scroll or 5) + if self:isVisibleXY(target, -max_scroll) + and (scroll_z or target.z == self.z) then + return self:scrollTo(target, scroll_gap or gap) + else + return self:centerOn(target) + end +end + +MOVEMENT_KEYS = { + CURSOR_UP = { 0, -1, 0 }, CURSOR_DOWN = { 0, 1, 0 }, + CURSOR_LEFT = { -1, 0, 0 }, CURSOR_RIGHT = { 1, 0, 0 }, + CURSOR_UPLEFT = { -1, -1, 0 }, CURSOR_UPRIGHT = { 1, -1, 0 }, + CURSOR_DOWNLEFT = { -1, 1, 0 }, CURSOR_DOWNRIGHT = { 1, 1, 0 }, + CURSOR_UP_FAST = { 0, -1, 0, true }, CURSOR_DOWN_FAST = { 0, 1, 0, true }, + CURSOR_LEFT_FAST = { -1, 0, 0, true }, CURSOR_RIGHT_FAST = { 1, 0, 0, true }, + CURSOR_UPLEFT_FAST = { -1, -1, 0, true }, CURSOR_UPRIGHT_FAST = { 1, -1, 0, true }, + CURSOR_DOWNLEFT_FAST = { -1, 1, 0, true }, CURSOR_DOWNRIGHT_FAST = { 1, 1, 0, true }, + CURSOR_UP_Z = { 0, 0, 1 }, CURSOR_DOWN_Z = { 0, 0, -1 }, + CURSOR_UP_Z_AUX = { 0, 0, 1 }, CURSOR_DOWN_Z_AUX = { 0, 0, -1 }, +} + +local function get_movement_delta(key, delta, big_step) + local info = MOVEMENT_KEYS[key] + if info then + if info[4] then + delta = big_step + end + + return delta*info[1], delta*info[2], info[3] + end +end + +function Viewport:scrollByKey(key) + local dx, dy, dz = get_movement_delta(key, 10, 20) + if dx then + return self:clip( + self.x1 + dx, + self.y1 + dy, + self.z + dz + ) + else + return self + end +end + +DwarfOverlay = defclass(DwarfOverlay, gui.Screen) + +function DwarfOverlay:updateLayout() + self.df_layout = getPanelLayout() +end + +function DwarfOverlay:getViewport(old_vp) + if old_vp then + return old_vp:resize(self.df_layout) + else + return Viewport.get(self.df_layout) + end +end + +function DwarfOverlay:moveCursorTo(cursor,viewport,gap) + setCursorPos(cursor) + self:zoomViewportTo(cursor,viewport,gap) +end + +function DwarfOverlay:zoomViewportTo(target, viewport, gap) + if gap and self:getViewport():isVisible(target, gap) then + return + end + self:getViewport(viewport):reveal(target, 5, 0, 10):set() +end + +function DwarfOverlay:selectBuilding(building,cursor,viewport,gap) + cursor = cursor or utils.getBuildingCenter(building) + + df.global.world.selected_building = building + self:moveCursorTo(cursor, viewport, gap) +end + +function DwarfOverlay:propagateMoveKeys(keys) + for code,_ in pairs(MOVEMENT_KEYS) do + if keys[code] then + self:sendInputToParent(code) + return code + end + end +end + +function DwarfOverlay:simulateViewScroll(keys, anchor, no_clip_cursor) + local layout = self.df_layout + local cursor = getCursorPos() + + anchor = anchor or cursor + + if anchor and keys.A_MOVE_SAME_SQUARE then + self:getViewport():centerOn(anchor):set() + return 'A_MOVE_SAME_SQUARE' + end + + for code,_ in pairs(MOVEMENT_KEYS) do + if keys[code] then + local vp = self:getViewport():scrollByKey(code) + if (cursor and not no_clip_cursor) or no_clip_cursor == false then + vp = vp:reveal(anchor,4,20,4,true) + end + vp:set() + + return code + end + end +end + +function DwarfOverlay:simulateCursorMovement(keys, anchor) + local layout = self.df_layout + local cursor = getCursorPos() + local cx, cy, cz = pos2xyz(cursor) + + if anchor and keys.A_MOVE_SAME_SQUARE then + setCursorPos(anchor) + self:getViewport():centerOn(anchor):set() + return 'A_MOVE_SAME_SQUARE' + end + + for code,_ in pairs(MOVEMENT_KEYS) do + if keys[code] then + local dx, dy, dz = get_movement_delta(code, 1, 10) + local ncur = xyz2pos(cx+dx, cy+dy, cz+dz) + + if dfhack.maps.isValidTilePos(ncur) then + setCursorPos(ncur) + self:getViewport():reveal(ncur,4,10,6,true):set() + return code + end + end + end +end + +function DwarfOverlay:onAboutToShow(below) + local screen = dfhack.gui.getCurViewscreen() + if below then screen = below.parent end + if not df.viewscreen_dwarfmodest:is_instance(screen) then + error("This screen requires the main dwarfmode view") + end +end + +MenuOverlay = defclass(MenuOverlay, DwarfOverlay) + +function MenuOverlay:updateLayout() + MenuOverlay.super.updateLayout(self) + self.frame_rect = self.df_layout.menu +end + +MenuOverlay.getWindowSize = gui.FramedScreen.getWindowSize +MenuOverlay.getMousePos = gui.FramedScreen.getMousePos + +function MenuOverlay:onAboutToShow(below) + MenuOverlay.super.onAboutToShow(self,below) + + self:updateLayout() + if not self.df_layout.menu then + error("The menu panel of dwarfmode is not visible") + end +end + +function MenuOverlay:onRender() + self:renderParent() + + local menu = self.df_layout.menu + if menu then + -- Paint signature on the frame. + dscreen.paintString( + {fg=COLOR_BLACK,bg=COLOR_DARKGREY}, + menu.x1+1, menu.y2+1, "DFHack" + ) + + self:onRenderBody(gui.Painter.new(menu)) + end +end + +return _ENV diff --git a/library/lua/utils.lua b/library/lua/utils.lua index 38a1e6c4..9fa473ed 100644 --- a/library/lua/utils.lua +++ b/library/lua/utils.lua @@ -361,6 +361,39 @@ function insert_or_update(vector,item,field,cmp) return added,cur,pos end +-- Calls a method with a string temporary +function call_with_string(obj,methodname,...) + return dfhack.with_temp_object( + df.new "string", + function(str,obj,methodname,...) + obj[methodname](obj,str,...) + return str.value + end, + obj,methodname,... + ) +end + +function getBuildingName(building) + return call_with_string(building, 'getName') +end + +function getBuildingCenter(building) + return xyz2pos(building.centerx, building.centery, building.z) +end + +function split_string(self, delimiter) + local result = { } + local from = 1 + local delim_from, delim_to = string.find( self, delimiter, from ) + while delim_from do + table.insert( result, string.sub( self, from , delim_from-1 ) ) + from = delim_to + 1 + delim_from, delim_to = string.find( self, delimiter, from ) + end + table.insert( result, string.sub( self, from ) ) + return result +end + -- Ask a yes-no question function prompt_yes_no(msg,default) local prompt = msg diff --git a/library/modules/Buildings.cpp b/library/modules/Buildings.cpp index 8ec60e55..9e78edd3 100644 --- a/library/modules/Buildings.cpp +++ b/library/modules/Buildings.cpp @@ -49,6 +49,7 @@ using namespace DFHack; #include "df/ui_look_list.h" #include "df/d_init.h" #include "df/item.h" +#include "df/unit.h" #include "df/job.h" #include "df/job_item.h" #include "df/general_ref_building_holderst.h" @@ -177,6 +178,44 @@ bool Buildings::ReadCustomWorkshopTypes(map <uint32_t, string> & btypes) return true; } +bool Buildings::setOwner(df::building *bld, df::unit *unit) +{ + CHECK_NULL_POINTER(bld); + + if (!bld->is_room) + return false; + if (bld->owner == unit) + return true; + + if (bld->owner) + { + auto &blist = bld->owner->owned_buildings; + vector_erase_at(blist, linear_index(blist, bld)); + + if (auto spouse = df::unit::find(bld->owner->relations.spouse_id)) + { + auto &blist = spouse->owned_buildings; + vector_erase_at(blist, linear_index(blist, bld)); + } + } + + bld->owner = unit; + + if (unit) + { + unit->owned_buildings.push_back(bld); + + if (auto spouse = df::unit::find(unit->relations.spouse_id)) + { + auto &blist = spouse->owned_buildings; + if (bld->canUseSpouseRoom() && linear_index(blist, bld) < 0) + blist.push_back(bld); + } + } + + return true; +} + df::building *Buildings::findAtTile(df::coord pos) { auto occ = Maps::getTileOccupancy(pos); @@ -285,7 +324,7 @@ df::building *Buildings::allocInstance(df::coord pos, df::building_type type, in { auto obj = (df::building_trapst*)bld; if (obj->trap_type == trap_type::PressurePlate) - obj->unk_cc = 500; + obj->ready_timeout = 500; break; } default: diff --git a/library/modules/Gui.cpp b/library/modules/Gui.cpp index cd44401f..21156ac0 100644 --- a/library/modules/Gui.cpp +++ b/library/modules/Gui.cpp @@ -42,6 +42,8 @@ using namespace std; using namespace DFHack; #include "modules/Job.h" +#include "modules/Screen.h" +#include "modules/Maps.h" #include "DataDefs.h" #include "df/world.h" @@ -51,8 +53,9 @@ using namespace DFHack; #include "df/viewscreen_dungeon_monsterstatusst.h" #include "df/viewscreen_joblistst.h" #include "df/viewscreen_unitlistst.h" +#include "df/viewscreen_buildinglistst.h" #include "df/viewscreen_itemst.h" -#include "df/viewscreen_layerst.h" +#include "df/viewscreen_layer.h" #include "df/viewscreen_layer_workshop_profilest.h" #include "df/viewscreen_layer_noblelistst.h" #include "df/viewscreen_layer_overall_healthst.h" @@ -80,6 +83,8 @@ using namespace DFHack; #include "df/graphic.h" #include "df/layer_object_listst.h" #include "df/assign_trade_status.h" +#include "df/announcement_flags.h" +#include "df/announcements.h" using namespace df::enums; using df::global::gview; @@ -87,8 +92,11 @@ using df::global::init; using df::global::gps; using df::global::ui; using df::global::world; +using df::global::selection_rect; +using df::global::ui_menu_width; +using df::global::ui_area_map_width; -static df::layer_object_listst *getLayerList(df::viewscreen_layerst *layer, int idx) +static df::layer_object_listst *getLayerList(df::viewscreen_layer *layer, int idx) { return virtual_cast<df::layer_object_listst>(vector_get(layer->layer_objects,idx)); } @@ -166,10 +174,9 @@ DEFINE_GET_FOCUS_STRING_HANDLER(dwarfmode) else if (id == &df::building_trapst::_identity) { auto trap = (df::building_trapst*)selected; - if (trap->trap_type == trap_type::Lever) { - focus += "/Lever"; + focus += "/" + enum_item_key(trap->trap_type); + if (trap->trap_type == trap_type::Lever) jobs = true; - } } else if (ui_building_in_assign && *ui_building_in_assign && ui_building_assign_type && ui_building_assign_units && @@ -182,6 +189,8 @@ DEFINE_GET_FOCUS_STRING_HANDLER(dwarfmode) focus += unit ? "/Unit" : "/None"; } } + else + focus += "/" + enum_item_key(selected->getType()); if (jobs) { @@ -204,7 +213,14 @@ DEFINE_GET_FOCUS_STRING_HANDLER(dwarfmode) if (ui_build_selector->building_type < 0) focus += "/Type"; else if (ui_build_selector->stage != 2) - focus += "/Position"; + { + if (ui_build_selector->stage != 1) + focus += "/NoMaterials"; + else + focus += "/Position"; + + focus += "/" + enum_item_key(ui_build_selector->building_type); + } else { focus += "/Material"; @@ -317,9 +333,9 @@ DEFINE_GET_FOCUS_STRING_HANDLER(layer_military) focus += "/" + enum_item_key(screen->page); int cur_list; - if (list1->bright) cur_list = 0; - else if (list2->bright) cur_list = 1; - else if (list3->bright) cur_list = 2; + if (list1->active) cur_list = 0; + else if (list2->active) cur_list = 1; + else if (list3->active) cur_list = 2; else return; switch (screen->page) @@ -405,7 +421,7 @@ DEFINE_GET_FOCUS_STRING_HANDLER(layer_assigntrade) if (unsigned(list_idx) >= num_lists) return; - if (list1->bright) + if (list1->active) focus += "/Groups"; else focus += "/Items"; @@ -443,10 +459,10 @@ DEFINE_GET_FOCUS_STRING_HANDLER(layer_stockpile) focus += "/On"; - if (list2->bright || list3->bright || screen->list_ids.empty()) { + if (list2->active || list3->active || screen->list_ids.empty()) { focus += "/" + enum_item_key(screen->cur_list); - if (list3->bright) + if (list3->active) focus += (screen->item_names.empty() ? "/None" : "/Item"); } } @@ -466,6 +482,11 @@ std::string Gui::getFocusString(df::viewscreen *top) return name; } + else if (dfhack_viewscreen::is_instance(top)) + { + auto name = static_cast<dfhack_viewscreen*>(top)->getFocusString(); + return name.empty() ? "dfhack" : "dfhack/"+name; + } else { Core &core = Core::getInstance(); @@ -671,6 +692,8 @@ df::job *Gui::getSelectedJob(color_ostream &out, bool quiet) return job; } + else if (auto dfscreen = dfhack_viewscreen::try_cast(top)) + return dfscreen->getSelectedJob(); else return getSelectedWorkshopJob(out, quiet); } @@ -743,7 +766,7 @@ static df::unit *getAnyUnit(df::viewscreen *top) { case df::viewscreen_petst::List: if (!vector_get(screen->is_vermin, screen->cursor)) - return (df::unit*)vector_get(screen->animal, screen->cursor); + return vector_get(screen->animal, screen->cursor).unit; return NULL; case df::viewscreen_petst::SelectTrainer: @@ -761,6 +784,9 @@ static df::unit *getAnyUnit(df::viewscreen *top) return NULL; } + if (auto dfscreen = dfhack_viewscreen::try_cast(top)) + return dfscreen->getSelectedUnit(); + if (!Gui::dwarfmode_hotkey(top)) return NULL; @@ -824,7 +850,7 @@ static df::item *getAnyItem(df::viewscreen *top) { auto list1 = getLayerList(screen, 0); auto list2 = getLayerList(screen, 1); - if (!list1 || !list2 || !list2->bright) + if (!list1 || !list2 || !list2->active) return NULL; int list_idx = vector_get(screen->visible_lists, list1->cursor, (int16_t)-1); @@ -855,6 +881,9 @@ static df::item *getAnyItem(df::viewscreen *top) return NULL; } + if (auto dfscreen = dfhack_viewscreen::try_cast(top)) + return dfscreen->getSelectedItem(); + if (!Gui::dwarfmode_hotkey(top)) return NULL; @@ -913,10 +942,75 @@ df::item *Gui::getSelectedItem(color_ostream &out, bool quiet) return item; } -// +static df::building *getAnyBuilding(df::viewscreen *top) +{ + using namespace ui_sidebar_mode; + using df::global::ui; + using df::global::ui_look_list; + using df::global::ui_look_cursor; + using df::global::world; + using df::global::ui_sidebar_menus; -void Gui::showAnnouncement(std::string message, int color, bool bright) + if (auto screen = strict_virtual_cast<df::viewscreen_buildinglistst>(top)) + return vector_get(screen->buildings, screen->cursor); + + if (auto dfscreen = dfhack_viewscreen::try_cast(top)) + return dfscreen->getSelectedBuilding(); + + if (!Gui::dwarfmode_hotkey(top)) + return NULL; + + switch (ui->main.mode) { + case LookAround: + { + if (!ui_look_list || !ui_look_cursor) + return NULL; + + auto item = vector_get(ui_look_list->items, *ui_look_cursor); + if (item && item->type == df::ui_look_list::T_items::Building) + return item->building; + else + return NULL; + } + case QueryBuilding: + case BuildingItems: + { + return world->selected_building; + } + case Zones: + case ZonesPenInfo: + case ZonesPitInfo: + case ZonesHospitalInfo: + { + if (ui_sidebar_menus) + return ui_sidebar_menus->zone.selected; + return NULL; + } + default: + return NULL; + } +} + +bool Gui::any_building_hotkey(df::viewscreen *top) { + return getAnyBuilding(top) != NULL; +} + +df::building *Gui::getSelectedBuilding(color_ostream &out, bool quiet) +{ + df::building *building = getAnyBuilding(Core::getTopViewscreen()); + + if (!building && !quiet) + out.printerr("No building is selected in the UI.\n"); + + return building; +} + +// + +static void doShowAnnouncement( + df::announcement_type type, df::coord pos, std::string message, int color, bool bright +) { using df::global::world; using df::global::cur_year; using df::global::cur_year_tick; @@ -942,6 +1036,9 @@ void Gui::showAnnouncement(std::string message, int color, bool bright) { df::report *new_rep = new df::report(); + new_rep->type = type; + new_rep->pos = pos; + new_rep->color = color; new_rep->bright = bright; new_rep->year = year; @@ -963,7 +1060,17 @@ void Gui::showAnnouncement(std::string message, int color, bool bright) world->status.announcements.push_back(new_rep); world->status.display_timer = 2000; } +} + +void Gui::showAnnouncement(std::string message, int color, bool bright) +{ + doShowAnnouncement(df::announcement_type(0), df::coord(), message, color, bright); +} +void Gui::showZoomAnnouncement( + df::announcement_type type, df::coord pos, std::string message, int color, bool bright +) { + doShowAnnouncement(type, pos, message, color, bright); } void Gui::showPopupAnnouncement(std::string message, int color, bool bright) @@ -977,17 +1084,163 @@ void Gui::showPopupAnnouncement(std::string message, int color, bool bright) world->status.popups.push_back(popup); } -df::viewscreen * Gui::GetCurrentScreen() +void Gui::showAutoAnnouncement( + df::announcement_type type, df::coord pos, std::string message, int color, bool bright +) { + using df::global::announcements; + + df::announcement_flags flags; + if (is_valid_enum_item(type) && announcements) + flags = announcements->flags[type]; + + doShowAnnouncement(type, pos, message, color, bright); + + if (flags.bits.DO_MEGA || flags.bits.PAUSE || flags.bits.RECENTER) + { + resetDwarfmodeView(flags.bits.DO_MEGA || flags.bits.PAUSE); + + if (flags.bits.RECENTER && pos.isValid()) + revealInDwarfmodeMap(pos, true); + } + + if (flags.bits.DO_MEGA) + showPopupAnnouncement(message, color, bright); +} + +df::viewscreen *Gui::getCurViewscreen(bool skip_dismissed) { df::viewscreen * ws = &gview->view; - while(ws) + while (ws && ws->child) + ws = ws->child; + + if (skip_dismissed) + { + while (ws && Screen::isDismissed(ws) && ws->parent) + ws = ws->parent; + } + + return ws; +} + +df::coord Gui::getViewportPos() +{ + if (!df::global::window_x || !df::global::window_y || !df::global::window_z) + return df::coord(0,0,0); + + return df::coord(*df::global::window_x, *df::global::window_y, *df::global::window_z); +} + +df::coord Gui::getCursorPos() +{ + using df::global::cursor; + if (!cursor) + return df::coord(); + + return df::coord(cursor->x, cursor->y, cursor->z); +} + +Gui::DwarfmodeDims Gui::getDwarfmodeViewDims() +{ + DwarfmodeDims dims; + + auto ws = Screen::getWindowSize(); + dims.y1 = 1; + dims.y2 = ws.y-2; + dims.map_x1 = 1; + dims.map_x2 = ws.x-2; + dims.area_x1 = dims.area_x2 = dims.menu_x1 = dims.menu_x2 = -1; + dims.menu_forced = false; + + int menu_pos = (ui_menu_width ? *ui_menu_width : 2); + int area_pos = (ui_area_map_width ? *ui_area_map_width : 3); + + if (ui && ui->main.mode && menu_pos >= area_pos) + { + dims.menu_forced = true; + menu_pos = area_pos-1; + } + + dims.area_on = (area_pos < 3); + dims.menu_on = (menu_pos < area_pos); + + if (dims.menu_on) { - if(ws->child) - ws = ws->child; + dims.menu_x2 = ws.x - 2; + dims.menu_x1 = dims.menu_x2 - Gui::MENU_WIDTH + 1; + if (menu_pos == 1) + dims.menu_x1 -= Gui::AREA_MAP_WIDTH + 1; + dims.map_x2 = dims.menu_x1 - 2; + } + if (dims.area_on) + { + dims.area_x2 = ws.x-2; + dims.area_x1 = dims.area_x2 - Gui::AREA_MAP_WIDTH + 1; + if (dims.menu_on) + dims.menu_x2 = dims.area_x1 - 2; else - return ws; + dims.map_x2 = dims.area_x1 - 2; + } + + return dims; +} + +void Gui::resetDwarfmodeView(bool pause) +{ + using df::global::cursor; + + if (ui) + { + ui->follow_unit = -1; + ui->follow_item = -1; + ui->main.mode = ui_sidebar_mode::Default; + } + + if (selection_rect) + { + selection_rect->start_x = -30000; + selection_rect->end_x = -30000; + } + + if (cursor) + cursor->x = cursor->y = cursor->z = -30000; + + if (pause && df::global::pause_state) + *df::global::pause_state = true; +} + +bool Gui::revealInDwarfmodeMap(df::coord pos, bool center) +{ + using df::global::window_x; + using df::global::window_y; + using df::global::window_z; + + if (!window_x || !window_y || !window_z || !world) + return false; + if (!Maps::isValidTilePos(pos)) + return false; + + auto dims = getDwarfmodeViewDims(); + int w = dims.map_x2 - dims.map_x1 + 1; + int h = dims.y2 - dims.y1 + 1; + + *window_z = pos.z; + + if (center) + { + *window_x = pos.x - w/2; + *window_y = pos.y - h/2; } - return 0; + else + { + while (*window_x + w < pos.x+5) *window_x += 10; + while (*window_y + h < pos.y+5) *window_y += 10; + while (*window_x + 5 > pos.x) *window_x -= 10; + while (*window_y + 5 > pos.y) *window_y -= 10; + } + + *window_x = std::max(0, std::min(*window_x, world->map.x_count-w)); + *window_y = std::max(0, std::min(*window_y, world->map.y_count-h)); + return true; } bool Gui::getViewCoords (int32_t &x, int32_t &y, int32_t &z) diff --git a/library/modules/Items.cpp b/library/modules/Items.cpp index dc64143c..b8c697a4 100644 --- a/library/modules/Items.cpp +++ b/library/modules/Items.cpp @@ -72,8 +72,11 @@ using namespace std; #include "df/general_ref_contains_itemst.h" #include "df/general_ref_contained_in_itemst.h" #include "df/general_ref_building_holderst.h" +#include "df/general_ref_projectile.h" #include "df/viewscreen_itemst.h" #include "df/vermin.h" +#include "df/proj_itemst.h" +#include "df/proj_list_link.h" #include "df/unit_inventory_item.h" #include "df/body_part_raw.h" @@ -88,6 +91,7 @@ using namespace df::enums; using df::global::world; using df::global::ui; using df::global::ui_selected_unit; +using df::global::proj_next_id; #define ITEMDEF_VECTORS \ ITEM(WEAPON, weapons, itemdef_weaponst) \ @@ -726,6 +730,18 @@ static bool detachItem(MapExtras::MapCache &mc, df::item *item) item->flags.bits.in_inventory = false; return true; } + else if (item->flags.bits.removed) + { + item->flags.bits.removed = false; + + if (item->flags.bits.garbage_collect) + { + item->flags.bits.garbage_collect = false; + item->categorize(true); + } + + return true; + } else return false; } @@ -866,3 +882,64 @@ bool DFHack::Items::moveToInventory( return true; } + +bool Items::remove(MapExtras::MapCache &mc, df::item *item, bool no_uncat) +{ + CHECK_NULL_POINTER(item); + + auto pos = getPosition(item); + + if (!detachItem(mc, item)) + return false; + + if (pos.isValid()) + item->pos = pos; + + if (!no_uncat) + item->uncategorize(); + + item->flags.bits.removed = true; + item->flags.bits.garbage_collect = !no_uncat; + return true; +} + +df::proj_itemst *Items::makeProjectile(MapExtras::MapCache &mc, df::item *item) +{ + CHECK_NULL_POINTER(item); + + if (!world || !proj_next_id) + return NULL; + + auto pos = getPosition(item); + if (!pos.isValid()) + return NULL; + + auto ref = df::allocate<df::general_ref_projectile>(); + if (!ref) + return NULL; + + if (!detachItem(mc, item)) + { + delete ref; + return NULL; + } + + item->pos = pos; + item->flags.bits.in_job = true; + + auto proj = new df::proj_itemst(); + proj->link = new df::proj_list_link(); + proj->link->item = proj; + proj->id = (*proj_next_id)++; + + proj->origin_pos = proj->target_pos = pos; + proj->cur_pos = proj->prev_pos = pos; + proj->item = item; + + ref->projectile_id = proj->id; + item->itemrefs.push_back(ref); + + linked_list_append(&world->proj_list, proj->link); + + return proj; +} diff --git a/library/modules/Job.cpp b/library/modules/Job.cpp index 1207c97b..b74a4b73 100644 --- a/library/modules/Job.cpp +++ b/library/modules/Job.cpp @@ -181,7 +181,7 @@ void DFHack::Job::printItemDetails(color_ostream &out, df::job_item *item, int i out << " reaction class: " << item->reaction_class << endl; if (!item->has_material_reaction_product.empty()) out << " reaction product: " << item->has_material_reaction_product << endl; - if (item->has_tool_use >= 0) + if (item->has_tool_use >= (df::tool_uses)0) out << " tool use: " << ENUM_KEY_STR(tool_uses, item->has_tool_use) << endl; } @@ -189,7 +189,7 @@ void DFHack::Job::printJobDetails(color_ostream &out, df::job *job) { CHECK_NULL_POINTER(job); - out.color(job->flags.bits.suspend ? Console::COLOR_DARKGREY : Console::COLOR_GREY); + out.color(job->flags.bits.suspend ? COLOR_DARKGREY : COLOR_GREY); out << "Job " << job->id << ": " << ENUM_KEY_STR(job_type,job->job_type); if (job->flags.whole) out << " (" << bitfield_to_string(job->flags) << ")"; diff --git a/library/modules/Maps.cpp b/library/modules/Maps.cpp index 3ab156d7..f1f40f19 100644 --- a/library/modules/Maps.cpp +++ b/library/modules/Maps.cpp @@ -57,6 +57,8 @@ using namespace std; #include "df/builtin_mats.h" #include "df/block_square_event_grassst.h" #include "df/z_level_flags.h" +#include "df/region_map_entry.h" +#include "df/flow_info.h" using namespace DFHack; using namespace df::enums; @@ -137,17 +139,57 @@ df::map_block *Maps::getBlock (int32_t blockx, int32_t blocky, int32_t blockz) return world->map.block_index[blockx][blocky][blockz]; } -df::map_block *Maps::getTileBlock (int32_t x, int32_t y, int32_t z) +bool Maps::isValidTilePos(int32_t x, int32_t y, int32_t z) { if (!IsValid()) - return NULL; + return false; if ((x < 0) || (y < 0) || (z < 0)) - return NULL; + return false; if ((x >= world->map.x_count) || (y >= world->map.y_count) || (z >= world->map.z_count)) + return false; + return true; +} + +df::map_block *Maps::getTileBlock (int32_t x, int32_t y, int32_t z) +{ + if (!isValidTilePos(x,y,z)) return NULL; return world->map.block_index[x >> 4][y >> 4][z]; } +df::map_block *Maps::ensureTileBlock (int32_t x, int32_t y, int32_t z) +{ + if (!isValidTilePos(x,y,z)) + return NULL; + + auto column = world->map.block_index[x >> 4][y >> 4]; + auto &slot = column[z]; + if (slot) + return slot; + + // Find another block below + int z2 = z; + while (z2 >= 0 && !column[z2]) z2--; + if (z2 < 0) + return NULL; + + slot = new df::map_block(); + slot->region_pos = column[z2]->region_pos; + slot->map_pos = column[z2]->map_pos; + slot->map_pos.z = z; + + // Assume sky + df::tile_designation dsgn(0); + dsgn.bits.light = true; + dsgn.bits.outside = true; + + for (int tx = 0; tx < 16; tx++) + for (int ty = 0; ty < 16; ty++) + slot->designation[tx][ty] = dsgn; + + return slot; +} + df::tiletype *Maps::getTileType(int32_t x, int32_t y, int32_t z) { df::map_block *block = getTileBlock(x,y,z); @@ -166,7 +208,7 @@ df::tile_occupancy *Maps::getTileOccupancy(int32_t x, int32_t y, int32_t z) return block ? &block->occupancy[x&15][y&15] : NULL; } -df::world_data::T_region_map *Maps::getRegionBiome(df::coord2d rgn_pos) +df::region_map_entry *Maps::getRegionBiome(df::coord2d rgn_pos) { auto data = world->world_data; if (!data) @@ -203,6 +245,26 @@ void Maps::enableBlockUpdates(df::map_block *blk, bool flow, bool temperature) } } +df::flow_info *Maps::spawnFlow(df::coord pos, df::flow_type type, int mat_type, int mat_index, int density) +{ + using df::global::flows; + + auto block = getTileBlock(pos); + if (!flows || !block) + return NULL; + + auto flow = new df::flow_info(); + flow->type = type; + flow->mat_type = mat_type; + flow->mat_index = mat_index; + flow->density = std::min(100, density); + flow->pos = pos; + + block->flows.push_back(flow); + flows->push_back(flow); + return flow; +} + df::feature_init *Maps::getGlobalInitFeature(int32_t index) { auto data = world->world_data; @@ -245,7 +307,7 @@ df::feature_init *Maps::getLocalInitFeature(df::coord2d rgn_pos, int32_t index) df::coord2d bigregion = rgn_pos / 16; // bigregion is 16x16 regions. for each bigregion in X dimension: - auto fptr = data->unk_204[bigregion.x][bigregion.y].features; + auto fptr = data->feature_map[bigregion.x][bigregion.y].features; if (!fptr) return NULL; @@ -484,8 +546,14 @@ MapExtras::Block::Block(MapCache *parent, DFCoord _bcoord) : parent(parent) valid = false; bcoord = _bcoord; block = Maps::getBlock(bcoord); - item_counts = NULL; tags = NULL; + + init(); +} + +void MapExtras::Block::init() +{ + item_counts = NULL; tiles = NULL; basemats = NULL; @@ -508,6 +576,23 @@ MapExtras::Block::Block(MapCache *parent, DFCoord _bcoord) : parent(parent) } } +bool MapExtras::Block::Allocate() +{ + if (block) + return true; + + block = Maps::ensureTileBlock(bcoord.x*16, bcoord.y*16, bcoord.z); + if (!block) + return false; + + delete item_counts; + delete tiles; + delete basemats; + init(); + + return true; +} + MapExtras::Block::~Block() { delete[] item_counts; diff --git a/library/modules/Materials.cpp b/library/modules/Materials.cpp index 50cf21a9..db9c9c7d 100644 --- a/library/modules/Materials.cpp +++ b/library/modules/Materials.cpp @@ -283,6 +283,19 @@ bool MaterialInfo::findCreature(const std::string &token, const std::string &sub return decode(-1); } +bool MaterialInfo::findProduct(df::material *material, const std::string &name) +{ + if (!material || name.empty()) + return decode(-1); + + auto &pids = material->reaction_product.id; + for (size_t i = 0; i < pids.size(); i++) + if ((*pids[i]) == name) + return decode(material->reaction_product.material, i); + + return decode(-1); +} + std::string MaterialInfo::getToken() { if (isNone()) diff --git a/library/modules/Screen.cpp b/library/modules/Screen.cpp new file mode 100644 index 00000000..8057d17a --- /dev/null +++ b/library/modules/Screen.cpp @@ -0,0 +1,680 @@ +/* +https://github.com/peterix/dfhack +Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + + +#include "Internal.h" + +#include <string> +#include <vector> +#include <map> +using namespace std; + +#include "modules/Screen.h" +#include "MemAccess.h" +#include "VersionInfo.h" +#include "Types.h" +#include "Error.h" +#include "ModuleFactory.h" +#include "Core.h" +#include "PluginManager.h" +#include "LuaTools.h" + +#include "MiscUtils.h" + +using namespace DFHack; + +#include "DataDefs.h" +#include "df/init.h" +#include "df/texture_handler.h" +#include "df/tile_page.h" +#include "df/interfacest.h" +#include "df/enabler.h" +#include "df/unit.h" +#include "df/item.h" +#include "df/job.h" +#include "df/building.h" + +using namespace df::enums; +using df::global::init; +using df::global::gps; +using df::global::texture; +using df::global::gview; +using df::global::enabler; + +using Screen::Pen; + +/* + * Screen painting API. + */ + +df::coord2d Screen::getMousePos() +{ + if (!gps || (enabler && !enabler->tracking_on)) + return df::coord2d(-1, -1); + + return df::coord2d(gps->mouse_x, gps->mouse_y); +} + +df::coord2d Screen::getWindowSize() +{ + if (!gps) return df::coord2d(80, 25); + + return df::coord2d(gps->dimx, gps->dimy); +} + +bool Screen::inGraphicsMode() +{ + return init && init->display.flag.is_set(init_display_flags::USE_GRAPHICS); +} + +static void doSetTile(const Pen &pen, int index) +{ + auto screen = gps->screen + index*4; + screen[0] = uint8_t(pen.ch); + screen[1] = uint8_t(pen.fg) & 15; + screen[2] = uint8_t(pen.bg) & 15; + screen[3] = uint8_t(pen.bold) & 1; + gps->screentexpos[index] = pen.tile; + gps->screentexpos_addcolor[index] = (pen.tile_mode == Screen::Pen::CharColor); + gps->screentexpos_grayscale[index] = (pen.tile_mode == Screen::Pen::TileColor); + gps->screentexpos_cf[index] = pen.tile_fg; + gps->screentexpos_cbr[index] = pen.tile_bg; +} + +bool Screen::paintTile(const Pen &pen, int x, int y) +{ + if (!gps || !pen.valid()) return false; + + int dimx = gps->dimx, dimy = gps->dimy; + if (x < 0 || x >= dimx || y < 0 || y >= dimy) return false; + + doSetTile(pen, x*dimy + y); + return true; +} + +Pen Screen::readTile(int x, int y) +{ + if (!gps) return Pen(0,0,0,-1); + + int dimx = gps->dimx, dimy = gps->dimy; + if (x < 0 || x >= dimx || y < 0 || y >= dimy) + return Pen(0,0,0,-1); + + int index = x*dimy + y; + auto screen = gps->screen + index*4; + if (screen[3] & 0x80) + return Pen(0,0,0,-1); + + Pen pen( + screen[0], screen[1], screen[2], screen[3]?true:false, + gps->screentexpos[index] + ); + + if (pen.tile) + { + if (gps->screentexpos_grayscale[index]) + { + pen.tile_mode = Screen::Pen::TileColor; + pen.tile_fg = gps->screentexpos_cf[index]; + pen.tile_bg = gps->screentexpos_cbr[index]; + } + else if (gps->screentexpos_addcolor[index]) + { + pen.tile_mode = Screen::Pen::CharColor; + } + } + + return pen; +} + +bool Screen::paintString(const Pen &pen, int x, int y, const std::string &text) +{ + if (!gps || y < 0 || y >= gps->dimy) return false; + + Pen tmp(pen); + bool ok = false; + + for (size_t i = -std::min(0,x); i < text.size(); i++) + { + if (x + i >= size_t(gps->dimx)) + break; + + tmp.ch = text[i]; + tmp.tile = (pen.tile ? pen.tile + uint8_t(text[i]) : 0); + paintTile(tmp, x+i, y); + ok = true; + } + + return ok; +} + +bool Screen::fillRect(const Pen &pen, int x1, int y1, int x2, int y2) +{ + if (!gps || !pen.valid()) return false; + + if (x1 < 0) x1 = 0; + if (y1 < 0) y1 = 0; + if (x2 >= gps->dimx) x2 = gps->dimx-1; + if (y2 >= gps->dimy) y2 = gps->dimy-1; + if (x1 > x2 || y1 > y2) return false; + + for (int x = x1; x <= x2; x++) + { + int index = x*gps->dimy; + + for (int y = y1; y <= y2; y++) + doSetTile(pen, index+y); + } + + return true; +} + +bool Screen::drawBorder(const std::string &title) +{ + if (!gps) return false; + + int dimx = gps->dimx, dimy = gps->dimy; + Pen border(0xDB, 8); + Pen text(0, 0, 7); + Pen signature(0, 0, 8); + + for (int x = 0; x < dimx; x++) + { + doSetTile(border, x * dimy + 0); + doSetTile(border, x * dimy + dimy - 1); + } + for (int y = 0; y < dimy; y++) + { + doSetTile(border, 0 * dimy + y); + doSetTile(border, (dimx - 1) * dimy + y); + } + + paintString(signature, dimx-8, dimy-1, "DFHack"); + + return paintString(text, (dimx - title.length()) / 2, 0, title); +} + +bool Screen::clear() +{ + if (!gps) return false; + + return fillRect(Pen(' ',0,0,false), 0, 0, gps->dimx-1, gps->dimy-1); +} + +bool Screen::invalidate() +{ + if (!enabler) return false; + + enabler->flag.bits.render = true; + return true; +} + +bool Screen::findGraphicsTile(const std::string &pagename, int x, int y, int *ptile, int *pgs) +{ + if (!gps || !texture || x < 0 || y < 0) return false; + + for (size_t i = 0; i < texture->page.size(); i++) + { + auto page = texture->page[i]; + if (!page->loaded || page->token != pagename) continue; + + if (x >= page->page_dim_x || y >= page->page_dim_y) + break; + int idx = y*page->page_dim_x + x; + if (size_t(idx) >= page->texpos.size()) + break; + + if (ptile) *ptile = page->texpos[idx]; + if (pgs) *pgs = page->texpos_gs[idx]; + return true; + } + + return false; +} + +bool Screen::show(df::viewscreen *screen, df::viewscreen *before) +{ + CHECK_NULL_POINTER(screen); + CHECK_INVALID_ARGUMENT(!screen->parent && !screen->child); + + if (!gps || !gview) return false; + + df::viewscreen *parent = &gview->view; + while (parent && parent->child != before) + parent = parent->child; + + if (!parent) return false; + + gps->force_full_display_count += 2; + + screen->child = parent->child; + screen->parent = parent; + parent->child = screen; + if (screen->child) + screen->child->parent = screen; + + if (dfhack_viewscreen::is_instance(screen)) + static_cast<dfhack_viewscreen*>(screen)->onShow(); + + return true; +} + +void Screen::dismiss(df::viewscreen *screen, bool to_first) +{ + CHECK_NULL_POINTER(screen); + + if (screen->breakdown_level != interface_breakdown_types::NONE) + return; + + if (to_first) + screen->breakdown_level = interface_breakdown_types::TOFIRST; + else + screen->breakdown_level = interface_breakdown_types::STOPSCREEN; + + if (dfhack_viewscreen::is_instance(screen)) + static_cast<dfhack_viewscreen*>(screen)->onDismiss(); +} + +bool Screen::isDismissed(df::viewscreen *screen) +{ + CHECK_NULL_POINTER(screen); + + return screen->breakdown_level != interface_breakdown_types::NONE; +} + +/* + * Base DFHack viewscreen. + */ + +static std::set<df::viewscreen*> dfhack_screens; + +dfhack_viewscreen::dfhack_viewscreen() : text_input_mode(false) +{ + dfhack_screens.insert(this); + + last_size = Screen::getWindowSize(); +} + +dfhack_viewscreen::~dfhack_viewscreen() +{ + dfhack_screens.erase(this); +} + +bool dfhack_viewscreen::is_instance(df::viewscreen *screen) +{ + return dfhack_screens.count(screen) != 0; +} + +dfhack_viewscreen *dfhack_viewscreen::try_cast(df::viewscreen *screen) +{ + return is_instance(screen) ? static_cast<dfhack_viewscreen*>(screen) : NULL; +} + +void dfhack_viewscreen::check_resize() +{ + auto size = Screen::getWindowSize(); + + if (size != last_size) + { + last_size = size; + resize(size.x, size.y); + } +} + +void dfhack_viewscreen::logic() +{ + check_resize(); + + // Various stuff works poorly unless always repainting + Screen::invalidate(); +} + +void dfhack_viewscreen::render() +{ + check_resize(); +} + +bool dfhack_viewscreen::key_conflict(df::interface_key key) +{ + if (key == interface_key::OPTIONS) + return true; + + if (text_input_mode) + { + if (key == interface_key::HELP || key == interface_key::MOVIES) + return true; + } + + return false; +} + +/* + * Lua-backed viewscreen. + */ + +static int DFHACK_LUA_VS_TOKEN = 0; + +df::viewscreen *dfhack_lua_viewscreen::get_pointer(lua_State *L, int idx, bool make) +{ + df::viewscreen *screen; + + if (lua_istable(L, idx)) + { + if (!Lua::IsCoreContext(L)) + luaL_error(L, "only the core context can create lua screens"); + + lua_rawgetp(L, idx, &DFHACK_LUA_VS_TOKEN); + + if (!lua_isnil(L, -1)) + { + if (make) + luaL_error(L, "this screen is already on display"); + + screen = (df::viewscreen*)lua_touserdata(L, -1); + } + else + { + if (!make) + luaL_error(L, "this screen is not on display"); + + screen = new dfhack_lua_viewscreen(L, idx); + } + + lua_pop(L, 1); + } + else + screen = Lua::CheckDFObject<df::viewscreen>(L, idx); + + return screen; +} + +bool dfhack_lua_viewscreen::safe_call_lua(int (*pf)(lua_State *), int args, int rvs) +{ + CoreSuspendClaimer suspend; + color_ostream_proxy out(Core::getInstance().getConsole()); + + auto L = Lua::Core::State; + lua_pushcfunction(L, pf); + if (args > 0) lua_insert(L, -args-1); + lua_pushlightuserdata(L, this); + if (args > 0) lua_insert(L, -args-1); + + return Lua::Core::SafeCall(out, args+1, rvs); +} + +dfhack_lua_viewscreen *dfhack_lua_viewscreen::get_self(lua_State *L) +{ + auto self = (dfhack_lua_viewscreen*)lua_touserdata(L, 1); + lua_rawgetp(L, LUA_REGISTRYINDEX, self); + if (!lua_istable(L, -1)) return NULL; + return self; +} + +int dfhack_lua_viewscreen::do_destroy(lua_State *L) +{ + auto self = get_self(L); + if (!self) return 0; + + lua_pushnil(L); + lua_rawsetp(L, LUA_REGISTRYINDEX, self); + + lua_pushnil(L); + lua_rawsetp(L, -2, &DFHACK_LUA_VS_TOKEN); + lua_pushnil(L); + lua_setfield(L, -2, "_native"); + + lua_getfield(L, -1, "onDestroy"); + if (lua_isnil(L, -1)) + return 0; + + lua_pushvalue(L, -2); + lua_call(L, 1, 0); + return 0; +} + +void dfhack_lua_viewscreen::update_focus(lua_State *L, int idx) +{ + lua_getfield(L, idx, "text_input_mode"); + text_input_mode = lua_toboolean(L, -1); + lua_pop(L, 1); + + lua_getfield(L, idx, "focus_path"); + auto str = lua_tostring(L, -1); + if (!str) str = ""; + focus = str; + lua_pop(L, 1); + + if (focus.empty()) + focus = "lua"; + else + focus = "lua/"+focus; +} + +int dfhack_lua_viewscreen::do_render(lua_State *L) +{ + auto self = get_self(L); + if (!self) return 0; + + lua_getfield(L, -1, "onRender"); + + if (lua_isnil(L, -1)) + { + Screen::clear(); + return 0; + } + + lua_pushvalue(L, -2); + lua_call(L, 1, 0); + return 0; +} + +int dfhack_lua_viewscreen::do_notify(lua_State *L) +{ + int args = lua_gettop(L); + + auto self = get_self(L); + if (!self) return 0; + + lua_pushvalue(L, 2); + lua_gettable(L, -2); + if (lua_isnil(L, -1)) + return 0; + + // self field args table fn -> table fn table args + lua_replace(L, 1); + lua_copy(L, -1, 2); + lua_insert(L, 1); + lua_call(L, args-1, 1); + + self->update_focus(L, 1); + return 1; +} + +int dfhack_lua_viewscreen::do_input(lua_State *L) +{ + auto self = get_self(L); + if (!self) return 0; + + auto keys = (std::set<df::interface_key>*)lua_touserdata(L, 2); + + lua_getfield(L, -1, "onInput"); + + if (lua_isnil(L, -1)) + { + if (keys->count(interface_key::LEAVESCREEN)) + Screen::dismiss(self); + + return 0; + } + + lua_pushvalue(L, -2); + + lua_createtable(L, 0, keys->size()+3); + + for (auto it = keys->begin(); it != keys->end(); ++it) + { + auto key = *it; + + if (auto name = enum_item_raw_key(key)) + lua_pushstring(L, name); + else + lua_pushinteger(L, key); + + lua_pushboolean(L, true); + lua_rawset(L, -3); + + if (key >= interface_key::STRING_A000 && + key <= interface_key::STRING_A255) + { + lua_pushinteger(L, key - interface_key::STRING_A000); + lua_setfield(L, -2, "_STRING"); + } + } + + if (enabler && enabler->tracking_on) + { + if (enabler->mouse_lbut) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "_MOUSE_L"); + } + if (enabler->mouse_rbut) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "_MOUSE_R"); + } + } + + lua_call(L, 2, 0); + self->update_focus(L, -1); + return 0; +} + +dfhack_lua_viewscreen::dfhack_lua_viewscreen(lua_State *L, int table_idx) +{ + assert(Lua::IsCoreContext(L)); + + Lua::PushDFObject(L, (df::viewscreen*)this); + lua_setfield(L, table_idx, "_native"); + lua_pushlightuserdata(L, this); + lua_rawsetp(L, table_idx, &DFHACK_LUA_VS_TOKEN); + + lua_pushvalue(L, table_idx); + lua_rawsetp(L, LUA_REGISTRYINDEX, this); + + update_focus(L, table_idx); +} + +dfhack_lua_viewscreen::~dfhack_lua_viewscreen() +{ + safe_call_lua(do_destroy, 0, 0); +} + +void dfhack_lua_viewscreen::render() +{ + if (Screen::isDismissed(this)) return; + + dfhack_viewscreen::render(); + + safe_call_lua(do_render, 0, 0); +} + +void dfhack_lua_viewscreen::logic() +{ + if (Screen::isDismissed(this)) return; + + dfhack_viewscreen::logic(); + + lua_pushstring(Lua::Core::State, "onIdle"); + safe_call_lua(do_notify, 1, 0); +} + +void dfhack_lua_viewscreen::help() +{ + if (Screen::isDismissed(this)) return; + + lua_pushstring(Lua::Core::State, "onHelp"); + safe_call_lua(do_notify, 1, 0); +} + +void dfhack_lua_viewscreen::resize(int w, int h) +{ + if (Screen::isDismissed(this)) return; + + auto L = Lua::Core::State; + lua_pushstring(L, "onResize"); + lua_pushinteger(L, w); + lua_pushinteger(L, h); + safe_call_lua(do_notify, 3, 0); +} + +void dfhack_lua_viewscreen::feed(std::set<df::interface_key> *keys) +{ + if (Screen::isDismissed(this)) return; + + lua_pushlightuserdata(Lua::Core::State, keys); + safe_call_lua(do_input, 1, 0); +} + +void dfhack_lua_viewscreen::onShow() +{ + lua_pushstring(Lua::Core::State, "onShow"); + safe_call_lua(do_notify, 1, 0); +} + +void dfhack_lua_viewscreen::onDismiss() +{ + lua_pushstring(Lua::Core::State, "onDismiss"); + safe_call_lua(do_notify, 1, 0); +} + +df::unit *dfhack_lua_viewscreen::getSelectedUnit() +{ + Lua::StackUnwinder frame(Lua::Core::State); + lua_pushstring(Lua::Core::State, "onGetSelectedUnit"); + safe_call_lua(do_notify, 1, 1); + return Lua::GetDFObject<df::unit>(Lua::Core::State, -1); +} + +df::item *dfhack_lua_viewscreen::getSelectedItem() +{ + Lua::StackUnwinder frame(Lua::Core::State); + lua_pushstring(Lua::Core::State, "onGetSelectedItem"); + safe_call_lua(do_notify, 1, 1); + return Lua::GetDFObject<df::item>(Lua::Core::State, -1); +} + +df::job *dfhack_lua_viewscreen::getSelectedJob() +{ + Lua::StackUnwinder frame(Lua::Core::State); + lua_pushstring(Lua::Core::State, "onGetSelectedJob"); + safe_call_lua(do_notify, 1, 1); + return Lua::GetDFObject<df::job>(Lua::Core::State, -1); +} + +df::building *dfhack_lua_viewscreen::getSelectedBuilding() +{ + Lua::StackUnwinder frame(Lua::Core::State); + lua_pushstring(Lua::Core::State, "onGetSelectedBuilding"); + safe_call_lua(do_notify, 1, 1); + return Lua::GetDFObject<df::building>(Lua::Core::State, -1); +} diff --git a/library/modules/Units.cpp b/library/modules/Units.cpp index ee383cc0..01b7b50f 100644 --- a/library/modules/Units.cpp +++ b/library/modules/Units.cpp @@ -63,11 +63,15 @@ using namespace std; #include "df/burrow.h" #include "df/creature_raw.h" #include "df/caste_raw.h" +#include "df/game_mode.h" +#include "df/unit_misc_trait.h" +#include "df/unit_skill.h" using namespace DFHack; using namespace df::enums; using df::global::world; using df::global::ui; +using df::global::gamemode; bool Units::isValid() { @@ -613,6 +617,58 @@ df::nemesis_record *Units::getNemesis(df::unit *unit) return NULL; } + +bool Units::isHidingCurse(df::unit *unit) +{ + if (!unit->job.hunt_target) + { + auto identity = Units::getIdentity(unit); + if (identity && identity->unk_4c == 0) + return true; + } + + return false; +} + +int Units::getPhysicalAttrValue(df::unit *unit, df::physical_attribute_type attr) +{ + auto &aobj = unit->body.physical_attrs[attr]; + int value = std::max(0, aobj.value - aobj.soft_demotion); + + if (auto mod = unit->curse.attr_change) + { + int mvalue = (value * mod->phys_att_perc[attr] / 100) + mod->phys_att_add[attr]; + + if (isHidingCurse(unit)) + value = std::min(value, mvalue); + else + value = mvalue; + } + + return std::max(0, value); +} + +int Units::getMentalAttrValue(df::unit *unit, df::mental_attribute_type attr) +{ + auto soul = unit->status.current_soul; + if (!soul) return 0; + + auto &aobj = soul->mental_attrs[attr]; + int value = std::max(0, aobj.value - aobj.soft_demotion); + + if (auto mod = unit->curse.attr_change) + { + int mvalue = (value * mod->ment_att_perc[attr] / 100) + mod->ment_att_add[attr]; + + if (isHidingCurse(unit)) + value = std::min(value, mvalue); + else + value = mvalue; + } + + return std::max(0, value); +} + static bool casteFlagSet(int race, int caste, df::caste_raw_flags flag) { auto creature = df::creature_raw::find(race); @@ -626,8 +682,9 @@ static bool casteFlagSet(int race, int caste, df::caste_raw_flags flag) return craw->flags.is_set(flag); } -static bool isCrazed(df::unit *unit) +bool Units::isCrazed(df::unit *unit) { + CHECK_NULL_POINTER(unit); if (unit->flags3.bits.scuttle) return false; if (unit->curse.rem_tags1.bits.CRAZED) @@ -637,13 +694,64 @@ static bool isCrazed(df::unit *unit) return casteFlagSet(unit->race, unit->caste, caste_raw_flags::CRAZED); } -static bool isOpposedToLife(df::unit *unit) +bool Units::isOpposedToLife(df::unit *unit) { + CHECK_NULL_POINTER(unit); if (unit->curse.rem_tags1.bits.OPPOSED_TO_LIFE) return false; if (unit->curse.add_tags1.bits.OPPOSED_TO_LIFE) return true; - return casteFlagSet(unit->race, unit->caste, caste_raw_flags::CANNOT_UNDEAD); + return casteFlagSet(unit->race, unit->caste, caste_raw_flags::OPPOSED_TO_LIFE); +} + +bool Units::hasExtravision(df::unit *unit) +{ + CHECK_NULL_POINTER(unit); + if (unit->curse.rem_tags1.bits.EXTRAVISION) + return false; + if (unit->curse.add_tags1.bits.EXTRAVISION) + return true; + return casteFlagSet(unit->race, unit->caste, caste_raw_flags::EXTRAVISION); +} + +bool Units::isBloodsucker(df::unit *unit) +{ + CHECK_NULL_POINTER(unit); + if (unit->curse.rem_tags1.bits.BLOODSUCKER) + return false; + if (unit->curse.add_tags1.bits.BLOODSUCKER) + return true; + return casteFlagSet(unit->race, unit->caste, caste_raw_flags::BLOODSUCKER); +} + +bool Units::isMischievous(df::unit *unit) +{ + CHECK_NULL_POINTER(unit); + if (unit->curse.rem_tags1.bits.MISCHIEVOUS) + return false; + if (unit->curse.add_tags1.bits.MISCHIEVOUS) + return true; + return casteFlagSet(unit->race, unit->caste, caste_raw_flags::MISCHIEVOUS); +} + +df::unit_misc_trait *Units::getMiscTrait(df::unit *unit, df::misc_trait_type type, bool create) +{ + CHECK_NULL_POINTER(unit); + + auto &vec = unit->status.misc_traits; + for (size_t i = 0; i < vec.size(); i++) + if (vec[i]->id == type) + return vec[i]; + + if (create) + { + auto obj = new df::unit_misc_trait(); + obj->id = type; + vec.push_back(obj); + return obj; + } + + return NULL; } bool DFHack::Units::isDead(df::unit *unit) @@ -753,6 +861,371 @@ double DFHack::Units::getAge(df::unit *unit, bool true_age) return cur_time - birth_time; } +inline void adjust_skill_rating(int &rating, bool is_adventure, int value, int dwarf3_4, int dwarf1_2, int adv9_10, int adv3_4, int adv1_2) +{ + if (is_adventure) + { + if (value >= adv1_2) rating >>= 1; + else if (value >= adv3_4) rating = rating*3/4; + else if (value >= adv9_10) rating = rating*9/10; + } + else + { + if (value >= dwarf1_2) rating >>= 1; + else if (value >= dwarf3_4) rating = rating*3/4; + } +} + +int Units::getEffectiveSkill(df::unit *unit, df::job_skill skill_id) +{ + CHECK_NULL_POINTER(unit); + + /* + * This is 100% reverse-engineered from DF code. + */ + + if (!unit->status.current_soul) + return 0; + + // Retrieve skill from unit soul: + + df::enum_field<df::job_skill,int16_t> key(skill_id); + auto skill = binsearch_in_vector(unit->status.current_soul->skills, &df::unit_skill::id, key); + + int rating = 0; + if (skill) + rating = std::max(0, int(skill->rating) - skill->rusty); + + // Apply special states + + if (unit->counters.soldier_mood == df::unit::T_counters::None) + { + if (unit->counters.nausea > 0) rating >>= 1; + if (unit->counters.winded > 0) rating >>= 1; + if (unit->counters.stunned > 0) rating >>= 1; + if (unit->counters.dizziness > 0) rating >>= 1; + if (unit->counters2.fever > 0) rating >>= 1; + } + + if (unit->counters.soldier_mood != df::unit::T_counters::MartialTrance) + { + if (!unit->flags3.bits.ghostly && !unit->flags3.bits.scuttle && + !unit->flags2.bits.vision_good && !unit->flags2.bits.vision_damaged && + !hasExtravision(unit)) + { + rating >>= 2; + } + if (unit->counters.pain >= 100 && unit->mood == -1) + { + rating >>= 1; + } + if (unit->counters2.exhaustion >= 2000) + { + rating = rating*3/4; + if (unit->counters2.exhaustion >= 4000) + { + rating = rating*3/4; + if (unit->counters2.exhaustion >= 6000) + rating = rating*3/4; + } + } + } + + // Hunger etc timers + + bool is_adventure = (gamemode && *gamemode == game_mode::ADVENTURE); + + if (!unit->flags3.bits.scuttle && isBloodsucker(unit)) + { + using namespace df::enums::misc_trait_type; + + if (auto trait = getMiscTrait(unit, TimeSinceSuckedBlood)) + { + adjust_skill_rating( + rating, is_adventure, trait->value, + 302400, 403200, // dwf 3/4; 1/2 + 1209600, 1209600, 2419200 // adv 9/10; 3/4; 1/2 + ); + } + } + + adjust_skill_rating( + rating, is_adventure, unit->counters2.thirst_timer, + 50000, 50000, 115200, 172800, 345600 + ); + adjust_skill_rating( + rating, is_adventure, unit->counters2.hunger_timer, + 75000, 75000, 172800, 1209600, 2592000 + ); + if (is_adventure && unit->counters2.sleepiness_timer >= 846000) + rating >>= 2; + else + adjust_skill_rating( + rating, is_adventure, unit->counters2.sleepiness_timer, + 150000, 150000, 172800, 259200, 345600 + ); + + return rating; +} + +inline void adjust_speed_rating(int &rating, bool is_adventure, int value, int dwarf100, int dwarf200, int adv50, int adv75, int adv100, int adv200) +{ + if (is_adventure) + { + if (value >= adv200) rating += 200; + else if (value >= adv100) rating += 100; + else if (value >= adv75) rating += 75; + else if (value >= adv50) rating += 50; + } + else + { + if (value >= dwarf200) rating += 200; + else if (value >= dwarf100) rating += 100; + } +} + +static int calcInventoryWeight(df::unit *unit) +{ + int armor_skill = Units::getEffectiveSkill(unit, job_skill::ARMOR); + int armor_mul = 15 - std::min(15, armor_skill); + + int inv_weight = 0, inv_weight_fraction = 0; + + for (size_t i = 0; i < unit->inventory.size(); i++) + { + auto item = unit->inventory[i]->item; + if (!item->flags.bits.weight_computed) + continue; + + int wval = item->weight; + int wfval = item->weight_fraction; + auto mode = unit->inventory[i]->mode; + + if ((mode == df::unit_inventory_item::Worn || + mode == df::unit_inventory_item::WrappedAround) && + item->isArmor() && armor_skill > 1) + { + wval = wval * armor_mul / 16; + wfval = wfval * armor_mul / 16; + } + + inv_weight += wval; + inv_weight_fraction += wfval; + } + + return inv_weight*100 + inv_weight_fraction/10000; +} + +int Units::computeMovementSpeed(df::unit *unit) +{ + using namespace df::enums::physical_attribute_type; + + /* + * Pure reverse-engineered computation of unit _slowness_, + * i.e. number of ticks to move * 100. + */ + + // Base speed + + auto creature = df::creature_raw::find(unit->race); + if (!creature) + return 0; + + auto craw = vector_get(creature->caste, unit->caste); + if (!craw) + return 0; + + int speed = craw->misc.speed; + + if (unit->flags3.bits.ghostly) + return speed; + + // Curse multiplier + + if (unit->curse.speed_mul_percent != 100) + { + speed *= 100; + if (unit->curse.speed_mul_percent != 0) + speed /= unit->curse.speed_mul_percent; + } + + speed += unit->curse.speed_add; + + // Swimming + + auto cur_liquid = unit->status2.liquid_type.bits.liquid_type; + bool in_magma = (cur_liquid == tile_liquid::Magma); + + if (unit->flags2.bits.swimming) + { + speed = craw->misc.swim_speed; + if (in_magma) + speed *= 2; + + if (craw->flags.is_set(caste_raw_flags::SWIMS_LEARNED)) + { + int skill = Units::getEffectiveSkill(unit, job_skill::SWIMMING); + + // Originally a switch: + if (skill > 1) + speed = speed * std::max(6, 21-skill) / 20; + } + } + else + { + int delta = 150*unit->status2.liquid_depth; + if (in_magma) + delta *= 2; + speed += delta; + } + + // General counters and flags + + if (unit->profession == profession::BABY) + speed += 3000; + + if (unit->flags3.bits.unk15) + speed /= 20; + + if (unit->counters2.exhaustion >= 2000) + { + speed += 200; + if (unit->counters2.exhaustion >= 4000) + { + speed += 200; + if (unit->counters2.exhaustion >= 6000) + speed += 200; + } + } + + if (unit->flags2.bits.gutted) speed += 2000; + + if (unit->counters.soldier_mood == df::unit::T_counters::None) + { + if (unit->counters.nausea > 0) speed += 1000; + if (unit->counters.winded > 0) speed += 1000; + if (unit->counters.stunned > 0) speed += 1000; + if (unit->counters.dizziness > 0) speed += 1000; + if (unit->counters2.fever > 0) speed += 1000; + } + + if (unit->counters.soldier_mood != df::unit::T_counters::MartialTrance) + { + if (unit->counters.pain >= 100 && unit->mood == -1) + speed += 1000; + } + + // Hunger etc timers + + bool is_adventure = (gamemode && *gamemode == game_mode::ADVENTURE); + + if (!unit->flags3.bits.scuttle && Units::isBloodsucker(unit)) + { + using namespace df::enums::misc_trait_type; + + if (auto trait = Units::getMiscTrait(unit, TimeSinceSuckedBlood)) + { + adjust_speed_rating( + speed, is_adventure, trait->value, + 302400, 403200, // dwf 100; 200 + 1209600, 1209600, 1209600, 2419200 // adv 50; 75; 100; 200 + ); + } + } + + adjust_speed_rating( + speed, is_adventure, unit->counters2.thirst_timer, + 50000, 0x7fffffff, 172800, 172800, 172800, 345600 + ); + adjust_speed_rating( + speed, is_adventure, unit->counters2.hunger_timer, + 75000, 0x7fffffff, 1209600, 1209600, 1209600, 2592000 + ); + adjust_speed_rating( + speed, is_adventure, unit->counters2.sleepiness_timer, + 57600, 150000, 172800, 259200, 345600, 864000 + ); + + // Activity state + + if (unit->relations.draggee_id != -1) speed += 1000; + + if (unit->flags1.bits.on_ground) + speed += 2000; + else if (unit->flags3.bits.on_crutch) + { + int skill = Units::getEffectiveSkill(unit, job_skill::CRUTCH_WALK); + speed += 2000 - 100*std::min(20, skill); + } + + if (unit->flags1.bits.hidden_in_ambush && !Units::isMischievous(unit)) + { + int skill = Units::getEffectiveSkill(unit, job_skill::SNEAK); + speed += 2000 - 100*std::min(20, skill); + } + + if (unsigned(unit->counters2.paralysis-1) <= 98) + speed += unit->counters2.paralysis*10; + if (unsigned(unit->counters.webbed-1) <= 8) + speed += unit->counters.webbed*100; + + // Muscle weight vs vascular tissue (?) + + auto &attr_tissue = unit->body.physical_attr_tissues; + int muscle = attr_tissue[STRENGTH]; + int blood = attr_tissue[AGILITY]; + speed = std::max(speed*3/4, std::min(speed*3/2, int(int64_t(speed)*muscle/blood))); + + // Attributes + + int strength_attr = Units::getPhysicalAttrValue(unit, STRENGTH); + int agility_attr = Units::getPhysicalAttrValue(unit, AGILITY); + + int total_attr = std::max(200, std::min(3800, strength_attr + agility_attr)); + speed = ((total_attr-200)*(speed/2) + (3800-total_attr)*(speed*3/2))/3600; + + // Stance + + if (!unit->flags1.bits.on_ground && unit->status2.able_stand > 2) + { + // WTF + int as = unit->status2.able_stand; + int x = (as-1) - (as>>1); + int y = as - unit->status2.able_stand_impair; + if (unit->flags3.bits.on_crutch) y--; + y = y * 500 / x; + if (y > 0) speed += y; + } + + // Mood + + if (unit->mood == mood_type::Melancholy) speed += 8000; + + // Inventory encumberance + + int total_weight = calcInventoryWeight(unit); + int free_weight = std::max(1, muscle/10 + strength_attr*3); + + if (free_weight < total_weight) + { + int delta = (total_weight - free_weight)/10 + 1; + if (!is_adventure) + delta = std::min(5000, delta); + speed += delta; + } + + // skipped: unknown loop on inventory items that amounts to 0 change + + if (is_adventure) + { + auto player = vector_get(world->units.active, 0); + if (player && player->id == unit->relations.group_leader_id) + speed = std::min(speed, computeMovementSpeed(player)); + } + + return std::min(10000, std::max(0, speed)); +} + static bool noble_pos_compare(const Units::NoblePosition &a, const Units::NoblePosition &b) { if (a.position->precedence < b.position->precedence) @@ -838,7 +1311,7 @@ std::string DFHack::Units::getCasteProfessionName(int race, int casteid, df::pro { std::string prof, race_prefix; - if (pid < 0 || !is_valid_enum_item(pid)) + if (pid < (df::profession)0 || !is_valid_enum_item(pid)) return ""; bool use_race_prefix = (race >= 0 && race != df::global::ui->race_id); @@ -948,3 +1421,40 @@ std::string DFHack::Units::getCasteProfessionName(int race, int casteid, df::pro return Translation::capitalize(prof, true); } + +int8_t DFHack::Units::getProfessionColor(df::unit *unit, bool ignore_noble) +{ + std::vector<NoblePosition> np; + + if (!ignore_noble && getNoblePositions(&np, unit)) + { + if (np[0].position->flags.is_set(entity_position_flags::COLOR)) + return np[0].position->color[0] + np[0].position->color[2] * 8; + } + + return getCasteProfessionColor(unit->race, unit->caste, unit->profession); +} + +int8_t DFHack::Units::getCasteProfessionColor(int race, int casteid, df::profession pid) +{ + // make sure it's an actual profession + if (pid < 0 || !is_valid_enum_item(pid)) + return 3; + + // If it's not a Peasant, it's hardcoded + if (pid != profession::STANDARD) + return ENUM_ATTR(profession, color, pid); + + if (auto creature = df::creature_raw::find(race)) + { + if (auto caste = vector_get(creature->caste, casteid)) + { + if (caste->flags.is_set(caste_raw_flags::CASTE_COLOR)) + return caste->caste_color[0] + caste->caste_color[2] * 8; + } + return creature->color[0] + creature->color[2] * 8; + } + + // default to dwarven peasant color + return 3; +} diff --git a/library/modules/World.cpp b/library/modules/World.cpp index 393e7cbf..67b8c123 100644 --- a/library/modules/World.cpp +++ b/library/modules/World.cpp @@ -285,13 +285,13 @@ PersistentDataItem World::GetPersistentData(int entry_id) PersistentDataItem World::GetPersistentData(const std::string &key, bool *added) { - *added = false; + if (added) *added = false; PersistentDataItem rv = GetPersistentData(key); if (!rv.isValid()) { - *added = true; + if (added) *added = true; rv = AddPersistentData(key); } @@ -300,6 +300,8 @@ PersistentDataItem World::GetPersistentData(const std::string &key, bool *added) void World::GetPersistentData(std::vector<PersistentDataItem> *vec, const std::string &key, bool prefix) { + vec->clear(); + if (!BuildPersistentCache()) return; @@ -343,8 +345,10 @@ bool World::DeletePersistentData(const PersistentDataItem &item) auto eqrange = d->persistent_index.equal_range(item.key_value); - for (auto it = eqrange.first; it != eqrange.second; ++it) + for (auto it2 = eqrange.first; it2 != eqrange.second; ) { + auto it = it2; ++it2; + if (it->second != -item.id) continue; diff --git a/library/modules/kitchen.cpp b/library/modules/kitchen.cpp index 4300d63d..aa235780 100644 --- a/library/modules/kitchen.cpp +++ b/library/modules/kitchen.cpp @@ -114,7 +114,7 @@ void Kitchen::fillWatchMap(std::map<t_materialIndex, unsigned int>& watchMap) watchMap.clear(); for(std::size_t i = 0; i < size(); ++i) { - if(ui->kitchen.item_subtypes[i] == limitType && ui->kitchen.item_subtypes[i] == limitSubtype && ui->kitchen.exc_types[i] == limitExclusion) + if(ui->kitchen.item_subtypes[i] == (short)limitType && ui->kitchen.item_subtypes[i] == (short)limitSubtype && ui->kitchen.exc_types[i] == limitExclusion) { watchMap[ui->kitchen.mat_indices[i]] = (unsigned int) ui->kitchen.mat_types[i]; } diff --git a/library/xml b/library/xml -Subproject 9f91e74767b4d583b580d46e16143216ba62ae6 +Subproject 9773484b8430417ad488423ddeae3832f011ce9 diff --git a/package/darwin/dfhack-run b/package/darwin/dfhack-run index 865c8bd2..cc69db96 100755 --- a/package/darwin/dfhack-run +++ b/package/darwin/dfhack-run @@ -3,7 +3,6 @@ DF_DIR=$(dirname "$0") cd "${DF_DIR}" -export DYLD_LIBRARY_PATH=${PWD}/hack:${PWD}/libs -export DYLD_FRAMEWORK_PATH=${PWD}/hack${PWD}/libs +export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"./stonesense/deplibs":"./hack" exec hack/dfhack-run "$@" diff --git a/package/darwin/fix-libs.sh b/package/darwin/fix-libs.sh new file mode 100755 index 00000000..cff98b6a --- /dev/null +++ b/package/darwin/fix-libs.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +BUILD_DIR=`pwd` + +echo "Fixing library dependencies in $BUILD_DIR/library" + +install_name_tool -change $BUILD_DIR/library/libdfhack.1.0.0.dylib @executable_path/hack/libdfhack.1.0.0.dylib library/libdfhack.1.0.0.dylib +install_name_tool -change $BUILD_DIR/library/libdfhack-client.dylib @executable_path/hack/libdfhack-client.dylib library/libdfhack-client.dylib +install_name_tool -change $BUILD_DIR/library/libdfhack-client.dylib @executable_path/hack/libdfhack-client.dylib library/dfhack-run +install_name_tool -change $BUILD_DIR/depends/protobuf/libprotobuf-lite.dylib @executable_path/hack/libprotobuf-lite.dylib library/libdfhack.1.0.0.dylib +install_name_tool -change $BUILD_DIR/depends/protobuf/libprotobuf-lite.dylib @executable_path/hack/libprotobuf-lite.dylib library/libdfhack-client.dylib +install_name_tool -change $BUILD_DIR/depends/protobuf/libprotobuf-lite.dylib @executable_path/hack/libprotobuf-lite.dylib library/dfhack-run +install_name_tool -change $BUILD_DIR/depends/lua/liblua.dylib @executable_path/hack/liblua.dylib library/libdfhack.1.0.0.dylib +install_name_tool -change @executable_path/../Frameworks/SDL.framework/Versions/A/SDL @executable_path/libs/SDL.framework/Versions/A/SDL library/libdfhack.1.0.0.dylib +install_name_tool -change /usr/local/lib/libstdc++.6.dylib @executable_path/libs/libstdc++.6.dylib library/libdfhack.1.0.0.dylib +install_name_tool -change /opt/local/lib/i386/libstdc++.6.dylib @executable_path/libs/libstdc++.6.dylib library/libdfhack.1.0.0.dylib +install_name_tool -change /opt/local/lib/i386/libstdc++.6.dylib @executable_path/libs/libstdc++.6.dylib library/libdfhack-client.dylib +install_name_tool -change /opt/local/lib/i386/libstdc++.6.dylib @executable_path/libs/libstdc++.6.dylib library/dfhack-run +install_name_tool -change /opt/local/lib/i386/libgcc_s.1.dylib @executable_path/libs/libgcc_s.1.dylib library/libdfhack.1.0.0.dylib +install_name_tool -change /opt/local/lib/i386/libgcc_s.1.dylib @executable_path/libs/libgcc_s.1.dylib library/libdfhack-client.dylib +install_name_tool -change /opt/local/lib/i386/libgcc_s.1.dylib @executable_path/libs/libgcc_s.1.dylib library/dfhack-run
\ No newline at end of file diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index 55a7c250..91d57821 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -44,6 +44,12 @@ endif() install(DIRECTORY lua/ DESTINATION ${DFHACK_LUA_DESTINATION}/plugins FILES_MATCHING PATTERN "*.lua") +install(DIRECTORY raw/ + DESTINATION ${DFHACK_DATA_DESTINATION}/raw + FILES_MATCHING PATTERN "*.txt") +install(DIRECTORY raw/ + DESTINATION ${DFHACK_DATA_DESTINATION}/raw + FILES_MATCHING PATTERN "*.diff") # Protobuf FILE(GLOB PROJECT_PROTOS ${CMAKE_CURRENT_SOURCE_DIR}/proto/*.proto) @@ -81,7 +87,7 @@ if (BUILD_SUPPORTED) DFHACK_PLUGIN(weather weather.cpp) DFHACK_PLUGIN(colonies colonies.cpp) DFHACK_PLUGIN(mode mode.cpp) - DFHACK_PLUGIN(liquids liquids.cpp Brushes.h) + DFHACK_PLUGIN(liquids liquids.cpp Brushes.h LINK_LIBRARIES lua) DFHACK_PLUGIN(tiletypes tiletypes.cpp Brushes.h) DFHACK_PLUGIN(tubefill tubefill.cpp) DFHACK_PLUGIN(autodump autodump.cpp) @@ -92,7 +98,7 @@ if (BUILD_SUPPORTED) DFHACK_PLUGIN(seedwatch seedwatch.cpp) DFHACK_PLUGIN(initflags initflags.cpp) DFHACK_PLUGIN(stockpiles stockpiles.cpp) - DFHACK_PLUGIN(rename rename.cpp PROTOBUFS rename) + DFHACK_PLUGIN(rename rename.cpp LINK_LIBRARIES lua PROTOBUFS rename) DFHACK_PLUGIN(jobutils jobutils.cpp) DFHACK_PLUGIN(workflow workflow.cpp) DFHACK_PLUGIN(showmood showmood.cpp) @@ -110,9 +116,14 @@ if (BUILD_SUPPORTED) DFHACK_PLUGIN(catsplosion catsplosion.cpp) DFHACK_PLUGIN(regrass regrass.cpp) DFHACK_PLUGIN(forceequip forceequip.cpp) + DFHACK_PLUGIN(manipulator manipulator.cpp) # this one exports functions to lua DFHACK_PLUGIN(burrows burrows.cpp LINK_LIBRARIES lua) DFHACK_PLUGIN(sort sort.cpp LINK_LIBRARIES lua) + DFHACK_PLUGIN(steam-engine steam-engine.cpp) + DFHACK_PLUGIN(power-meter power-meter.cpp LINK_LIBRARIES lua) + DFHACK_PLUGIN(siege-engine siege-engine.cpp LINK_LIBRARIES lua) + DFHACK_PLUGIN(add-spatter add-spatter.cpp) # not yet. busy with other crud again... #DFHACK_PLUGIN(versionosd versionosd.cpp) DFHACK_PLUGIN(misery misery.cpp) diff --git a/plugins/add-spatter.cpp b/plugins/add-spatter.cpp new file mode 100644 index 00000000..425ffe9d --- /dev/null +++ b/plugins/add-spatter.cpp @@ -0,0 +1,433 @@ +#include "Core.h" +#include <Console.h> +#include <Export.h> +#include <PluginManager.h> +#include <modules/Gui.h> +#include <modules/Screen.h> +#include <modules/Maps.h> +#include <modules/Job.h> +#include <modules/Items.h> +#include <modules/Units.h> +#include <TileTypes.h> +#include <vector> +#include <cstdio> +#include <stack> +#include <string> +#include <cmath> +#include <string.h> + +#include <VTableInterpose.h> +#include "df/item_liquid_miscst.h" +#include "df/item_constructed.h" +#include "df/builtin_mats.h" +#include "df/world.h" +#include "df/job.h" +#include "df/job_item.h" +#include "df/job_item_ref.h" +#include "df/ui.h" +#include "df/report.h" +#include "df/reaction.h" +#include "df/reaction_reagent_itemst.h" +#include "df/reaction_product_item_improvementst.h" +#include "df/reaction_product_improvement_flags.h" +#include "df/matter_state.h" +#include "df/contaminant.h" + +#include "MiscUtils.h" + +using std::vector; +using std::string; +using std::stack; +using namespace DFHack; +using namespace df::enums; + +using df::global::gps; +using df::global::world; +using df::global::ui; + +typedef df::reaction_product_item_improvementst improvement_product; + +DFHACK_PLUGIN("add-spatter"); + +struct ReagentSource { + int idx; + df::reaction_reagent *reagent; + + ReagentSource() : idx(-1), reagent(NULL) {} +}; + +struct MaterialSource : ReagentSource { + bool product; + std::string product_name; + + int mat_type, mat_index; + + MaterialSource() : product(false), mat_type(-1), mat_index(-1) {} +}; + +struct ProductInfo { + df::reaction *react; + improvement_product *product; + + ReagentSource object; + MaterialSource material; + + bool isValid() { + return object.reagent && (material.mat_type >= 0 || material.reagent); + } +}; + +struct ReactionInfo { + df::reaction *react; + + std::vector<ProductInfo> products; +}; + +static std::map<std::string, ReactionInfo> reactions; +static std::map<df::reaction_product*, ProductInfo*> products; + +static ReactionInfo *find_reaction(const std::string &name) +{ + auto it = reactions.find(name); + return (it != reactions.end()) ? &it->second : NULL; +} + +static bool is_add_spatter(const std::string &name) +{ + return name.size() > 12 && memcmp(name.data(), "SPATTER_ADD_", 12) == 0; +} + +static void find_material(int *type, int *index, df::item *input, MaterialSource &mat) +{ + if (input && mat.reagent) + { + MaterialInfo info(input); + + if (mat.product) + { + if (!info.findProduct(info, mat.product_name)) + { + color_ostream_proxy out(Core::getInstance().getConsole()); + out.printerr("Cannot find product '%s'\n", mat.product_name.c_str()); + } + } + + *type = info.type; + *index = info.index; + } + else + { + *type = mat.mat_type; + *index = mat.mat_index; + } +} + +static int has_contaminant(df::item_actual *item, int type, int index) +{ + auto cont = item->contaminants; + if (!cont) + return 0; + + int size = 0; + + for (size_t i = 0; i < cont->size(); i++) + { + auto cur = (*cont)[i]; + if (cur->mat_type == type && cur->mat_index == index) + size += cur->size; + } + + return size; +} + +/* + * Hooks + */ + +typedef std::map<int, std::vector<df::item*> > item_table; + +static void index_items(item_table &table, df::job *job, ReactionInfo *info) +{ + for (int i = job->items.size()-1; i >= 0; i--) + { + auto iref = job->items[i]; + if (iref->job_item_idx < 0) continue; + auto iitem = job->job_items[iref->job_item_idx]; + + if (iitem->contains.empty()) + { + table[iitem->reagent_index].push_back(iref->item); + } + else + { + std::vector<df::item*> contents; + Items::getContainedItems(iref->item, &contents); + + for (int j = contents.size()-1; j >= 0; j--) + { + for (int k = iitem->contains.size()-1; k >= 0; k--) + { + int ridx = iitem->contains[k]; + auto reag = info->react->reagents[ridx]; + + if (reag->matchesChild(contents[j], info->react, iitem->reaction_id)) + table[ridx].push_back(contents[j]); + } + } + } + } +} + +df::item* find_item(ReagentSource &info, item_table &table) +{ + if (!info.reagent) + return NULL; + if (table[info.idx].empty()) + return NULL; + return table[info.idx].back(); +} + +struct item_hook : df::item_constructed { + typedef df::item_constructed interpose_base; + + DEFINE_VMETHOD_INTERPOSE(bool, isImprovable, (df::job *job, int16_t mat_type, int32_t mat_index)) + { + ReactionInfo *info; + + if (job && job->job_type == job_type::CustomReaction && + (info = find_reaction(job->reaction_name)) != NULL) + { + if (!contaminants || contaminants->empty()) + return true; + + item_table table; + index_items(table, job, info); + + for (size_t i = 0; i < info->products.size(); i++) + { + auto &product = info->products[i]; + + int mattype, matindex; + auto material = find_item(info->products[i].material, table); + + find_material(&mattype, &matindex, material, product.material); + + if (mattype < 0 || has_contaminant(this, mattype, matindex) >= 50) + return false; + } + + return true; + } + + return INTERPOSE_NEXT(isImprovable)(job, mat_type, mat_index); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(item_hook, isImprovable); + +df::item* find_item( + ReagentSource &info, + std::vector<df::reaction_reagent*> *in_reag, + std::vector<df::item*> *in_items +) { + if (!info.reagent) + return NULL; + for (int i = in_items->size(); i >= 0; i--) + if ((*in_reag)[i] == info.reagent) + return (*in_items)[i]; + return NULL; +} + +struct product_hook : improvement_product { + typedef improvement_product interpose_base; + + DEFINE_VMETHOD_INTERPOSE( + void, produce, + (df::unit *unit, std::vector<df::item*> *out_items, + std::vector<df::reaction_reagent*> *in_reag, + std::vector<df::item*> *in_items, + int32_t quantity, int16_t skill, + df::historical_entity *entity, df::world_site *site) + ) { + if (auto product = products[this]) + { + auto object = find_item(product->object, in_reag, in_items); + auto material = find_item(product->material, in_reag, in_items); + + if (object && (material || !product->material.reagent)) + { + using namespace df::enums::improvement_type; + + int mattype, matindex; + find_material(&mattype, &matindex, material, product->material); + + df::matter_state state = matter_state::Liquid; + + switch (improvement_type) + { + case COVERED: + if (flags.is_set(reaction_product_improvement_flags::GLAZED)) + state = matter_state::Solid; + break; + case BANDS: + state = matter_state::Paste; + break; + case SPIKES: + state = matter_state::Powder; + break; + default: + break; + } + + int rating = unit ? Units::getEffectiveSkill(unit, df::job_skill(skill)) : 0; + int size = int(probability*(1.0f + 0.06f*rating)); // +90% at legendary + + object->addContaminant( + mattype, matindex, state, + object->getTemperature(), + size, -1, + 0x8000 // not washed by water, and 'clean items' safe. + ); + } + + return; + } + + INTERPOSE_NEXT(produce)(unit, out_items, in_reag, in_items, quantity, skill, entity, site); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(product_hook, produce); + +/* + * Scan raws for matching reactions. + */ + +static void find_reagent( + color_ostream &out, ReagentSource &info, df::reaction *react, std::string name +) { + for (size_t i = 0; i < react->reagents.size(); i++) + { + if (react->reagents[i]->code != name) + continue; + + info.idx = i; + info.reagent = react->reagents[i]; + return; + } + + out.printerr("Invalid reagent name '%s' in '%s'\n", name.c_str(), react->code.c_str()); +} + +static void parse_product( + color_ostream &out, ProductInfo &info, df::reaction *react, improvement_product *prod +) { + using namespace df::enums::reaction_product_improvement_flags; + + info.react = react; + info.product = prod; + + find_reagent(out, info.object, react, prod->target_reagent); + + auto ritem = strict_virtual_cast<df::reaction_reagent_itemst>(info.object.reagent); + if (ritem) + ritem->flags1.bits.improvable = true; + + info.material.mat_type = prod->mat_type; + info.material.mat_index = prod->mat_index; + + if (prod->flags.is_set(GET_MATERIAL_PRODUCT)) + { + find_reagent(out, info.material, react, prod->get_material.reagent_code); + + info.material.product = true; + info.material.product_name = prod->get_material.product_code; + } + else if (prod->flags.is_set(GET_MATERIAL_SAME)) + { + find_reagent(out, info.material, react, prod->get_material.reagent_code); + } +} + +static bool find_reactions(color_ostream &out) +{ + reactions.clear(); + products.clear(); + + auto &rlist = world->raws.reactions; + + for (size_t i = 0; i < rlist.size(); i++) + { + if (!is_add_spatter(rlist[i]->code)) + continue; + + reactions[rlist[i]->code].react = rlist[i]; + } + + for (auto it = reactions.begin(); it != reactions.end(); ++it) + { + auto &prod = it->second.react->products; + auto &out_prod = it->second.products; + + for (size_t i = 0; i < prod.size(); i++) + { + auto itprod = strict_virtual_cast<improvement_product>(prod[i]); + if (!itprod) continue; + + out_prod.push_back(ProductInfo()); + parse_product(out, out_prod.back(), it->second.react, itprod); + } + + for (size_t i = 0; i < prod.size(); i++) + { + if (out_prod[i].isValid()) + products[out_prod[i].product] = &out_prod[i]; + } + } + + return !products.empty(); +} + +static void enable_hooks(bool enable) +{ + INTERPOSE_HOOK(item_hook, isImprovable).apply(enable); + INTERPOSE_HOOK(product_hook, produce).apply(enable); +} + +DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event) +{ + switch (event) { + case SC_WORLD_LOADED: + if (find_reactions(out)) + { + out.print("Detected spatter add reactions - enabling plugin.\n"); + enable_hooks(true); + } + else + enable_hooks(false); + break; + case SC_WORLD_UNLOADED: + enable_hooks(false); + reactions.clear(); + products.clear(); + break; + default: + break; + } + + return CR_OK; +} + +DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands) +{ + if (Core::getInstance().isWorldLoaded()) + plugin_onstatechange(out, SC_WORLD_LOADED); + + return CR_OK; +} + +DFhackCExport command_result plugin_shutdown ( color_ostream &out ) +{ + enable_hooks(false); + return CR_OK; +} diff --git a/plugins/advtools.cpp b/plugins/advtools.cpp index 4823d362..d674f552 100644 --- a/plugins/advtools.cpp +++ b/plugins/advtools.cpp @@ -462,7 +462,7 @@ void joinCounts(std::map<df::coord, int> &counts) static void printCompanionHeader(color_ostream &out, size_t i, df::unit *unit) { - out.color(Console::COLOR_GREY); + out.color(COLOR_GREY); if (i < 28) out << char('a'+i); diff --git a/plugins/autolabor.cpp b/plugins/autolabor.cpp index c3a2b313..c39b126c 100644 --- a/plugins/autolabor.cpp +++ b/plugins/autolabor.cpp @@ -9,6 +9,7 @@ #include <vector> #include <algorithm> +#include "modules/Units.h" #include "modules/World.h" // DF data structure definition headers @@ -358,11 +359,11 @@ static const dwarf_state dwarf_states[] = { OTHER /* DrinkBlood */, OTHER /* ReportCrime */, OTHER /* ExecuteCriminal */, - BUSY /* TrainAnimal */, - BUSY /* CarveTrack */, - BUSY /* PushTrackVehicle */, - BUSY /* PlaceTrackVehicle */, - BUSY /* StoreItemInVehicle */ + BUSY /* TrainAnimal */, + BUSY /* CarveTrack */, + BUSY /* PushTrackVehicle */, + BUSY /* PlaceTrackVehicle */, + BUSY /* StoreItemInVehicle */ }; struct labor_info @@ -397,108 +398,108 @@ static int hauler_pct = 33; static std::vector<struct labor_info> labor_infos; static const struct labor_default default_labor_infos[] = { - /* MINE */ {AUTOMATIC, true, 2, 200, 0}, - /* HAUL_STONE */ {HAULERS, false, 1, 200, 0}, - /* HAUL_WOOD */ {HAULERS, false, 1, 200, 0}, - /* HAUL_BODY */ {HAULERS, false, 1, 200, 0}, - /* HAUL_FOOD */ {HAULERS, false, 1, 200, 0}, - /* HAUL_REFUSE */ {HAULERS, false, 1, 200, 0}, - /* HAUL_ITEM */ {HAULERS, false, 1, 200, 0}, - /* HAUL_FURNITURE */ {HAULERS, false, 1, 200, 0}, - /* HAUL_ANIMAL */ {HAULERS, false, 1, 200, 0}, - /* CLEAN */ {HAULERS, false, 1, 200, 0}, - /* CUTWOOD */ {AUTOMATIC, true, 1, 200, 0}, - /* CARPENTER */ {AUTOMATIC, false, 1, 200, 0}, - /* DETAIL */ {AUTOMATIC, false, 1, 200, 0}, - /* MASON */ {AUTOMATIC, false, 1, 200, 0}, - /* ARCHITECT */ {AUTOMATIC, false, 1, 200, 0}, - /* ANIMALTRAIN */ {AUTOMATIC, false, 1, 200, 0}, - /* ANIMALCARE */ {AUTOMATIC, false, 1, 200, 0}, - /* DIAGNOSE */ {AUTOMATIC, false, 1, 200, 0}, - /* SURGERY */ {AUTOMATIC, false, 1, 200, 0}, - /* BONE_SETTING */ {AUTOMATIC, false, 1, 200, 0}, - /* SUTURING */ {AUTOMATIC, false, 1, 200, 0}, - /* DRESSING_WOUNDS */ {AUTOMATIC, false, 1, 200, 0}, - /* FEED_WATER_CIVILIANS */ {AUTOMATIC, false, 200, 200, 0}, - /* RECOVER_WOUNDED */ {HAULERS, false, 1, 200, 0}, - /* BUTCHER */ {AUTOMATIC, false, 1, 200, 0}, - /* TRAPPER */ {AUTOMATIC, false, 1, 200, 0}, - /* DISSECT_VERMIN */ {AUTOMATIC, false, 1, 200, 0}, - /* LEATHER */ {AUTOMATIC, false, 1, 200, 0}, - /* TANNER */ {AUTOMATIC, false, 1, 200, 0}, - /* BREWER */ {AUTOMATIC, false, 1, 200, 0}, - /* ALCHEMIST */ {AUTOMATIC, false, 1, 200, 0}, - /* SOAP_MAKER */ {AUTOMATIC, false, 1, 200, 0}, - /* WEAVER */ {AUTOMATIC, false, 1, 200, 0}, - /* CLOTHESMAKER */ {AUTOMATIC, false, 1, 200, 0}, - /* MILLER */ {AUTOMATIC, false, 1, 200, 0}, - /* PROCESS_PLANT */ {AUTOMATIC, false, 1, 200, 0}, - /* MAKE_CHEESE */ {AUTOMATIC, false, 1, 200, 0}, - /* MILK */ {AUTOMATIC, false, 1, 200, 0}, - /* COOK */ {AUTOMATIC, false, 1, 200, 0}, - /* PLANT */ {AUTOMATIC, false, 1, 200, 0}, - /* HERBALIST */ {AUTOMATIC, false, 1, 200, 0}, - /* FISH */ {AUTOMATIC, false, 1, 1, 0}, - /* CLEAN_FISH */ {AUTOMATIC, false, 1, 200, 0}, - /* DISSECT_FISH */ {AUTOMATIC, false, 1, 200, 0}, - /* HUNT */ {AUTOMATIC, true, 1, 1, 0}, - /* SMELT */ {AUTOMATIC, false, 1, 200, 0}, - /* FORGE_WEAPON */ {AUTOMATIC, false, 1, 200, 0}, - /* FORGE_ARMOR */ {AUTOMATIC, false, 1, 200, 0}, - /* FORGE_FURNITURE */ {AUTOMATIC, false, 1, 200, 0}, - /* METAL_CRAFT */ {AUTOMATIC, false, 1, 200, 0}, - /* CUT_GEM */ {AUTOMATIC, false, 1, 200, 0}, - /* ENCRUST_GEM */ {AUTOMATIC, false, 1, 200, 0}, - /* WOOD_CRAFT */ {AUTOMATIC, false, 1, 200, 0}, - /* STONE_CRAFT */ {AUTOMATIC, false, 1, 200, 0}, - /* BONE_CARVE */ {AUTOMATIC, false, 1, 200, 0}, - /* GLASSMAKER */ {AUTOMATIC, false, 1, 200, 0}, - /* EXTRACT_STRAND */ {AUTOMATIC, false, 1, 200, 0}, - /* SIEGECRAFT */ {AUTOMATIC, false, 1, 200, 0}, - /* SIEGEOPERATE */ {AUTOMATIC, false, 1, 200, 0}, - /* BOWYER */ {AUTOMATIC, false, 1, 200, 0}, - /* MECHANIC */ {AUTOMATIC, false, 1, 200, 0}, - /* POTASH_MAKING */ {AUTOMATIC, false, 1, 200, 0}, - /* LYE_MAKING */ {AUTOMATIC, false, 1, 200, 0}, - /* DYER */ {AUTOMATIC, false, 1, 200, 0}, - /* BURN_WOOD */ {AUTOMATIC, false, 1, 200, 0}, - /* OPERATE_PUMP */ {AUTOMATIC, false, 1, 200, 0}, - /* SHEARER */ {AUTOMATIC, false, 1, 200, 0}, - /* SPINNER */ {AUTOMATIC, false, 1, 200, 0}, - /* POTTERY */ {AUTOMATIC, false, 1, 200, 0}, - /* GLAZING */ {AUTOMATIC, false, 1, 200, 0}, - /* PRESSING */ {AUTOMATIC, false, 1, 200, 0}, - /* BEEKEEPING */ {AUTOMATIC, false, 1, 1, 0}, // reduce risk of stuck beekeepers (see http://www.bay12games.com/dwarves/mantisbt/view.php?id=3981) - /* WAX_WORKING */ {AUTOMATIC, false, 1, 200, 0}, + /* MINE */ {AUTOMATIC, true, 2, 200, 0}, + /* HAUL_STONE */ {HAULERS, false, 1, 200, 0}, + /* HAUL_WOOD */ {HAULERS, false, 1, 200, 0}, + /* HAUL_BODY */ {HAULERS, false, 1, 200, 0}, + /* HAUL_FOOD */ {HAULERS, false, 1, 200, 0}, + /* HAUL_REFUSE */ {HAULERS, false, 1, 200, 0}, + /* HAUL_ITEM */ {HAULERS, false, 1, 200, 0}, + /* HAUL_FURNITURE */ {HAULERS, false, 1, 200, 0}, + /* HAUL_ANIMAL */ {HAULERS, false, 1, 200, 0}, + /* CLEAN */ {HAULERS, false, 1, 200, 0}, + /* CUTWOOD */ {AUTOMATIC, true, 1, 200, 0}, + /* CARPENTER */ {AUTOMATIC, false, 1, 200, 0}, + /* DETAIL */ {AUTOMATIC, false, 1, 200, 0}, + /* MASON */ {AUTOMATIC, false, 1, 200, 0}, + /* ARCHITECT */ {AUTOMATIC, false, 1, 200, 0}, + /* ANIMALTRAIN */ {AUTOMATIC, false, 1, 200, 0}, + /* ANIMALCARE */ {AUTOMATIC, false, 1, 200, 0}, + /* DIAGNOSE */ {AUTOMATIC, false, 1, 200, 0}, + /* SURGERY */ {AUTOMATIC, false, 1, 200, 0}, + /* BONE_SETTING */ {AUTOMATIC, false, 1, 200, 0}, + /* SUTURING */ {AUTOMATIC, false, 1, 200, 0}, + /* DRESSING_WOUNDS */ {AUTOMATIC, false, 1, 200, 0}, + /* FEED_WATER_CIVILIANS */ {AUTOMATIC, false, 200, 200, 0}, + /* RECOVER_WOUNDED */ {HAULERS, false, 1, 200, 0}, + /* BUTCHER */ {AUTOMATIC, false, 1, 200, 0}, + /* TRAPPER */ {AUTOMATIC, false, 1, 200, 0}, + /* DISSECT_VERMIN */ {AUTOMATIC, false, 1, 200, 0}, + /* LEATHER */ {AUTOMATIC, false, 1, 200, 0}, + /* TANNER */ {AUTOMATIC, false, 1, 200, 0}, + /* BREWER */ {AUTOMATIC, false, 1, 200, 0}, + /* ALCHEMIST */ {AUTOMATIC, false, 1, 200, 0}, + /* SOAP_MAKER */ {AUTOMATIC, false, 1, 200, 0}, + /* WEAVER */ {AUTOMATIC, false, 1, 200, 0}, + /* CLOTHESMAKER */ {AUTOMATIC, false, 1, 200, 0}, + /* MILLER */ {AUTOMATIC, false, 1, 200, 0}, + /* PROCESS_PLANT */ {AUTOMATIC, false, 1, 200, 0}, + /* MAKE_CHEESE */ {AUTOMATIC, false, 1, 200, 0}, + /* MILK */ {AUTOMATIC, false, 1, 200, 0}, + /* COOK */ {AUTOMATIC, false, 1, 200, 0}, + /* PLANT */ {AUTOMATIC, false, 1, 200, 0}, + /* HERBALIST */ {AUTOMATIC, false, 1, 200, 0}, + /* FISH */ {AUTOMATIC, false, 1, 1, 0}, + /* CLEAN_FISH */ {AUTOMATIC, false, 1, 200, 0}, + /* DISSECT_FISH */ {AUTOMATIC, false, 1, 200, 0}, + /* HUNT */ {AUTOMATIC, true, 1, 1, 0}, + /* SMELT */ {AUTOMATIC, false, 1, 200, 0}, + /* FORGE_WEAPON */ {AUTOMATIC, false, 1, 200, 0}, + /* FORGE_ARMOR */ {AUTOMATIC, false, 1, 200, 0}, + /* FORGE_FURNITURE */ {AUTOMATIC, false, 1, 200, 0}, + /* METAL_CRAFT */ {AUTOMATIC, false, 1, 200, 0}, + /* CUT_GEM */ {AUTOMATIC, false, 1, 200, 0}, + /* ENCRUST_GEM */ {AUTOMATIC, false, 1, 200, 0}, + /* WOOD_CRAFT */ {AUTOMATIC, false, 1, 200, 0}, + /* STONE_CRAFT */ {AUTOMATIC, false, 1, 200, 0}, + /* BONE_CARVE */ {AUTOMATIC, false, 1, 200, 0}, + /* GLASSMAKER */ {AUTOMATIC, false, 1, 200, 0}, + /* EXTRACT_STRAND */ {AUTOMATIC, false, 1, 200, 0}, + /* SIEGECRAFT */ {AUTOMATIC, false, 1, 200, 0}, + /* SIEGEOPERATE */ {AUTOMATIC, false, 1, 200, 0}, + /* BOWYER */ {AUTOMATIC, false, 1, 200, 0}, + /* MECHANIC */ {AUTOMATIC, false, 1, 200, 0}, + /* POTASH_MAKING */ {AUTOMATIC, false, 1, 200, 0}, + /* LYE_MAKING */ {AUTOMATIC, false, 1, 200, 0}, + /* DYER */ {AUTOMATIC, false, 1, 200, 0}, + /* BURN_WOOD */ {AUTOMATIC, false, 1, 200, 0}, + /* OPERATE_PUMP */ {AUTOMATIC, false, 1, 200, 0}, + /* SHEARER */ {AUTOMATIC, false, 1, 200, 0}, + /* SPINNER */ {AUTOMATIC, false, 1, 200, 0}, + /* POTTERY */ {AUTOMATIC, false, 1, 200, 0}, + /* GLAZING */ {AUTOMATIC, false, 1, 200, 0}, + /* PRESSING */ {AUTOMATIC, false, 1, 200, 0}, + /* BEEKEEPING */ {AUTOMATIC, false, 1, 1, 0}, // reduce risk of stuck beekeepers (see http://www.bay12games.com/dwarves/mantisbt/view.php?id=3981) + /* WAX_WORKING */ {AUTOMATIC, false, 1, 200, 0}, /* PUSH_HAUL_VEHICLES */ {HAULERS, false, 1, 200, 0} }; static const int responsibility_penalties[] = { - 0, /* LAW_MAKING */ - 0, /* LAW_ENFORCEMENT */ - 3000, /* RECEIVE_DIPLOMATS */ - 0, /* MEET_WORKERS */ - 1000, /* MANAGE_PRODUCTION */ - 3000, /* TRADE */ - 1000, /* ACCOUNTING */ - 0, /* ESTABLISH_COLONY_TRADE_AGREEMENTS */ - 0, /* MAKE_INTRODUCTIONS */ - 0, /* MAKE_PEACE_AGREEMENTS */ - 0, /* MAKE_TOPIC_AGREEMENTS */ - 0, /* COLLECT_TAXES */ - 0, /* ESCORT_TAX_COLLECTOR */ - 0, /* EXECUTIONS */ - 0, /* TAME_EXOTICS */ - 0, /* RELIGION */ - 0, /* ATTACK_ENEMIES */ - 0, /* PATROL_TERRITORY */ - 0, /* MILITARY_GOALS */ - 0, /* MILITARY_STRATEGY */ - 0, /* UPGRADE_SQUAD_EQUIPMENT */ - 0, /* EQUIPMENT_MANIFESTS */ - 0, /* SORT_AMMUNITION */ - 0, /* BUILD_MORALE */ - 5000 /* HEALTH_MANAGEMENT */ + 0, /* LAW_MAKING */ + 0, /* LAW_ENFORCEMENT */ + 3000, /* RECEIVE_DIPLOMATS */ + 0, /* MEET_WORKERS */ + 1000, /* MANAGE_PRODUCTION */ + 3000, /* TRADE */ + 1000, /* ACCOUNTING */ + 0, /* ESTABLISH_COLONY_TRADE_AGREEMENTS */ + 0, /* MAKE_INTRODUCTIONS */ + 0, /* MAKE_PEACE_AGREEMENTS */ + 0, /* MAKE_TOPIC_AGREEMENTS */ + 0, /* COLLECT_TAXES */ + 0, /* ESCORT_TAX_COLLECTOR */ + 0, /* EXECUTIONS */ + 0, /* TAME_EXOTICS */ + 0, /* RELIGION */ + 0, /* ATTACK_ENEMIES */ + 0, /* PATROL_TERRITORY */ + 0, /* MILITARY_GOALS */ + 0, /* MILITARY_STRATEGY */ + 0, /* UPGRADE_SQUAD_EQUIPMENT */ + 0, /* EQUIPMENT_MANIFESTS */ + 0, /* SORT_AMMUNITION */ + 0, /* BUILD_MORALE */ + 5000 /* HEALTH_MANAGEMENT */ }; struct dwarf_info_t @@ -537,7 +538,7 @@ static void cleanup_state() labor_infos.clear(); } -static void reset_labor(df::enums::unit_labor::unit_labor labor) +static void reset_labor(df::unit_labor labor) { labor_infos[labor].set_minimum_dwarfs(default_labor_infos[labor].minimum_dwarfs); labor_infos[labor].set_maximum_dwarfs(default_labor_infos[labor].maximum_dwarfs); @@ -576,7 +577,7 @@ static void init_state() for (auto p = items.begin(); p != items.end(); p++) { string key = p->key(); - df::enums::unit_labor::unit_labor labor = (df::enums::unit_labor::unit_labor) atoi(key.substr(strlen("autolabor/labors/")).c_str()); + df::unit_labor labor = (df::unit_labor) atoi(key.substr(strlen("autolabor/labors/")).c_str()); if (labor >= 0 && labor <= labor_infos.size()) { labor_infos[labor].config = *p; @@ -597,7 +598,7 @@ static void init_state() labor_infos[i].is_exclusive = default_labor_infos[i].is_exclusive; labor_infos[i].active_dwarfs = 0; - reset_labor((df::enums::unit_labor::unit_labor) i); + reset_labor((df::unit_labor) i); } generate_labor_to_skill_map(); @@ -611,12 +612,12 @@ static void generate_labor_to_skill_map() // Generate labor -> skill mapping for (int i = 0; i <= ENUM_LAST_ITEM(unit_labor); i++) - labor_to_skill[i] = df::enums::job_skill::NONE; + labor_to_skill[i] = job_skill::NONE; FOR_ENUM_ITEMS(job_skill, skill) { int labor = ENUM_ATTR(job_skill, labor, skill); - if (labor != df::enums::unit_labor::NONE) + if (labor != unit_labor::NONE) { /* assert(labor >= 0); @@ -779,7 +780,7 @@ static void assign_labor(unit_labor::unit_labor labor, int value = dwarf_info[dwarf].mastery_penalty; - if (skill != df::enums::job_skill::NONE) + if (skill != job_skill::NONE) { int skill_level = 0; int skill_experience = 0; @@ -843,9 +844,9 @@ static void assign_labor(unit_labor::unit_labor labor, int max_dwarfs = labor_infos[labor].maximum_dwarfs(); // Special - don't assign hunt without a butchers, or fish without a fishery - if (df::enums::unit_labor::HUNT == labor && !has_butchers) + if (unit_labor::HUNT == labor && !has_butchers) min_dwarfs = max_dwarfs = 0; - if (df::enums::unit_labor::FISH == labor && !has_fishery) + if (unit_labor::FISH == labor && !has_fishery) min_dwarfs = max_dwarfs = 0; bool want_idle_dwarf = true; @@ -956,15 +957,15 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) { df::building *build = world->buildings.all[i]; auto type = build->getType(); - if (df::enums::building_type::Workshop == type) + if (building_type::Workshop == type) { - auto subType = build->getSubtype(); - if (df::enums::workshop_type::Butchers == subType) + df::workshop_type subType = (df::workshop_type)build->getSubtype(); + if (workshop_type::Butchers == subType) has_butchers = true; - if (df::enums::workshop_type::Fishery == subType) + if (workshop_type::Fishery == subType) has_fishery = true; } - else if (df::enums::building_type::TradeDepot == type) + else if (building_type::TradeDepot == type) { df::building_tradedepotst* depot = (df::building_tradedepotst*) build; trader_requested = depot->trade_flags.bits.trader_requested; @@ -978,11 +979,10 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) } } - for (int i = 0; i < world->units.all.size(); ++i) + for (int i = 0; i < world->units.active.size(); ++i) { - df::unit* cre = world->units.all[i]; - if (cre->race == race && cre->civ_id == civ && !cre->flags1.bits.marauder && !cre->flags1.bits.diplomat && !cre->flags1.bits.merchant && - !cre->flags1.bits.dead && !cre->flags1.bits.forest) + df::unit* cre = world->units.active[i]; + if (Units::isCitizen(cre)) { if (cre->burrows.size() > 0) continue; // dwarfs assigned to burrows are skipped entirely @@ -1003,9 +1003,6 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) { dwarf_info[dwarf].single_labor = -1; -// assert(dwarfs[dwarf]->status.souls.size() > 0); -// assert fails can cause DF to crash, so don't do that - if (dwarfs[dwarf]->status.souls.size() <= 0) continue; @@ -1076,7 +1073,7 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) // Track total & highest skill among normal/medical skills. (We don't care about personal or social skills.) - if (skill_class != df::enums::job_skill_class::Normal && skill_class != df::enums::job_skill_class::Medical) + if (skill_class != job_skill_class::Normal && skill_class != job_skill_class::Medical) continue; if (dwarf_info[dwarf].highest_skill < skill_level) @@ -1093,16 +1090,11 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) dwarf_info[dwarf].mastery_penalty -= 10 * dwarf_info[dwarf].total_skill; dwarf_info[dwarf].mastery_penalty -= dwarf_info[dwarf].noble_penalty; - for (int labor = ENUM_FIRST_ITEM(unit_labor); labor <= ENUM_LAST_ITEM(unit_labor); labor++) + FOR_ENUM_ITEMS(unit_labor, labor) { - if (labor == df::enums::unit_labor::NONE) + if (labor == unit_labor::NONE) continue; - /* - assert(labor >= 0); - assert(labor < ARRAY_COUNT(labor_infos)); - */ - if (labor_infos[labor].is_exclusive && dwarfs[dwarf]->status.labors[labor]) dwarf_info[dwarf].mastery_penalty -= 100; } @@ -1120,15 +1112,13 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) for (auto p = dwarfs[dwarf]->status.misc_traits.begin(); p < dwarfs[dwarf]->status.misc_traits.end(); p++) { - // 7 / 0x7 = Newly arrived migrant, will not work yet - // 17 / 0x11 = On break - if ((*p)->id == 0x07 || (*p)->id == 0x11) + if ((*p)->id == misc_trait_type::Migrant || (*p)->id == misc_trait_type::OnBreak) is_on_break = true; } - if (dwarfs[dwarf]->profession == df::enums::profession::BABY || - dwarfs[dwarf]->profession == df::enums::profession::CHILD || - dwarfs[dwarf]->profession == df::enums::profession::DRUNK) + if (dwarfs[dwarf]->profession == profession::BABY || + dwarfs[dwarf]->profession == profession::CHILD || + dwarfs[dwarf]->profession == profession::DRUNK) { dwarf_info[dwarf].state = CHILD; } @@ -1146,18 +1136,13 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) else { int job = dwarfs[dwarf]->job.current_job->job_type; - - /* - assert(job >= 0); - assert(job < ARRAY_COUNT(dwarf_states)); - */ - if (job >= 0 && job < ARRAY_COUNT(dwarf_states)) - dwarf_info[dwarf].state = dwarf_states[job]; - else - { - out.print("Dwarf %i \"%s\" has unknown job %i\n", dwarf, dwarfs[dwarf]->name.first_name.c_str(), job); - dwarf_info[dwarf].state = OTHER; - } + if (job >= 0 && job < ARRAY_COUNT(dwarf_states)) + dwarf_info[dwarf].state = dwarf_states[job]; + else + { + out.print("Dwarf %i \"%s\" has unknown job %i\n", dwarf, dwarfs[dwarf]->name.first_name.c_str(), job); + dwarf_info[dwarf].state = OTHER; + } } state_count[dwarf_info[dwarf].state]++; @@ -1170,14 +1155,9 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) FOR_ENUM_ITEMS(unit_labor, labor) { - if (labor == df::enums::unit_labor::NONE) + if (labor == unit_labor::NONE) continue; - /* - assert(labor >= 0); - assert(labor < ARRAY_COUNT(labor_infos)); - */ - labor_infos[labor].active_dwarfs = 0; labors.push_back(labor); @@ -1217,11 +1197,6 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) { auto labor = *lp; - /* - assert(labor >= 0); - assert(labor < ARRAY_COUNT(labor_infos)); - */ - assign_labor(labor, n_dwarfs, dwarf_info, trader_requested, dwarfs, has_butchers, has_fishery, out); } @@ -1241,7 +1216,7 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) { FOR_ENUM_ITEMS(unit_labor, labor) { - if (labor == df::enums::unit_labor::NONE) + if (labor == unit_labor::NONE) continue; if (labor_infos[labor].mode() != HAULERS) continue; @@ -1264,14 +1239,9 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) FOR_ENUM_ITEMS(unit_labor, labor) { - if (labor == df::enums::unit_labor::NONE) + if (labor == unit_labor::NONE) continue; - /* - assert(labor >= 0); - assert(labor < ARRAY_COUNT(labor_infos)); - */ - if (labor_infos[labor].mode() != HAULERS) continue; @@ -1311,7 +1281,7 @@ DFhackCExport command_result plugin_onupdate ( color_ostream &out ) return CR_OK; } -void print_labor (df::enums::unit_labor::unit_labor labor, color_ostream &out) +void print_labor (df::unit_labor labor, color_ostream &out) { string labor_name = ENUM_KEY_STR(unit_labor, labor); out << labor_name << ": "; @@ -1358,7 +1328,6 @@ command_result autolabor (color_ostream &out, std::vector <std::string> & parame return CR_OK; } - else if (parameters.size() == 2 && parameters[0] == "haulpct") { if (!enable_autolabor) @@ -1371,15 +1340,15 @@ command_result autolabor (color_ostream &out, std::vector <std::string> & parame hauler_pct = pct; return CR_OK; } - else if (parameters.size() == 2 || parameters.size() == 3) { - + else if (parameters.size() == 2 || parameters.size() == 3) + { if (!enable_autolabor) { out << "Error: The plugin is not enabled." << endl; return CR_FAILURE; } - df::enums::unit_labor::unit_labor labor = df::enums::unit_labor::NONE; + df::unit_labor labor = unit_labor::NONE; FOR_ENUM_ITEMS(unit_labor, test_labor) { @@ -1387,7 +1356,7 @@ command_result autolabor (color_ostream &out, std::vector <std::string> & parame labor = test_labor; } - if (labor == df::enums::unit_labor::NONE) + if (labor == unit_labor::NONE) { out.printerr("Could not find labor %s.\n", parameters[0].c_str()); return CR_WRONG_USAGE; @@ -1430,7 +1399,8 @@ command_result autolabor (color_ostream &out, std::vector <std::string> & parame return CR_OK; } - else if (parameters.size() == 1 && parameters[0] == "reset-all") { + else if (parameters.size() == 1 && parameters[0] == "reset-all") + { if (!enable_autolabor) { out << "Error: The plugin is not enabled." << endl; @@ -1439,12 +1409,13 @@ command_result autolabor (color_ostream &out, std::vector <std::string> & parame for (int i = 0; i < labor_infos.size(); i++) { - reset_labor((df::enums::unit_labor::unit_labor) i); + reset_labor((df::unit_labor) i); } out << "All labors reset." << endl; return CR_OK; } - else if (parameters.size() == 1 && parameters[0] == "list" || parameters[0] == "status") { + else if (parameters.size() == 1 && parameters[0] == "list" || parameters[0] == "status") + { if (!enable_autolabor) { out << "Error: The plugin is not enabled." << endl; @@ -1467,7 +1438,7 @@ command_result autolabor (color_ostream &out, std::vector <std::string> & parame { FOR_ENUM_ITEMS(unit_labor, labor) { - if (labor == df::enums::unit_labor::NONE) + if (labor == unit_labor::NONE) continue; print_labor(labor, out); @@ -1571,7 +1542,7 @@ static int stockcheck(color_ostream &out, vector <string> & parameters) { df::building *build = world->buildings.all[i]; auto type = build->getType(); - if (df::enums::building_type::Stockpile == type) + if (building_type::Stockpile == type) { df::building_stockpilest *sp = virtual_cast<df::building_stockpilest>(build); StockpileInfo *spi = new StockpileInfo(sp); @@ -1580,7 +1551,7 @@ static int stockcheck(color_ostream &out, vector <string> & parameters) } - std::vector<df::item*> &items = world->items.other[df::enums::items_other_id::ANY_FREE]; + std::vector<df::item*> &items = world->items.other[items_other_id::ANY_FREE]; // Precompute a bitmask with the bad flags df::item_flags bad_flags; @@ -1602,13 +1573,13 @@ static int stockcheck(color_ostream &out, vector <string> & parameters) // we really only care about MEAT, FISH, FISH_RAW, PLANT, CHEESE, FOOD, and EGG df::item_type typ = item->getType(); - if (typ != df::enums::item_type::MEAT && - typ != df::enums::item_type::FISH && - typ != df::enums::item_type::FISH_RAW && - typ != df::enums::item_type::PLANT && - typ != df::enums::item_type::CHEESE && - typ != df::enums::item_type::FOOD && - typ != df::enums::item_type::EGG) + if (typ != item_type::MEAT && + typ != item_type::FISH && + typ != item_type::FISH_RAW && + typ != item_type::PLANT && + typ != item_type::CHEESE && + typ != item_type::FOOD && + typ != item_type::EGG) continue; df::item *container = 0; @@ -1673,11 +1644,11 @@ static int stockcheck(color_ostream &out, vector <string> & parameters) if (building) { df::building_type btype = building->getType(); - if (btype == df::enums::building_type::TradeDepot || - btype == df::enums::building_type::Wagon) + if (btype == building_type::TradeDepot || + btype == building_type::Wagon) continue; // items in trade depot or the embark wagon do not rot - if (typ == df::enums::item_type::EGG && btype ==df::enums::building_type::NestBox) + if (typ == item_type::EGG && btype ==building_type::NestBox) continue; // eggs in nest box do not rot } diff --git a/plugins/changelayer.cpp b/plugins/changelayer.cpp index 317a0fa3..3ab1899a 100644 --- a/plugins/changelayer.cpp +++ b/plugins/changelayer.cpp @@ -19,6 +19,7 @@ #include "df/world_data.h" #include "df/world_geo_biome.h" #include "df/world_geo_layer.h" +#include "df/region_map_entry.h" using namespace DFHack; using namespace df::enums; diff --git a/plugins/cleaners.cpp b/plugins/cleaners.cpp index 30befab2..319b83c1 100644 --- a/plugins/cleaners.cpp +++ b/plugins/cleaners.cpp @@ -50,12 +50,12 @@ command_result cleanmap (color_ostream &out, bool snow, bool mud) // filter snow if(!snow && spatter->mat_type == builtin_mats::WATER - && spatter->mat_state == matter_state::Powder) + && spatter->mat_state == (short)matter_state::Powder) continue; // filter mud if(!mud && spatter->mat_type == builtin_mats::MUD - && spatter->mat_state == matter_state::Solid) + && spatter->mat_state == (short)matter_state::Solid) continue; delete evt; @@ -81,11 +81,18 @@ command_result cleanitems (color_ostream &out) df::item_actual *item = (df::item_actual *)world->items.all[i]; if (item->contaminants && item->contaminants->size()) { + std::vector<df::contaminant*> saved; for (size_t j = 0; j < item->contaminants->size(); j++) - delete item->contaminants->at(j); + { + auto obj = (*item->contaminants)[j]; + if (obj->flags.whole & 0x8000) // DFHack-generated contaminant + saved.push_back(obj); + else + delete obj; + } cleaned_items++; - cleaned_total += item->contaminants->size(); - item->contaminants->clear(); + cleaned_total += item->contaminants->size() - saved.size(); + item->contaminants->swap(saved); } } if (cleaned_total) @@ -114,6 +121,28 @@ command_result cleanunits (color_ostream &out) return CR_OK; } +command_result cleanplants (color_ostream &out) +{ + // Invoked from clean(), already suspended + int cleaned_plants = 0, cleaned_total = 0; + for (size_t i = 0; i < world->plants.all.size(); i++) + { + df::plant *plant = world->plants.all[i]; + + if (plant->contaminants.size()) + { + for (size_t j = 0; j < plant->contaminants.size(); j++) + delete plant->contaminants[j]; + cleaned_plants++; + cleaned_total += plant->contaminants.size(); + plant->contaminants.clear(); + } + } + if (cleaned_total) + out.print("Removed %d contaminants from %d plants.\n", cleaned_total, cleaned_plants); + return CR_OK; +} + command_result spotclean (color_ostream &out, vector <string> & parameters) { // HOTKEY COMMAND: CORE ALREADY SUSPENDED @@ -153,6 +182,7 @@ command_result clean (color_ostream &out, vector <string> & parameters) bool mud = false; bool units = false; bool items = false; + bool plants = false; for(size_t i = 0; i < parameters.size();i++) { if(parameters[i] == "map") @@ -161,11 +191,14 @@ command_result clean (color_ostream &out, vector <string> & parameters) units = true; else if(parameters[i] == "items") items = true; + else if(parameters[i] == "plants") + plants = true; else if(parameters[i] == "all") { map = true; items = true; units = true; + plants = true; } else if(parameters[i] == "snow") snow = true; @@ -174,7 +207,7 @@ command_result clean (color_ostream &out, vector <string> & parameters) else return CR_WRONG_USAGE; } - if(!map && !units && !items) + if(!map && !units && !items && !plants) return CR_WRONG_USAGE; CoreSuspender suspend; @@ -185,6 +218,8 @@ command_result clean (color_ostream &out, vector <string> & parameters) cleanunits(out); if(items) cleanitems(out); + if(plants) + cleanplants(out); return CR_OK; } @@ -198,6 +233,7 @@ DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <Plug " map - clean the map tiles\n" " items - clean all items\n" " units - clean all creatures\n" + " plants - clean all plants\n" " all - clean everything.\n" "More options for 'map':\n" " snow - also remove snow\n" diff --git a/plugins/cleanowned.cpp b/plugins/cleanowned.cpp index c1521b8d..cd01fd61 100644 --- a/plugins/cleanowned.cpp +++ b/plugins/cleanowned.cpp @@ -116,7 +116,7 @@ command_result df_cleanowned (color_ostream &out, vector <string> & parameters) } else if (item->flags.bits.on_ground) { - int32_t type = item->getType(); + df::item_type type = item->getType(); if(type == item_type::MEAT || type == item_type::FISH || type == item_type::VERMIN || diff --git a/plugins/devel/CMakeLists.txt b/plugins/devel/CMakeLists.txt index 5d1d585a..134d5cb6 100644 --- a/plugins/devel/CMakeLists.txt +++ b/plugins/devel/CMakeLists.txt @@ -17,3 +17,7 @@ DFHACK_PLUGIN(stockcheck stockcheck.cpp) DFHACK_PLUGIN(stripcaged stripcaged.cpp) DFHACK_PLUGIN(rprobe rprobe.cpp) DFHACK_PLUGIN(nestboxes nestboxes.cpp) +DFHACK_PLUGIN(vshook vshook.cpp) +IF(UNIX) +DFHACK_PLUGIN(ref-index ref-index.cpp) +ENDIF() diff --git a/plugins/devel/dumpmats.cpp b/plugins/devel/dumpmats.cpp index ba888e7c..0af1fce5 100644 --- a/plugins/devel/dumpmats.cpp +++ b/plugins/devel/dumpmats.cpp @@ -11,6 +11,7 @@ #include "df/matter_state.h" #include "df/descriptor_color.h" #include "df/item_type.h" +#include "df/strain_type.h" using std::string; using std::vector; @@ -195,47 +196,17 @@ command_result df_dumpmats (color_ostream &out, vector<string> ¶meters) if (mat->molar_mass != 0xFBBC7818) out.print("\t[MOLAR_MASS:%i]\n", mat->molar_mass); - if (mat->strength.impact_yield != 10000) - out.print("\t[IMPACT_YIELD:%i]\n", mat->strength.impact_yield); - if (mat->strength.impact_fracture != 10000) - out.print("\t[IMPACT_FRACTURE:%i]\n", mat->strength.impact_fracture); - if (mat->strength.impact_strain_at_yield != 0) - out.print("\t[IMPACT_STRAIN_AT_YIELD:%i]\n", mat->strength.impact_strain_at_yield); - - if (mat->strength.compressive_yield != 10000) - out.print("\t[COMPRESSIVE_YIELD:%i]\n", mat->strength.compressive_yield); - if (mat->strength.compressive_fracture != 10000) - out.print("\t[COMPRESSIVE_FRACTURE:%i]\n", mat->strength.compressive_fracture); - if (mat->strength.compressive_strain_at_yield != 0) - out.print("\t[COMPRESSIVE_STRAIN_AT_YIELD:%i]\n", mat->strength.compressive_strain_at_yield); - - if (mat->strength.tensile_yield != 10000) - out.print("\t[TENSILE_YIELD:%i]\n", mat->strength.tensile_yield); - if (mat->strength.tensile_fracture != 10000) - out.print("\t[TENSILE_FRACTURE:%i]\n", mat->strength.tensile_fracture); - if (mat->strength.tensile_strain_at_yield != 0) - out.print("\t[TENSILE_STRAIN_AT_YIELD:%i]\n", mat->strength.tensile_strain_at_yield); - - if (mat->strength.torsion_yield != 10000) - out.print("\t[TORSION_YIELD:%i]\n", mat->strength.torsion_yield); - if (mat->strength.torsion_fracture != 10000) - out.print("\t[TORSION_FRACTURE:%i]\n", mat->strength.torsion_fracture); - if (mat->strength.torsion_strain_at_yield != 0) - out.print("\t[TORSION_STRAIN_AT_YIELD:%i]\n", mat->strength.torsion_strain_at_yield); - - if (mat->strength.shear_yield != 10000) - out.print("\t[SHEAR_YIELD:%i]\n", mat->strength.shear_yield); - if (mat->strength.shear_fracture != 10000) - out.print("\t[SHEAR_FRACTURE:%i]\n", mat->strength.shear_fracture); - if (mat->strength.shear_strain_at_yield != 0) - out.print("\t[SHEAR_STRAIN_AT_YIELD:%i]\n", mat->strength.shear_strain_at_yield); - - if (mat->strength.bending_yield != 10000) - out.print("\t[BENDING_YIELD:%i]\n", mat->strength.bending_yield); - if (mat->strength.bending_fracture != 10000) - out.print("\t[BENDING_FRACTURE:%i]\n", mat->strength.bending_fracture); - if (mat->strength.bending_strain_at_yield != 0) - out.print("\t[BENDING_STRAIN_AT_YIELD:%i]\n", mat->strength.bending_strain_at_yield); + FOR_ENUM_ITEMS(strain_type, strain) + { + auto name = ENUM_KEY_STR(strain_type,strain); + + if (mat->strength.yield[strain] != 10000) + out.print("\t[%s_YIELD:%i]\n", name.c_str(), mat->strength.yield[strain]); + if (mat->strength.fracture[strain] != 10000) + out.print("\t[%s_FRACTURE:%i]\n", name.c_str(), mat->strength.fracture[strain]); + if (mat->strength.strain_at_yield[strain] != 0) + out.print("\t[%s_STRAIN_AT_YIELD:%i]\n", name.c_str(), mat->strength.strain_at_yield[strain]); + } if (mat->strength.max_edge != 0) out.print("\t[MAX_EDGE:%i]\n", mat->strength.max_edge); diff --git a/plugins/devel/kittens.cpp b/plugins/devel/kittens.cpp index 2e8e6eab..b610d474 100644 --- a/plugins/devel/kittens.cpp +++ b/plugins/devel/kittens.cpp @@ -257,7 +257,7 @@ command_result kittens (color_ostream &out, vector <string> & parameters) }; con.cursor(false); con.clear(); - Console::color_value color = Console::COLOR_BLUE; + Console::color_value color = COLOR_BLUE; while(1) { if(shutdown_flag) @@ -282,7 +282,7 @@ command_result kittens (color_ostream &out, vector <string> & parameters) con.flush(); con.msleep(60); ((int&)color) ++; - if(color > Console::COLOR_MAX) - color = Console::COLOR_BLUE; + if(color > COLOR_MAX) + color = COLOR_BLUE; } } diff --git a/plugins/devel/memview.cpp b/plugins/devel/memview.cpp index 5d8d6a9b..757b475d 100644 --- a/plugins/devel/memview.cpp +++ b/plugins/devel/memview.cpp @@ -73,7 +73,7 @@ void outputHex(uint8_t *buf,uint8_t *lbuf,size_t len,size_t start,color_ostream con.reset_color();
if(isAddr((uint32_t *)(buf+j+i),ranges))
- con.color(Console::COLOR_LIGHTRED); //coloring in the middle does not work
+ con.color(COLOR_LIGHTRED); //coloring in the middle does not work
//TODO make something better?
}
if(lbuf[j+i]!=buf[j+i])
diff --git a/plugins/devel/nestboxes.cpp b/plugins/devel/nestboxes.cpp index b3d24cd9..42c3c066 100644 --- a/plugins/devel/nestboxes.cpp +++ b/plugins/devel/nestboxes.cpp @@ -31,6 +31,40 @@ static command_result nestboxes(color_ostream &out, vector <string> & parameters DFHACK_PLUGIN("nestboxes"); +static bool enabled = false; + +static void eggscan(color_ostream &out) +{ + CoreSuspender suspend; + + for (int i = 0; i < world->buildings.all.size(); ++i) + { + df::building *build = world->buildings.all[i]; + auto type = build->getType(); + if (df::enums::building_type::NestBox == type) + { + bool fertile = false; + df::building_nest_boxst *nb = virtual_cast<df::building_nest_boxst>(build); + if (nb->claimed_by != -1) + { + df::unit* u = df::unit::find(nb->claimed_by); + if (u && u->relations.pregnancy_timer > 0) + fertile = true; + } + for (int j = 1; j < nb->contained_items.size(); j++) + { + df::item* item = nb->contained_items[j]->item; + if (item->flags.bits.forbid != fertile) + { + item->flags.bits.forbid = fertile; + out << item->getStackSize() << " eggs " << (fertile ? "forbidden" : "unforbidden.") << endl; + } + } + } + } +} + + DFhackCExport command_result plugin_init (color_ostream &out, std::vector <PluginCommand> &commands) { if (world && ui) { @@ -49,6 +83,19 @@ DFhackCExport command_result plugin_shutdown ( color_ostream &out ) return CR_OK; } +DFhackCExport command_result plugin_onupdate(color_ostream &out) +{ + if (!enabled) + return CR_OK; + + static unsigned cnt = 0; + if ((++cnt % 5) != 0) + return CR_OK; + + eggscan(out); + + return CR_OK; +} static command_result nestboxes(color_ostream &out, vector <string> & parameters) { @@ -57,60 +104,16 @@ static command_result nestboxes(color_ostream &out, vector <string> & parameters int dump_count = 0; int good_egg = 0; - if (parameters.size() == 1 && parameters[0] == "clean") - { - clean = true; - } - for (int i = 0; i < world->buildings.all.size(); ++i) - { - df::building *build = world->buildings.all[i]; - auto type = build->getType(); - if (df::enums::building_type::NestBox == type) - { - bool needs_clean = false; - df::building_nest_boxst *nb = virtual_cast<df::building_nest_boxst>(build); - out << "Nestbox at (" << nb->x1 << "," << nb->y1 << ","<< nb->z << "): claimed-by " << nb->claimed_by << ", contained item count " << nb->contained_items.size() << " (" << nb->anon_1 << ")" << endl; - if (nb->contained_items.size() > 1) - needs_clean = true; - if (nb->claimed_by != -1) - { - df::unit* u = df::unit::find(nb->claimed_by); - if (u) - { - out << " Claimed by "; - if (u->name.has_name) - out << u->name.first_name << ", "; - df::creature_raw *raw = df::global::world->raws.creatures.all[u->race]; - out << raw->creature_id - << ", pregnancy timer " << u->relations.pregnancy_timer << endl; - if (u->relations.pregnancy_timer > 0) - needs_clean = false; - } - } - for (int j = 1; j < nb->contained_items.size(); j++) - { - df::item* item = nb->contained_items[j]->item; - if (needs_clean) { - if (clean && !item->flags.bits.dump) - { - item->flags.bits.dump = 1; - dump_count += item->getStackSize(); - - } - } else { - good_egg += item->getStackSize(); - } - } - } - } - - if (clean) - { - out << dump_count << " eggs dumped." << endl; - } - out << good_egg << " fertile eggs found." << endl; - - + if (parameters.size() == 1) { + if (parameters[0] == "enable") + enabled = true; + else if (parameters[0] == "disable") + enabled = false; + else + return CR_WRONG_USAGE; + } else { + out << "Plugin " << (enabled ? "enabled" : "disabled") << "." << endl; + } return CR_OK; } diff --git a/plugins/devel/ref-index.cpp b/plugins/devel/ref-index.cpp new file mode 100644 index 00000000..686f6918 --- /dev/null +++ b/plugins/devel/ref-index.cpp @@ -0,0 +1,149 @@ +#include "Core.h" +#include <Console.h> +#include <Export.h> +#include <PluginManager.h> +#include <modules/Gui.h> +#include <modules/Screen.h> +#include <vector> +#include <cstdio> +#include <stack> +#include <string> +#include <cmath> + +#include <VTableInterpose.h> +#include "df/item.h" +#include "df/unit.h" +#include "df/world.h" +#include "df/general_ref_item.h" +#include "df/general_ref_unit.h" + +using std::vector; +using std::string; +using std::stack; +using namespace DFHack; + +using df::global::gps; + +DFHACK_PLUGIN("ref-index"); + +#define global_id id + +template<class T> +T get_from_global_id_vector(int32_t id, const std::vector<T> &vect, int32_t *cache) +{ + size_t size = vect.size(); + int32_t start=0; + int32_t end=(int32_t)size-1; + + // Check the cached location. If it is a match, this provides O(1) lookup. + // Otherwise it works like one binsearch iteration. + if (size_t(*cache) < size) + { + T cptr = vect[*cache]; + if (cptr->global_id == id) + return cptr; + if (cptr->global_id < id) + start = *cache+1; + else + end = *cache-1; + } + + // Regular binsearch. The end check provides O(1) caching for missing item. + if (start <= end && vect[end]->global_id >= id) + { + do { + int32_t mid=(start+end)>>1; + + T cptr=vect[mid]; + if(cptr->global_id==id) + { + *cache = mid; + return cptr; + } + else if(cptr->global_id>id)end=mid-1; + else start=mid+1; + } while(start<=end); + } + + *cache = end+1; + return NULL; +} + +template<class T> T *find_object(int32_t id, int32_t *cache); +template<> df::item *find_object<df::item>(int32_t id, int32_t *cache) { + return get_from_global_id_vector(id, df::global::world->items.all, cache); +} +template<> df::unit *find_object<df::unit>(int32_t id, int32_t *cache) { + return get_from_global_id_vector(id, df::global::world->units.all, cache); +} + +template<class T> +struct CachedRef { + int32_t id; + int32_t cache; + CachedRef(int32_t id = -1) : id(id), cache(-1) {} + T *target() { return find_object<T>(id, &cache); } +}; + +#ifdef LINUX_BUILD +struct item_hook : df::general_ref_item { + typedef df::general_ref_item interpose_base; + + DEFINE_VMETHOD_INTERPOSE(df::item*, getItem, ()) + { + // HUGE HACK: ASSUMES THERE ARE 4 USABLE BYTES AFTER THE OBJECT + // This actually is true with glibc allocator due to granularity. + return find_object<df::item>(item_id, 1+&item_id); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(item_hook, getItem); + +struct unit_hook : df::general_ref_unit { + typedef df::general_ref_unit interpose_base; + + DEFINE_VMETHOD_INTERPOSE(df::unit*, getUnit, ()) + { + // HUGE HACK: ASSUMES THERE ARE 4 USABLE BYTES AFTER THE OBJECT + // This actually is true with glibc allocator due to granularity. + return find_object<df::unit>(unit_id, 1+&unit_id); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(unit_hook, getUnit); + +command_result hook_refs(color_ostream &out, vector <string> & parameters) +{ + auto &hook = INTERPOSE_HOOK(item_hook, getItem); + if (hook.is_applied()) + { + hook.remove(); + INTERPOSE_HOOK(unit_hook, getUnit).remove(); + } + else + { + hook.apply(); + INTERPOSE_HOOK(unit_hook, getUnit).apply(); + } + + if (hook.is_applied()) + out.print("Hook is applied.\n"); + else + out.print("Hook is not applied.\n"); + return CR_OK; +} +#endif + +DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands) +{ +#ifdef LINUX_BUILD + commands.push_back(PluginCommand("hook-refs","Inject O(1) cached lookup into general refs.",hook_refs)); +#endif + + return CR_OK; +} + +DFhackCExport command_result plugin_shutdown ( color_ostream &out ) +{ + return CR_OK; +} diff --git a/plugins/devel/rprobe.cpp b/plugins/devel/rprobe.cpp index 7a091a96..805489d5 100644 --- a/plugins/devel/rprobe.cpp +++ b/plugins/devel/rprobe.cpp @@ -27,6 +27,7 @@ using namespace std; #include "df/world_region_details.h" #include "df/world_geo_biome.h" #include "df/world_geo_layer.h" +#include "df/region_map_entry.h" #include "df/inclusion_type.h" #include "df/viewscreen_choose_start_sitest.h" @@ -79,7 +80,7 @@ command_result rprobe (color_ostream &out, vector <string> & parameters) if (parameters.size() == 2) { - if (parameters[0] == "wet") + if (parameters[0] == "rai") set_field = 0; else if (parameters[0] == "veg") set_field = 1; @@ -87,7 +88,7 @@ command_result rprobe (color_ostream &out, vector <string> & parameters) set_field = 2; else if (parameters[0] == "evi") set_field = 3; - else if (parameters[0] == "hil") + else if (parameters[0] == "dra") set_field = 4; else if (parameters[0] == "sav") set_field = 5; @@ -113,11 +114,11 @@ command_result rprobe (color_ostream &out, vector <string> & parameters) { coord2d rg = screen->biome_rgn[i]; - df::world_data::T_region_map* rd = &data->region_map[rg.x][rg.y]; + auto rd = &data->region_map[rg.x][rg.y]; if (set && i == to_set) { if (set_field == 0) - rd->wetness = set_val; + rd->rainfall = set_val; else if (set_field == 1) rd->vegetation = set_val; else if (set_field == 2) @@ -125,11 +126,11 @@ command_result rprobe (color_ostream &out, vector <string> & parameters) else if (set_field == 3) rd->evilness = set_val; else if (set_field == 4) - rd->hilliness = set_val; + rd->drainage = set_val; else if (set_field == 5) rd->savagery = set_val; else if (set_field == 6) - rd->saltiness = set_val; + rd->salinity = set_val; } out << i << ": x = " << rg.x << ", y = " << rg.y; @@ -140,13 +141,13 @@ command_result rprobe (color_ostream &out, vector <string> & parameters) " landmass_id: " << rd->landmass_id << " flags: " << hex << rd->flags.as_int() << dec << endl; out << - "wet: " << rd->wetness << " " << + "rai: " << rd->rainfall << " " << "veg: " << rd->vegetation << " " << "tem: " << rd->temperature << " " << "evi: " << rd->evilness << " " << - "hil: " << rd->hilliness << " " << + "dra: " << rd->drainage << " " << "sav: " << rd->savagery << " " << - "sal: " << rd->saltiness; + "sal: " << rd->salinity; int32_t *p = (int32_t *)rd; int c = sizeof(*rd) / sizeof(int32_t); diff --git a/plugins/devel/vshook.cpp b/plugins/devel/vshook.cpp new file mode 100644 index 00000000..ceec2d08 --- /dev/null +++ b/plugins/devel/vshook.cpp @@ -0,0 +1,55 @@ +#include "Core.h" +#include <Console.h> +#include <Export.h> +#include <PluginManager.h> +#include <modules/Gui.h> +#include <modules/Screen.h> +#include <vector> +#include <cstdio> +#include <stack> +#include <string> +#include <cmath> + +#include <VTableInterpose.h> +#include "df/graphic.h" +#include "df/viewscreen_titlest.h" + +using std::vector; +using std::string; +using std::stack; +using namespace DFHack; + +using df::global::gps; + +DFHACK_PLUGIN("vshook"); + +struct title_hook : df::viewscreen_titlest { + typedef df::viewscreen_titlest interpose_base; + + DEFINE_VMETHOD_INTERPOSE(void, render, ()) + { + INTERPOSE_NEXT(render)(); + + Screen::Pen pen(' ',COLOR_WHITE,COLOR_BLACK); + Screen::paintString(pen,0,0,"DFHack " DFHACK_VERSION); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(title_hook, render); + +DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands) +{ + if (gps) + { + if (!INTERPOSE_HOOK(title_hook, render).apply()) + out.printerr("Could not interpose viewscreen_titlest::render\n"); + } + + return CR_OK; +} + +DFhackCExport command_result plugin_shutdown ( color_ostream &out ) +{ + INTERPOSE_HOOK(title_hook, render).remove(); + return CR_OK; +} diff --git a/plugins/jobutils.cpp b/plugins/jobutils.cpp index 24ad4170..dbfe26b9 100644 --- a/plugins/jobutils.cpp +++ b/plugins/jobutils.cpp @@ -372,7 +372,7 @@ static command_result job_cmd(color_ostream &out, vector <string> & parameters) out << "Job item updated." << endl; - if (item->item_type < 0 && minfo.isValid()) + if (item->item_type < (df::item_type)0 && minfo.isValid()) out.printerr("WARNING: Due to a probable bug, creature & plant material subtype\n" " is ignored unless the item type is also specified.\n"); diff --git a/plugins/liquids.cpp b/plugins/liquids.cpp index b036e4fa..6df530a9 100644 --- a/plugins/liquids.cpp +++ b/plugins/liquids.cpp @@ -27,6 +27,7 @@ #include <set> #include <cstdlib> #include <sstream> +#include <memory> using std::vector; using std::string; using std::endl; @@ -41,6 +42,7 @@ using std::set; #include "modules/Gui.h" #include "TileTypes.h" #include "modules/MapCache.h" +#include "LuaTools.h" #include "Brushes.h" using namespace MapExtras; using namespace DFHack; @@ -50,7 +52,6 @@ CommandHistory liquids_hist; command_result df_liquids (color_ostream &out, vector <string> & parameters); command_result df_liquids_here (color_ostream &out, vector <string> & parameters); -command_result df_liquids_execute (color_ostream &out); DFHACK_PLUGIN("liquids"); @@ -74,13 +75,79 @@ DFhackCExport command_result plugin_shutdown ( color_ostream &out ) return CR_OK; } -// static stuff to be remembered between sessions -static string brushname = "point"; -static string mode="magma"; -static string flowmode="f+"; -static string _setmode ="s."; -static unsigned int amount = 7; -static int width = 1, height = 1, z_levels = 1; +enum BrushType { + B_POINT, B_RANGE, B_BLOCK, B_COLUMN, B_FLOOD +}; + +static const char *brush_name[] = { + "point", "range", "block", "column", "flood", NULL +}; + +enum PaintMode { + P_WATER, P_MAGMA, P_OBSIDIAN, P_OBSIDIAN_FLOOR, + P_RIVER_SOURCE, P_FLOW_BITS, P_WCLEAN +}; + +static const char *paint_mode_name[] = { + "water", "magma", "obsidian", "obsidian_floor", + "riversource", "flowbits", "wclean", NULL +}; + +enum ModifyMode { + M_INC, M_KEEP, M_DEC +}; + +static const char *modify_mode_name[] = { + "+", ".", "-", NULL +}; + +enum PermaflowMode { + PF_KEEP, PF_NONE, + PF_NORTH, PF_SOUTH, PF_EAST, PF_WEST, + PF_NORTHEAST, PF_NORTHWEST, PF_SOUTHEAST, PF_SOUTHWEST +}; + +static const char *permaflow_name[] = { + ".", "-", "N", "S", "E", "W", + "NE", "NW", "SE", "SW", NULL +}; + +#define X(name) tile_liquid_flow_dir::name +static const df::tile_liquid_flow_dir permaflow_id[] = { + X(none), X(none), X(north), X(south), X(east), X(west), + X(northeast), X(northwest), X(southeast), X(southwest) +}; +#undef X + +struct OperationMode { + BrushType brush; + PaintMode paint; + ModifyMode flowmode; + ModifyMode setmode; + PermaflowMode permaflow; + unsigned int amount; + df::coord size; + + OperationMode() : + brush(B_POINT), paint(P_MAGMA), + flowmode(M_INC), setmode(M_KEEP), permaflow(PF_KEEP), amount(7), + size(1,1,1) + {} +} cur_mode; + +command_result df_liquids_execute(color_ostream &out); +command_result df_liquids_execute(color_ostream &out, OperationMode &mode, df::coord pos); + +static void print_prompt(std::ostream &str, OperationMode &cur_mode) +{ + str <<"[" << paint_mode_name[cur_mode.paint] << ":" << brush_name[cur_mode.brush]; + if (cur_mode.brush == B_RANGE) + str << "(w" << cur_mode.size.x << ":h" << cur_mode.size.y << ":z" << cur_mode.size.z << ")"; + str << ":" << cur_mode.amount << ":f" << modify_mode_name[cur_mode.flowmode] + << ":s" << modify_mode_name[cur_mode.setmode] + << ":pf" << permaflow_name[cur_mode.permaflow] + << "]"; +} command_result df_liquids (color_ostream &out_, vector <string> & parameters) { @@ -117,10 +184,8 @@ command_result df_liquids (color_ostream &out_, vector <string> & parameters) string input = ""; std::stringstream str; - str <<"[" << mode << ":" << brushname; - if (brushname == "range") - str << "(w" << width << ":h" << height << ":z" << z_levels << ")"; - str << ":" << amount << ":" << flowmode << ":" << _setmode << "]#"; + print_prompt(str, cur_mode); + str << "# "; if(out.lineedit(str.str(),input,liquids_hist) == -1) return CR_FAILURE; liquids_hist.add(input); @@ -147,6 +212,10 @@ command_result df_liquids (color_ostream &out_, vector <string> & parameters) << "f+ - make the spawned liquid flow" << endl << "f. - don't change flow state (read state in flow mode)" << endl << "f- - make the spawned liquid static" << endl + << "Permaflow (only for water):" << endl + << "pf. - don't change permaflow state" << endl + << "pf- - make the spawned liquid static" << endl + << "pf[NS][EW] - make the spawned liquid permanently flow" << endl << "0-7 - set liquid amount" << endl << "Brush:" << endl << "point - single tile [p]" << endl @@ -168,38 +237,39 @@ command_result df_liquids (color_ostream &out_, vector <string> & parameters) } else if(command == "m") { - mode = "magma"; + cur_mode.paint = P_MAGMA; } else if(command == "o") { - mode = "obsidian"; + cur_mode.paint = P_OBSIDIAN; } else if(command == "of") { - mode = "obsidian_floor"; + cur_mode.paint = P_OBSIDIAN_FLOOR; } else if(command == "w") { - mode = "water"; + cur_mode.paint = P_WATER; } else if(command == "f") { - mode = "flowbits"; + cur_mode.paint = P_FLOW_BITS; } else if(command == "rs") { - mode = "riversource"; + cur_mode.paint = P_RIVER_SOURCE; } else if(command == "wclean") { - mode = "wclean"; + cur_mode.paint = P_WCLEAN; } else if(command == "point" || command == "p") { - brushname = "point"; + cur_mode.brush = B_POINT; } else if(command == "range" || command == "r") { + int width, height, z_levels; command_result res = parseRectangle(out, commands, 1, commands.size(), width, height, z_levels); if (res != CR_OK) @@ -209,24 +279,26 @@ command_result df_liquids (color_ostream &out_, vector <string> & parameters) if (width == 1 && height == 1 && z_levels == 1) { - brushname = "point"; + cur_mode.brush = B_POINT; + cur_mode.size = df::coord(1, 1, 1); } else { - brushname = "range"; + cur_mode.brush = B_RANGE; + cur_mode.size = df::coord(width, height, z_levels); } } else if(command == "block") { - brushname = "block"; + cur_mode.brush = B_BLOCK; } else if(command == "column") { - brushname = "column"; + cur_mode.brush = B_COLUMN; } else if(command == "flood") { - brushname = "flood"; + cur_mode.brush = B_FLOOD; } else if(command == "q") { @@ -234,45 +306,59 @@ command_result df_liquids (color_ostream &out_, vector <string> & parameters) } else if(command == "f+") { - flowmode = "f+"; + cur_mode.flowmode = M_INC; } else if(command == "f-") { - flowmode = "f-"; + cur_mode.flowmode = M_DEC; } else if(command == "f.") { - flowmode = "f."; + cur_mode.flowmode = M_KEEP; } else if(command == "s+") { - _setmode = "s+"; + cur_mode.setmode = M_INC; } else if(command == "s-") { - _setmode = "s-"; + cur_mode.setmode = M_DEC; } else if(command == "s.") { - _setmode = "s."; + cur_mode.setmode = M_KEEP; + } + else if (command.size() > 2 && memcmp(command.c_str(), "pf", 2) == 0) + { + auto *tail = command.c_str()+2; + for (int pm = PF_KEEP; pm <= PF_SOUTHWEST; pm++) + { + if (strcmp(tail, permaflow_name[pm]) != 0) + continue; + cur_mode.permaflow = PermaflowMode(pm); + tail = NULL; + break; + } + if (tail) + out << command << " : invalid permaflow mode" << endl; } // blah blah, bad code, bite me. else if(command == "0") - amount = 0; + cur_mode.amount = 0; else if(command == "1") - amount = 1; + cur_mode.amount = 1; else if(command == "2") - amount = 2; + cur_mode.amount = 2; else if(command == "3") - amount = 3; + cur_mode.amount = 3; else if(command == "4") - amount = 4; + cur_mode.amount = 4; else if(command == "5") - amount = 5; + cur_mode.amount = 5; else if(command == "6") - amount = 6; + cur_mode.amount = 6; else if(command == "7") - amount = 7; + cur_mode.amount = 7; else if(command.empty()) { df_liquids_execute(out); @@ -298,78 +384,75 @@ command_result df_liquids_here (color_ostream &out, vector <string> & parameters } out.print("Run liquids-here with these parameters: "); - out << "[" << mode << ":" << brushname; - if (brushname == "range") - out << "(w" << width << ":h" << height << ":z" << z_levels << ")"; - out << ":" << amount << ":" << flowmode << ":" << _setmode << "]\n"; + print_prompt(out, cur_mode); + out << endl; return df_liquids_execute(out); } command_result df_liquids_execute(color_ostream &out) { - // create brush type depending on old parameters - Brush * brush; + CoreSuspender suspend; - if (brushname == "point") + auto cursor = Gui::getCursorPos(); + if (!cursor.isValid()) { - brush = new RectangleBrush(1,1,1,0,0,0); - //width = 1; - //height = 1; - //z_levels = 1; + out.printerr("Can't get cursor coords! Make sure you have a cursor active in DF.\n"); + return CR_WRONG_USAGE; } - else if (brushname == "range") - { - brush = new RectangleBrush(width,height,z_levels,0,0,0); - } - else if(brushname == "block") + + auto rv = df_liquids_execute(out, cur_mode, cursor); + if (rv == CR_OK) + out << "OK" << endl; + return rv; +} + +command_result df_liquids_execute(color_ostream &out, OperationMode &cur_mode, df::coord cursor) +{ + // create brush type depending on old parameters + Brush *brush; + + switch (cur_mode.brush) { + case B_POINT: + brush = new RectangleBrush(1,1,1,0,0,0); + break; + case B_RANGE: + brush = new RectangleBrush(cur_mode.size.x,cur_mode.size.y,cur_mode.size.z,0,0,0); + break; + case B_BLOCK: brush = new BlockBrush(); - } - else if(brushname == "column") - { + break; + case B_COLUMN: brush = new ColumnBrush(); - } - else if(brushname == "flood") - { + break; + case B_FLOOD: brush = new FloodBrush(&Core::getInstance()); - } - else - { + break; + default: // this should never happen! out << "Old brushtype is invalid! Resetting to point brush.\n"; - brushname = "point"; - width = 1; - height = 1; - z_levels = 1; - brush = new RectangleBrush(width,height,z_levels,0,0,0); + cur_mode.brush = B_POINT; + brush = new RectangleBrush(1,1,1,0,0,0); } - CoreSuspender suspend; + std::auto_ptr<Brush> brush_ref(brush); - do + if (!Maps::IsValid()) { - if (!Maps::IsValid()) - { - out << "Can't see any DF map loaded." << endl; - break;; - } - int32_t x,y,z; - if(!Gui::getCursorCoords(x,y,z)) - { - out << "Can't get cursor coords! Make sure you have a cursor active in DF." << endl; - break; - } - out << "cursor coords: " << x << "/" << y << "/" << z << endl; - MapCache mcache; - DFHack::DFCoord cursor(x,y,z); - coord_vec all_tiles = brush->points(mcache,cursor); - out << "working..." << endl; + out << "Can't see any DF map loaded." << endl; + return CR_FAILURE; + } - // Force the game to recompute its walkability cache - df::global::world->reindex_pathfinding = true; + MapCache mcache; + coord_vec all_tiles = brush->points(mcache,cursor); - if(mode == "obsidian") + // Force the game to recompute its walkability cache + df::global::world->reindex_pathfinding = true; + + switch (cur_mode.paint) + { + case P_OBSIDIAN: { coord_vec::iterator iter = all_tiles.begin(); while (iter != all_tiles.end()) @@ -383,8 +466,9 @@ command_result df_liquids_execute(color_ostream &out) mcache.setDesignationAt(*iter, des); iter ++; } + break; } - if(mode == "obsidian_floor") + case P_OBSIDIAN_FLOOR: { coord_vec::iterator iter = all_tiles.begin(); while (iter != all_tiles.end()) @@ -392,8 +476,9 @@ command_result df_liquids_execute(color_ostream &out) mcache.setTiletypeAt(*iter, findRandomVariant(tiletype::LavaFloor1)); iter ++; } + break; } - else if(mode == "riversource") + case P_RIVER_SOURCE: { coord_vec::iterator iter = all_tiles.begin(); while (iter != all_tiles.end()) @@ -413,8 +498,9 @@ command_result df_liquids_execute(color_ostream &out) iter++; } + break; } - else if(mode=="wclean") + case P_WCLEAN: { coord_vec::iterator iter = all_tiles.begin(); while (iter != all_tiles.end()) @@ -426,8 +512,11 @@ command_result df_liquids_execute(color_ostream &out) mcache.setDesignationAt(current,des); iter++; } + break; } - else if(mode== "magma" || mode== "water" || mode == "flowbits") + case P_MAGMA: + case P_WATER: + case P_FLOW_BITS: { set <Block *> seen_blocks; coord_vec::iterator iter = all_tiles.begin(); @@ -442,6 +531,7 @@ command_result df_liquids_execute(color_ostream &out) iter ++; continue; } + auto raw_block = block->getRaw(); df::tile_designation des = mcache.designationAt(current); df::tiletype tt = mcache.tiletypeAt(current); // don't put liquids into places where they don't belong... @@ -450,30 +540,29 @@ command_result df_liquids_execute(color_ostream &out) iter++; continue; } - if(mode != "flowbits") + if(cur_mode.paint != P_FLOW_BITS) { unsigned old_amount = des.bits.flow_size; unsigned new_amount = old_amount; df::tile_liquid old_liquid = des.bits.liquid_type; df::tile_liquid new_liquid = old_liquid; // Compute new liquid type and amount - if(_setmode == "s.") - { - new_amount = amount; - } - else if(_setmode == "s+") - { - if(old_amount < amount) - new_amount = amount; - } - else if(_setmode == "s-") + switch (cur_mode.setmode) { - if (old_amount > amount) - new_amount = amount; + case M_KEEP: + new_amount = cur_mode.amount; + break; + case M_INC: + if(old_amount < cur_mode.amount) + new_amount = cur_mode.amount; + break; + case M_DEC: + if (old_amount > cur_mode.amount) + new_amount = cur_mode.amount; } - if (mode == "magma") + if (cur_mode.paint == P_MAGMA) new_liquid = tile_liquid::Magma; - else if (mode == "water") + else if (cur_mode.paint == P_WATER) new_liquid = tile_liquid::Water; // Store new amount and type des.bits.flow_size = new_amount; @@ -502,40 +591,77 @@ command_result df_liquids_execute(color_ostream &out) // request flow engine updates block->enableBlockUpdates(new_amount != old_amount, new_liquid != old_liquid); } + if (cur_mode.permaflow != PF_KEEP && raw_block) + { + auto &flow = raw_block->liquid_flow[current.x&15][current.y&15]; + flow.bits.perm_flow_dir = permaflow_id[cur_mode.permaflow]; + flow.bits.temp_flow_timer = 0; + } seen_blocks.insert(block); iter++; } set <Block *>::iterator biter = seen_blocks.begin(); while (biter != seen_blocks.end()) { - if(flowmode == "f+") + switch (cur_mode.flowmode) { + case M_INC: (*biter)->enableBlockUpdates(true); - } - else if(flowmode == "f-") - { + break; + case M_DEC: if (auto block = (*biter)->getRaw()) { block->flags.bits.update_liquid = false; block->flags.bits.update_liquid_twice = false; } - } - else - { - auto bflags = (*biter)->BlockFlags(); - out << "flow bit 1 = " << bflags.bits.update_liquid << endl; - out << "flow bit 2 = " << bflags.bits.update_liquid_twice << endl; + break; + case M_KEEP: + { + auto bflags = (*biter)->BlockFlags(); + out << "flow bit 1 = " << bflags.bits.update_liquid << endl; + out << "flow bit 2 = " << bflags.bits.update_liquid_twice << endl; + } } biter ++; } + break; } - if(mcache.WriteAll()) - out << "OK" << endl; - else - out << "Something failed horribly! RUN!" << endl; - } while (0); + } + + if(!mcache.WriteAll()) + { + out << "Something failed horribly! RUN!" << endl; + return CR_FAILURE; + } - // cleanup - delete brush; return CR_OK; } + +static int paint(lua_State *L) +{ + df::coord pos; + OperationMode mode; + + lua_settop(L, 8); + Lua::CheckDFAssign(L, &pos, 1); + if (!pos.isValid()) + luaL_argerror(L, 1, "invalid cursor position"); + mode.brush = (BrushType)luaL_checkoption(L, 2, NULL, brush_name); + mode.paint = (PaintMode)luaL_checkoption(L, 3, NULL, paint_mode_name); + mode.amount = luaL_optint(L, 4, 7); + if (mode.amount < 0 || mode.amount > 7) + luaL_argerror(L, 4, "invalid liquid amount"); + if (!lua_isnil(L, 5)) + Lua::CheckDFAssign(L, &mode.size, 5); + mode.setmode = (ModifyMode)luaL_checkoption(L, 6, ".", modify_mode_name); + mode.flowmode = (ModifyMode)luaL_checkoption(L, 7, "+", modify_mode_name); + mode.permaflow = (PermaflowMode)luaL_checkoption(L, 8, ".", permaflow_name); + + lua_pushboolean(L, df_liquids_execute(*Lua::GetOutput(L), mode, pos)); + return 1; +} + +DFHACK_PLUGIN_LUA_COMMANDS { + DFHACK_LUA_COMMAND(paint), + DFHACK_LUA_END +}; diff --git a/plugins/lua/liquids.lua b/plugins/lua/liquids.lua new file mode 100644 index 00000000..22ce4da3 --- /dev/null +++ b/plugins/lua/liquids.lua @@ -0,0 +1,11 @@ +local _ENV = mkmodule('plugins.liquids') + +--[[ + + Native functions: + + * paint(pos,brush,paint,amount,size,setmode,flowmode) + +--]] + +return _ENV
\ No newline at end of file diff --git a/plugins/lua/power-meter.lua b/plugins/lua/power-meter.lua new file mode 100644 index 00000000..310e51c4 --- /dev/null +++ b/plugins/lua/power-meter.lua @@ -0,0 +1,11 @@ +local _ENV = mkmodule('plugins.power-meter') + +--[[ + + Native functions: + + * makePowerMeter(plate_info,min_power,max_power,invert) + +--]] + +return _ENV
\ No newline at end of file diff --git a/plugins/lua/rename.lua b/plugins/lua/rename.lua new file mode 100644 index 00000000..0e7128f5 --- /dev/null +++ b/plugins/lua/rename.lua @@ -0,0 +1,13 @@ +local _ENV = mkmodule('plugins.rename') + +--[[ + + Native functions: + + * canRenameBuilding(building) + * isRenamingBuilding(building) + * renameBuilding(building, name) + +--]] + +return _ENV
\ No newline at end of file diff --git a/plugins/lua/siege-engine.lua b/plugins/lua/siege-engine.lua new file mode 100644 index 00000000..33e120fe --- /dev/null +++ b/plugins/lua/siege-engine.lua @@ -0,0 +1,229 @@ +local _ENV = mkmodule('plugins.siege-engine') + +--[[ + + Native functions: + + * getTargetArea(building) -> point1, point2 + * clearTargetArea(building) + * setTargetArea(building, point1, point2) -> true/false + + * isLinkedToPile(building,pile) -> true/false + * getStockpileLinks(building) -> {pile} + * addStockpileLink(building,pile) -> true/false + * removeStockpileLink(building,pile) -> true/false + + * saveWorkshopProfile(building) -> profile + + * getAmmoItem(building) -> item_type + * setAmmoItem(building,item_type) -> true/false + + * isPassableTile(pos) -> true/false + * isTreeTile(pos) -> true/false + * isTargetableTile(pos) -> true/false + + * getTileStatus(building,pos) -> 'invalid/ok/out_of_range/blocked/semiblocked' + * paintAimScreen(building,view_pos_xyz,left_top_xy,size_xy) + + * canTargetUnit(unit) -> true/false + + proj_info = { target = pos, [delta = float/pos], [factor = int] } + + * projPosAtStep(building,proj_info,step) -> pos + * projPathMetrics(building,proj_info) -> { + hit_type = 'wall/floor/ceiling/map_edge/tree', + collision_step = int, + collision_z_step = int, + goal_distance = int, + goal_step = int/nil, + goal_z_step = int/nil, + status = 'ok/out_of_range/blocked' + } + + * adjustToTarget(building,pos) -> pos,ok=true/false + + * traceUnitPath(unit) -> { {x=int,y=int,z=int[,from=time][,to=time]} } + * unitPosAtTime(unit, time) -> pos + + * proposeUnitHits(building) -> { { + pos=pos, unit=unit, time=float, dist=int, + [lmargin=float,] [rmargin=float,] + } } + + * computeNearbyWeight(building,hits,{[id/unit]=score}[,fname]) + +]] + +Z_STEP_COUNT = 15 +Z_STEP = 1/31 + +function getMetrics(engine, path) + path.metrics = path.metrics or projPathMetrics(engine, path) + return path.metrics +end + +function findShotHeight(engine, target) + local path = { target = target, delta = 0.0 } + + if getMetrics(engine, path).goal_step then + return path + end + + local tpath = { target = target, delta = Z_STEP_COUNT*Z_STEP } + + if getMetrics(engine, tpath).goal_step then + for i = 1,Z_STEP_COUNT-1 do + path = { target = target, delta = i*Z_STEP } + if getMetrics(engine, path).goal_step then + return path + end + end + + return tpath + end + + tpath = { target = target, delta = -Z_STEP_COUNT*Z_STEP } + + if getMetrics(engine, tpath).goal_step then + for i = 1,Z_STEP_COUNT-1 do + path = { target = target, delta = -i*Z_STEP } + if getMetrics(engine, path).goal_step then + return path + end + end + + return tpath + end +end + +function findReachableTargets(engine, targets) + local reachable = {} + for _,tgt in ipairs(targets) do + tgt.path = findShotHeight(engine, tgt.pos) + if tgt.path then + table.insert(reachable, tgt) + end + end + return reachable +end + +recent_targets = recent_targets or {} + +if dfhack.is_core_context then + dfhack.onStateChange[_ENV] = function(code) + if code == SC_MAP_LOADED then + recent_targets = {} + end + end +end + +function saveRecent(unit) + local id = unit.id + local tgt = recent_targets + tgt[id] = (tgt[id] or 0) + 1 + dfhack.timeout(3, 'days', function() + tgt[id] = math.max(0, tgt[id]-1) + end) +end + +function getBaseUnitWeight(unit) + if dfhack.units.isCitizen(unit) then + return -10 + elseif unit.flags1.diplomat or unit.flags1.merchant then + return -2 + elseif unit.flags1.tame and unit.civ_id == df.global.ui.civ_id then + return -1 + else + local rv = 1 + if unit.flags1.marauder then rv = rv + 0.5 end + if unit.flags1.active_invader then rv = rv + 1 end + if unit.flags1.invader_origin then rv = rv + 1 end + if unit.flags1.invades then rv = rv + 1 end + if unit.flags1.hidden_ambusher then rv = rv + 1 end + return rv + end +end + +function getUnitWeight(unit) + local base = getBaseUnitWeight(unit) + return base * math.pow(0.7, recent_targets[unit.id] or 0) +end + +function unitWeightCache() + local cache = {} + return cache, function(unit) + local id = unit.id + cache[id] = cache[id] or getUnitWeight(unit) + return cache[id] + end +end + +function scoreTargets(engine, reachable) + local ucache, get_weight = unitWeightCache() + + for _,tgt in ipairs(reachable) do + tgt.score = get_weight(tgt.unit) + if tgt.lmargin and tgt.lmargin < 3 then + tgt.score = tgt.score * tgt.lmargin / 3 + end + if tgt.rmargin and tgt.rmargin < 3 then + tgt.score = tgt.score * tgt.rmargin / 3 + end + end + + computeNearbyWeight(engine, reachable, ucache) + + for _,tgt in ipairs(reachable) do + tgt.score = (tgt.score + tgt.nearby_weight*0.7) * math.pow(0.995, tgt.time/3) + end + + table.sort(reachable, function(a,b) + return a.score > b.score or (a.score == b.score and a.time < b.time) + end) +end + +function pickUniqueTargets(reachable) + local unique = {} + + if #reachable > 0 then + local pos_table = {} + local first_score = reachable[1].score + + for i,tgt in ipairs(reachable) do + if tgt.score < 0 or tgt.score < 0.1*first_score then + break + end + local x,y,z = pos2xyz(tgt.pos) + local key = x..':'..y..':'..z + if pos_table[key] then + table.insert(pos_table[key].units, tgt.unit) + else + table.insert(unique, tgt) + pos_table[key] = tgt + tgt.units = { tgt.unit } + end + end + end + + return unique +end + +function doAimProjectile(engine, item, target_min, target_max, skill) + print(item, df.skill_rating[skill]) + + local targets = proposeUnitHits(engine) + local reachable = findReachableTargets(engine, targets) + scoreTargets(engine, reachable) + local unique = pickUniqueTargets(reachable) + + if #unique > 0 then + local cnt = math.max(math.min(#unique,5), math.min(10, math.floor(#unique/2))) + local rnd = math.random(cnt) + for _,u in ipairs(unique[rnd].units) do + saveRecent(u) + end + return unique[rnd].path + end +end + +return _ENV
\ No newline at end of file diff --git a/plugins/lua/sort/items.lua b/plugins/lua/sort/items.lua index 13b62ff9..5c6d4a5b 100644 --- a/plugins/lua/sort/items.lua +++ b/plugins/lua/sort/items.lua @@ -23,12 +23,18 @@ orders.description = { end } -orders.quality = { +orders.base_quality = { key = function(item) return item:getQuality() end } +orders.quality = { + key = function(item) + return item:getOverallQuality() + end +} + orders.improvement = { key = function(item) return item:getImprovementQuality() diff --git a/plugins/manipulator.cpp b/plugins/manipulator.cpp new file mode 100644 index 00000000..953cf2ba --- /dev/null +++ b/plugins/manipulator.cpp @@ -0,0 +1,1194 @@ +// Dwarf Manipulator - a Therapist-style labor editor + +#include "Core.h" +#include <Console.h> +#include <Export.h> +#include <PluginManager.h> +#include <MiscUtils.h> +#include <modules/Screen.h> +#include <modules/Translation.h> +#include <modules/Units.h> +#include <vector> +#include <string> +#include <set> +#include <algorithm> + +#include <VTableInterpose.h> +#include "df/world.h" +#include "df/ui.h" +#include "df/graphic.h" +#include "df/enabler.h" +#include "df/viewscreen_unitlistst.h" +#include "df/interface_key.h" +#include "df/unit.h" +#include "df/unit_soul.h" +#include "df/unit_skill.h" +#include "df/creature_graphics_role.h" +#include "df/creature_raw.h" +#include "df/caste_raw.h" + +using std::set; +using std::vector; +using std::string; + +using namespace DFHack; +using namespace df::enums; + +using df::global::world; +using df::global::ui; +using df::global::gps; +using df::global::enabler; + +struct SkillLevel +{ + const char *name; + int points; + char abbrev; +}; + +#define NUM_SKILL_LEVELS (sizeof(skill_levels) / sizeof(SkillLevel)) + +// The various skill rankings. Zero skill is hardcoded to "Not" and '-'. +const SkillLevel skill_levels[] = { + {"Dabbling", 500, '0'}, + {"Novice", 600, '1'}, + {"Adequate", 700, '2'}, + {"Competent", 800, '3'}, + {"Skilled", 900, '4'}, + {"Proficient", 1000, '5'}, + {"Talented", 1100, '6'}, + {"Adept", 1200, '7'}, + {"Expert", 1300, '8'}, + {"Professional",1400, '9'}, + {"Accomplished",1500, 'A'}, + {"Great", 1600, 'B'}, + {"Master", 1700, 'C'}, + {"High Master", 1800, 'D'}, + {"Grand Master",1900, 'E'}, + {"Legendary", 2000, 'U'}, + {"Legendary+1", 2100, 'V'}, + {"Legendary+2", 2200, 'W'}, + {"Legendary+3", 2300, 'X'}, + {"Legendary+4", 2400, 'Y'}, + {"Legendary+5", 0, 'Z'} +}; + +struct SkillColumn +{ + int group; // for navigation and mass toggling + int8_t color; // for column headers + df::profession profession; // to display graphical tiles + df::unit_labor labor; // toggled when pressing Enter + df::job_skill skill; // displayed rating + char label[3]; // column header + bool special; // specified labor is mutually exclusive with all other special labors +}; + +#define NUM_COLUMNS (sizeof(columns) / sizeof(SkillColumn)) + +// All of the skill/labor columns we want to display. +const SkillColumn columns[] = { +// Mining + {0, 7, profession::MINER, unit_labor::MINE, job_skill::MINING, "Mi", true}, +// Woodworking + {1, 14, profession::CARPENTER, unit_labor::CARPENTER, job_skill::CARPENTRY, "Ca"}, + {1, 14, profession::BOWYER, unit_labor::BOWYER, job_skill::BOWYER, "Bw"}, + {1, 14, profession::WOODCUTTER, unit_labor::CUTWOOD, job_skill::WOODCUTTING, "WC", true}, +// Stoneworking + {2, 15, profession::MASON, unit_labor::MASON, job_skill::MASONRY, "Ma"}, + {2, 15, profession::ENGRAVER, unit_labor::DETAIL, job_skill::DETAILSTONE, "En"}, +// Hunting/Related + {3, 2, profession::ANIMAL_TRAINER, unit_labor::ANIMALTRAIN, job_skill::ANIMALTRAIN, "Tn"}, + {3, 2, profession::ANIMAL_CARETAKER, unit_labor::ANIMALCARE, job_skill::ANIMALCARE, "Ca"}, + {3, 2, profession::HUNTER, unit_labor::HUNT, job_skill::SNEAK, "Hu", true}, + {3, 2, profession::TRAPPER, unit_labor::TRAPPER, job_skill::TRAPPING, "Tr"}, + {3, 2, profession::ANIMAL_DISSECTOR, unit_labor::DISSECT_VERMIN, job_skill::DISSECT_VERMIN, "Di"}, +// Healthcare + {4, 5, profession::DIAGNOSER, unit_labor::DIAGNOSE, job_skill::DIAGNOSE, "Di"}, + {4, 5, profession::SURGEON, unit_labor::SURGERY, job_skill::SURGERY, "Su"}, + {4, 5, profession::BONE_SETTER, unit_labor::BONE_SETTING, job_skill::SET_BONE, "Bo"}, + {4, 5, profession::SUTURER, unit_labor::SUTURING, job_skill::SUTURE, "St"}, + {4, 5, profession::DOCTOR, unit_labor::DRESSING_WOUNDS, job_skill::DRESS_WOUNDS, "Dr"}, + {4, 5, profession::NONE, unit_labor::FEED_WATER_CIVILIANS, job_skill::NONE, "Fd"}, + {4, 5, profession::NONE, unit_labor::RECOVER_WOUNDED, job_skill::NONE, "Re"}, +// Farming/Related + {5, 6, profession::BUTCHER, unit_labor::BUTCHER, job_skill::BUTCHER, "Bu"}, + {5, 6, profession::TANNER, unit_labor::TANNER, job_skill::TANNER, "Ta"}, + {5, 6, profession::PLANTER, unit_labor::PLANT, job_skill::PLANT, "Gr"}, + {5, 6, profession::DYER, unit_labor::DYER, job_skill::DYER, "Dy"}, + {5, 6, profession::SOAP_MAKER, unit_labor::SOAP_MAKER, job_skill::SOAP_MAKING, "So"}, + {5, 6, profession::WOOD_BURNER, unit_labor::BURN_WOOD, job_skill::WOOD_BURNING, "WB"}, + {5, 6, profession::POTASH_MAKER, unit_labor::POTASH_MAKING, job_skill::POTASH_MAKING, "Po"}, + {5, 6, profession::LYE_MAKER, unit_labor::LYE_MAKING, job_skill::LYE_MAKING, "Ly"}, + {5, 6, profession::MILLER, unit_labor::MILLER, job_skill::MILLING, "Ml"}, + {5, 6, profession::BREWER, unit_labor::BREWER, job_skill::BREWING, "Br"}, + {5, 6, profession::HERBALIST, unit_labor::HERBALIST, job_skill::HERBALISM, "He"}, + {5, 6, profession::THRESHER, unit_labor::PROCESS_PLANT, job_skill::PROCESSPLANTS, "Th"}, + {5, 6, profession::CHEESE_MAKER, unit_labor::MAKE_CHEESE, job_skill::CHEESEMAKING, "Ch"}, + {5, 6, profession::MILKER, unit_labor::MILK, job_skill::MILK, "Mk"}, + {5, 6, profession::SHEARER, unit_labor::SHEARER, job_skill::SHEARING, "Sh"}, + {5, 6, profession::SPINNER, unit_labor::SPINNER, job_skill::SPINNING, "Sp"}, + {5, 6, profession::COOK, unit_labor::COOK, job_skill::COOK, "Co"}, + {5, 6, profession::PRESSER, unit_labor::PRESSING, job_skill::PRESSING, "Pr"}, + {5, 6, profession::BEEKEEPER, unit_labor::BEEKEEPING, job_skill::BEEKEEPING, "Be"}, +// Fishing/Related + {6, 1, profession::FISHERMAN, unit_labor::FISH, job_skill::FISH, "Fi"}, + {6, 1, profession::FISH_CLEANER, unit_labor::CLEAN_FISH, job_skill::PROCESSFISH, "Cl"}, + {6, 1, profession::FISH_DISSECTOR, unit_labor::DISSECT_FISH, job_skill::DISSECT_FISH, "Di"}, +// Metalsmithing + {7, 8, profession::FURNACE_OPERATOR, unit_labor::SMELT, job_skill::SMELT, "Fu"}, + {7, 8, profession::WEAPONSMITH, unit_labor::FORGE_WEAPON, job_skill::FORGE_WEAPON, "We"}, + {7, 8, profession::ARMORER, unit_labor::FORGE_ARMOR, job_skill::FORGE_ARMOR, "Ar"}, + {7, 8, profession::BLACKSMITH, unit_labor::FORGE_FURNITURE, job_skill::FORGE_FURNITURE, "Bl"}, + {7, 8, profession::METALCRAFTER, unit_labor::METAL_CRAFT, job_skill::METALCRAFT, "Cr"}, +// Jewelry + {8, 10, profession::GEM_CUTTER, unit_labor::CUT_GEM, job_skill::CUTGEM, "Cu"}, + {8, 10, profession::GEM_SETTER, unit_labor::ENCRUST_GEM, job_skill::ENCRUSTGEM, "Se"}, +// Crafts + {9, 9, profession::LEATHERWORKER, unit_labor::LEATHER, job_skill::LEATHERWORK, "Le"}, + {9, 9, profession::WOODCRAFTER, unit_labor::WOOD_CRAFT, job_skill::WOODCRAFT, "Wo"}, + {9, 9, profession::STONECRAFTER, unit_labor::STONE_CRAFT, job_skill::STONECRAFT, "St"}, + {9, 9, profession::BONE_CARVER, unit_labor::BONE_CARVE, job_skill::BONECARVE, "Bo"}, + {9, 9, profession::GLASSMAKER, unit_labor::GLASSMAKER, job_skill::GLASSMAKER, "Gl"}, + {9, 9, profession::WEAVER, unit_labor::WEAVER, job_skill::WEAVING, "We"}, + {9, 9, profession::CLOTHIER, unit_labor::CLOTHESMAKER, job_skill::CLOTHESMAKING, "Cl"}, + {9, 9, profession::STRAND_EXTRACTOR, unit_labor::EXTRACT_STRAND, job_skill::EXTRACT_STRAND, "Ad"}, + {9, 9, profession::POTTER, unit_labor::POTTERY, job_skill::POTTERY, "Po"}, + {9, 9, profession::GLAZER, unit_labor::GLAZING, job_skill::GLAZING, "Gl"}, + {9, 9, profession::WAX_WORKER, unit_labor::WAX_WORKING, job_skill::WAX_WORKING, "Wx"}, +// Engineering + {10, 12, profession::SIEGE_ENGINEER, unit_labor::SIEGECRAFT, job_skill::SIEGECRAFT, "En"}, + {10, 12, profession::SIEGE_OPERATOR, unit_labor::SIEGEOPERATE, job_skill::SIEGEOPERATE, "Op"}, + {10, 12, profession::MECHANIC, unit_labor::MECHANIC, job_skill::MECHANICS, "Me"}, + {10, 12, profession::PUMP_OPERATOR, unit_labor::OPERATE_PUMP, job_skill::OPERATE_PUMP, "Pu"}, +// Hauling + {11, 3, profession::NONE, unit_labor::HAUL_STONE, job_skill::NONE, "St"}, + {11, 3, profession::NONE, unit_labor::HAUL_WOOD, job_skill::NONE, "Wo"}, + {11, 3, profession::NONE, unit_labor::HAUL_ITEM, job_skill::NONE, "It"}, + {11, 3, profession::NONE, unit_labor::HAUL_BODY, job_skill::NONE, "Bu"}, + {11, 3, profession::NONE, unit_labor::HAUL_FOOD, job_skill::NONE, "Fo"}, + {11, 3, profession::NONE, unit_labor::HAUL_REFUSE, job_skill::NONE, "Re"}, + {11, 3, profession::NONE, unit_labor::HAUL_FURNITURE, job_skill::NONE, "Fu"}, + {11, 3, profession::NONE, unit_labor::HAUL_ANIMAL, job_skill::NONE, "An"}, + {11, 3, profession::NONE, unit_labor::PUSH_HAUL_VEHICLE, job_skill::NONE, "Ve"}, +// Other Jobs + {12, 4, profession::ARCHITECT, unit_labor::ARCHITECT, job_skill::DESIGNBUILDING, "Ar"}, + {12, 4, profession::ALCHEMIST, unit_labor::ALCHEMIST, job_skill::ALCHEMY, "Al"}, + {12, 4, profession::NONE, unit_labor::CLEAN, job_skill::NONE, "Cl"}, +// Military - Weapons + {13, 7, profession::WRESTLER, unit_labor::NONE, job_skill::WRESTLING, "Wr"}, + {13, 7, profession::AXEMAN, unit_labor::NONE, job_skill::AXE, "Ax"}, + {13, 7, profession::SWORDSMAN, unit_labor::NONE, job_skill::SWORD, "Sw"}, + {13, 7, profession::MACEMAN, unit_labor::NONE, job_skill::MACE, "Mc"}, + {13, 7, profession::HAMMERMAN, unit_labor::NONE, job_skill::HAMMER, "Ha"}, + {13, 7, profession::SPEARMAN, unit_labor::NONE, job_skill::SPEAR, "Sp"}, + {13, 7, profession::CROSSBOWMAN, unit_labor::NONE, job_skill::CROSSBOW, "Cb"}, + {13, 7, profession::THIEF, unit_labor::NONE, job_skill::DAGGER, "Kn"}, + {13, 7, profession::BOWMAN, unit_labor::NONE, job_skill::BOW, "Bo"}, + {13, 7, profession::BLOWGUNMAN, unit_labor::NONE, job_skill::BLOWGUN, "Bl"}, + {13, 7, profession::PIKEMAN, unit_labor::NONE, job_skill::PIKE, "Pk"}, + {13, 7, profession::LASHER, unit_labor::NONE, job_skill::WHIP, "La"}, +// Military - Other Combat + {14, 15, profession::NONE, unit_labor::NONE, job_skill::BITE, "Bi"}, + {14, 15, profession::NONE, unit_labor::NONE, job_skill::GRASP_STRIKE, "St"}, + {14, 15, profession::NONE, unit_labor::NONE, job_skill::STANCE_STRIKE, "Ki"}, + {14, 15, profession::NONE, unit_labor::NONE, job_skill::MISC_WEAPON, "Mi"}, + {14, 15, profession::NONE, unit_labor::NONE, job_skill::MELEE_COMBAT, "Fg"}, + {14, 15, profession::NONE, unit_labor::NONE, job_skill::RANGED_COMBAT, "Ac"}, + {14, 15, profession::NONE, unit_labor::NONE, job_skill::ARMOR, "Ar"}, + {14, 15, profession::NONE, unit_labor::NONE, job_skill::SHIELD, "Sh"}, + {14, 15, profession::NONE, unit_labor::NONE, job_skill::DODGING, "Do"}, +// Military - Misc + {15, 8, profession::NONE, unit_labor::NONE, job_skill::LEADERSHIP, "Ld"}, + {15, 8, profession::NONE, unit_labor::NONE, job_skill::TEACHING, "Te"}, + {15, 8, profession::NONE, unit_labor::NONE, job_skill::KNOWLEDGE_ACQUISITION, "St"}, + {15, 8, profession::NONE, unit_labor::NONE, job_skill::DISCIPLINE, "Di"}, + {15, 8, profession::NONE, unit_labor::NONE, job_skill::CONCENTRATION, "Co"}, + {15, 8, profession::NONE, unit_labor::NONE, job_skill::SITUATIONAL_AWARENESS, "Ob"}, + {15, 8, profession::NONE, unit_labor::NONE, job_skill::COORDINATION, "Cr"}, + {15, 8, profession::NONE, unit_labor::NONE, job_skill::BALANCE, "Ba"}, +// Social + {16, 3, profession::NONE, unit_labor::NONE, job_skill::PERSUASION, "Pe"}, + {16, 3, profession::NONE, unit_labor::NONE, job_skill::NEGOTIATION, "Ne"}, + {16, 3, profession::NONE, unit_labor::NONE, job_skill::JUDGING_INTENT, "Ju"}, + {16, 3, profession::NONE, unit_labor::NONE, job_skill::LYING, "Li"}, + {16, 3, profession::NONE, unit_labor::NONE, job_skill::INTIMIDATION, "In"}, + {16, 3, profession::NONE, unit_labor::NONE, job_skill::CONVERSATION, "Cn"}, + {16, 3, profession::NONE, unit_labor::NONE, job_skill::COMEDY, "Cm"}, + {16, 3, profession::NONE, unit_labor::NONE, job_skill::FLATTERY, "Fl"}, + {16, 3, profession::NONE, unit_labor::NONE, job_skill::CONSOLE, "Cs"}, + {16, 3, profession::NONE, unit_labor::NONE, job_skill::PACIFY, "Pc"}, +// Noble + {17, 5, profession::TRADER, unit_labor::NONE, job_skill::APPRAISAL, "Ap"}, + {17, 5, profession::ADMINISTRATOR, unit_labor::NONE, job_skill::ORGANIZATION, "Or"}, + {17, 5, profession::CLERK, unit_labor::NONE, job_skill::RECORD_KEEPING, "RK"}, +// Miscellaneous + {18, 3, profession::NONE, unit_labor::NONE, job_skill::THROW, "Th"}, + {18, 3, profession::NONE, unit_labor::NONE, job_skill::CRUTCH_WALK, "CW"}, + {18, 3, profession::NONE, unit_labor::NONE, job_skill::SWIMMING, "Sw"}, + {18, 3, profession::NONE, unit_labor::NONE, job_skill::KNAPPING, "Kn"}, + + {19, 6, profession::NONE, unit_labor::NONE, job_skill::WRITING, "Wr"}, + {19, 6, profession::NONE, unit_labor::NONE, job_skill::PROSE, "Pr"}, + {19, 6, profession::NONE, unit_labor::NONE, job_skill::POETRY, "Po"}, + {19, 6, profession::NONE, unit_labor::NONE, job_skill::READING, "Rd"}, + {19, 6, profession::NONE, unit_labor::NONE, job_skill::SPEAKING, "Sp"}, + + {20, 5, profession::NONE, unit_labor::NONE, job_skill::MILITARY_TACTICS, "MT"}, + {20, 5, profession::NONE, unit_labor::NONE, job_skill::TRACKING, "Tr"}, + {20, 5, profession::NONE, unit_labor::NONE, job_skill::MAGIC_NATURE, "Dr"}, +}; + +struct UnitInfo +{ + df::unit *unit; + bool allowEdit; + string name; + string transname; + string profession; + int8_t color; + int active_index; +}; + +enum altsort_mode { + ALTSORT_NAME, + ALTSORT_PROFESSION, + ALTSORT_HAPPINESS, + ALTSORT_ARRIVAL, + ALTSORT_MAX +}; + +bool descending; +df::job_skill sort_skill; +df::unit_labor sort_labor; + +bool sortByName (const UnitInfo *d1, const UnitInfo *d2) +{ + if (descending) + return (d1->name > d2->name); + else + return (d1->name < d2->name); +} + +bool sortByProfession (const UnitInfo *d1, const UnitInfo *d2) +{ + if (descending) + return (d1->profession > d2->profession); + else + return (d1->profession < d2->profession); +} + +bool sortByHappiness (const UnitInfo *d1, const UnitInfo *d2) +{ + if (descending) + return (d1->unit->status.happiness > d2->unit->status.happiness); + else + return (d1->unit->status.happiness < d2->unit->status.happiness); +} + +bool sortByArrival (const UnitInfo *d1, const UnitInfo *d2) +{ + if (descending) + return (d1->active_index > d2->active_index); + else + return (d1->active_index < d2->active_index); +} + +bool sortBySkill (const UnitInfo *d1, const UnitInfo *d2) +{ + if (sort_skill != job_skill::NONE) + { + df::unit_skill *s1 = binsearch_in_vector<df::unit_skill,df::enum_field<df::job_skill,int16_t>>(d1->unit->status.current_soul->skills, &df::unit_skill::id, sort_skill); + df::unit_skill *s2 = binsearch_in_vector<df::unit_skill,df::enum_field<df::job_skill,int16_t>>(d2->unit->status.current_soul->skills, &df::unit_skill::id, sort_skill); + int l1 = s1 ? s1->rating : 0; + int l2 = s2 ? s2->rating : 0; + int e1 = s1 ? s1->experience : 0; + int e2 = s2 ? s2->experience : 0; + if (descending) + { + if (l1 != l2) + return l1 > l2; + if (e1 != e2) + return e1 > e2; + } + else + { + if (l1 != l2) + return l1 < l2; + if (e1 != e2) + return e1 < e2; + } + } + if (sort_labor != unit_labor::NONE) + { + if (descending) + return d1->unit->status.labors[sort_labor] > d2->unit->status.labors[sort_labor]; + else + return d1->unit->status.labors[sort_labor] < d2->unit->status.labors[sort_labor]; + } + return sortByName(d1, d2); +} + +enum display_columns { + DISP_COLUMN_HAPPINESS, + DISP_COLUMN_NAME, + DISP_COLUMN_PROFESSION, + DISP_COLUMN_LABORS, + DISP_COLUMN_MAX, +}; + +class viewscreen_unitlaborsst : public dfhack_viewscreen { +public: + void feed(set<df::interface_key> *events); + + void logic() { + dfhack_viewscreen::logic(); + if (do_refresh_names) + refreshNames(); + } + + void render(); + void resize(int w, int h) { calcSize(); } + + void help() { } + + std::string getFocusString() { return "unitlabors"; } + + df::unit *getSelectedUnit(); + + viewscreen_unitlaborsst(vector<df::unit*> &src, int cursor_pos); + ~viewscreen_unitlaborsst() { }; + +protected: + vector<UnitInfo *> units; + altsort_mode altsort; + + bool do_refresh_names; + int first_row, sel_row, num_rows; + int first_column, sel_column; + + int col_widths[DISP_COLUMN_MAX]; + int col_offsets[DISP_COLUMN_MAX]; + + void refreshNames(); + void calcSize (); +}; + +viewscreen_unitlaborsst::viewscreen_unitlaborsst(vector<df::unit*> &src, int cursor_pos) +{ + std::map<df::unit*,int> active_idx; + auto &active = world->units.active; + for (size_t i = 0; i < active.size(); i++) + active_idx[active[i]] = i; + + for (size_t i = 0; i < src.size(); i++) + { + UnitInfo *cur = new UnitInfo; + df::unit *unit = src[i]; + cur->unit = unit; + cur->allowEdit = true; + cur->active_index = active_idx[unit]; + + if (unit->race != ui->race_id) + cur->allowEdit = false; + + if (unit->civ_id != ui->civ_id) + cur->allowEdit = false; + + if (unit->flags1.bits.dead) + cur->allowEdit = false; + + if (!ENUM_ATTR(profession, can_assign_labor, unit->profession)) + cur->allowEdit = false; + + cur->color = Units::getProfessionColor(unit); + + units.push_back(cur); + } + altsort = ALTSORT_NAME; + first_column = sel_column = 0; + + refreshNames(); + + first_row = 0; + sel_row = cursor_pos; + calcSize(); + + // recalculate first_row to roughly match the original layout + first_row = 0; + while (first_row < sel_row - num_rows + 1) + first_row += num_rows + 2; + // make sure the selection stays visible + if (first_row > sel_row) + first_row = sel_row - num_rows + 1; + // don't scroll beyond the end + if (first_row > units.size() - num_rows) + first_row = units.size() - num_rows; +} + +void viewscreen_unitlaborsst::refreshNames() +{ + do_refresh_names = false; + + for (size_t i = 0; i < units.size(); i++) + { + UnitInfo *cur = units[i]; + df::unit *unit = cur->unit; + + cur->name = Translation::TranslateName(&unit->name, false); + cur->transname = Translation::TranslateName(&unit->name, true); + cur->profession = Units::getProfessionName(unit); + } + calcSize(); +} + +void viewscreen_unitlaborsst::calcSize() +{ + num_rows = gps->dimy - 10; + if (num_rows > units.size()) + num_rows = units.size(); + + int num_columns = gps->dimx - DISP_COLUMN_MAX - 1; + + // min/max width of columns + int col_minwidth[DISP_COLUMN_MAX]; + int col_maxwidth[DISP_COLUMN_MAX]; + col_minwidth[DISP_COLUMN_HAPPINESS] = 4; + col_maxwidth[DISP_COLUMN_HAPPINESS] = 4; + col_minwidth[DISP_COLUMN_NAME] = 0; + col_maxwidth[DISP_COLUMN_NAME] = 0; + col_minwidth[DISP_COLUMN_PROFESSION] = 0; + col_maxwidth[DISP_COLUMN_PROFESSION] = 0; + col_minwidth[DISP_COLUMN_LABORS] = num_columns*3/5; // 60% + col_maxwidth[DISP_COLUMN_LABORS] = NUM_COLUMNS; + + // get max_name/max_prof from strings length + for (size_t i = 0; i < units.size(); i++) + { + if (col_maxwidth[DISP_COLUMN_NAME] < units[i]->name.size()) + col_maxwidth[DISP_COLUMN_NAME] = units[i]->name.size(); + if (col_maxwidth[DISP_COLUMN_PROFESSION] < units[i]->profession.size()) + col_maxwidth[DISP_COLUMN_PROFESSION] = units[i]->profession.size(); + } + + // check how much room we have + int width_min = 0, width_max = 0; + for (int i = 0; i < DISP_COLUMN_MAX; i++) + { + width_min += col_minwidth[i]; + width_max += col_maxwidth[i]; + } + + if (width_max <= num_columns) + { + // lots of space, distribute leftover (except last column) + int col_margin = (num_columns - width_max) / (DISP_COLUMN_MAX-1); + int col_margin_r = (num_columns - width_max) % (DISP_COLUMN_MAX-1); + for (int i = DISP_COLUMN_MAX-1; i>=0; i--) + { + col_widths[i] = col_maxwidth[i]; + + if (i < DISP_COLUMN_MAX-1) + { + col_widths[i] += col_margin; + + if (col_margin_r) + { + col_margin_r--; + col_widths[i]++; + } + } + } + } + else if (width_min <= num_columns) + { + // constrained, give between min and max to every column + int space = num_columns - width_min; + // max size columns not yet seen may consume + int next_consume_max = width_max - width_min; + + for (int i = 0; i < DISP_COLUMN_MAX; i++) + { + // divide evenly remaining space + int col_margin = space / (DISP_COLUMN_MAX-i); + + // take more if the columns after us cannot + next_consume_max -= (col_maxwidth[i]-col_minwidth[i]); + if (col_margin < space-next_consume_max) + col_margin = space - next_consume_max; + + // no more than maxwidth + if (col_margin > col_maxwidth[i] - col_minwidth[i]) + col_margin = col_maxwidth[i] - col_minwidth[i]; + + col_widths[i] = col_minwidth[i] + col_margin; + + space -= col_margin; + } + } + else + { + // should not happen, min screen is 80x25 + int space = num_columns; + for (int i = 0; i < DISP_COLUMN_MAX; i++) + { + col_widths[i] = space / (DISP_COLUMN_MAX-i); + space -= col_widths[i]; + } + } + + for (int i = 0; i < DISP_COLUMN_MAX; i++) + { + if (i == 0) + col_offsets[i] = 1; + else + col_offsets[i] = col_offsets[i - 1] + col_widths[i - 1] + 1; + } + + // don't adjust scroll position immediately after the window opened + if (units.size() == 0) + return; + + // if the window grows vertically, scroll upward to eliminate blank rows from the bottom + if (first_row > units.size() - num_rows) + first_row = units.size() - num_rows; + + // if it shrinks vertically, scroll downward to keep the cursor visible + if (first_row < sel_row - num_rows + 1) + first_row = sel_row - num_rows + 1; + + // if the window grows horizontally, scroll to the left to eliminate blank columns from the right + if (first_column > NUM_COLUMNS - col_widths[DISP_COLUMN_LABORS]) + first_column = NUM_COLUMNS - col_widths[DISP_COLUMN_LABORS]; + + // if it shrinks horizontally, scroll to the right to keep the cursor visible + if (first_column < sel_column - col_widths[DISP_COLUMN_LABORS] + 1) + first_column = sel_column - col_widths[DISP_COLUMN_LABORS] + 1; +} + +void viewscreen_unitlaborsst::feed(set<df::interface_key> *events) +{ + bool leave_all = events->count(interface_key::LEAVESCREEN_ALL); + if (leave_all || events->count(interface_key::LEAVESCREEN)) + { + events->clear(); + Screen::dismiss(this); + if (leave_all) + { + events->insert(interface_key::LEAVESCREEN); + parent->feed(events); + events->clear(); + } + return; + } + + if (!units.size()) + return; + + if (do_refresh_names) + refreshNames(); + + int old_sel_row = sel_row; + + if (events->count(interface_key::CURSOR_UP) || events->count(interface_key::CURSOR_UPLEFT) || events->count(interface_key::CURSOR_UPRIGHT)) + sel_row--; + if (events->count(interface_key::CURSOR_UP_FAST) || events->count(interface_key::CURSOR_UPLEFT_FAST) || events->count(interface_key::CURSOR_UPRIGHT_FAST)) + sel_row -= 10; + if (events->count(interface_key::CURSOR_DOWN) || events->count(interface_key::CURSOR_DOWNLEFT) || events->count(interface_key::CURSOR_DOWNRIGHT)) + sel_row++; + if (events->count(interface_key::CURSOR_DOWN_FAST) || events->count(interface_key::CURSOR_DOWNLEFT_FAST) || events->count(interface_key::CURSOR_DOWNRIGHT_FAST)) + sel_row += 10; + + if ((sel_row > 0) && events->count(interface_key::CURSOR_UP_Z_AUX)) + { + sel_row = 0; + } + if ((sel_row < units.size()-1) && events->count(interface_key::CURSOR_DOWN_Z_AUX)) + { + sel_row = units.size()-1; + } + + if (sel_row < 0) + { + if (old_sel_row == 0 && events->count(interface_key::CURSOR_UP)) + sel_row = units.size() - 1; + else + sel_row = 0; + } + + if (sel_row > units.size() - 1) + { + if (old_sel_row == units.size()-1 && events->count(interface_key::CURSOR_DOWN)) + sel_row = 0; + else + sel_row = units.size() - 1; + } + + if (sel_row < first_row) + first_row = sel_row; + if (first_row < sel_row - num_rows + 1) + first_row = sel_row - num_rows + 1; + + if (events->count(interface_key::CURSOR_LEFT) || events->count(interface_key::CURSOR_UPLEFT) || events->count(interface_key::CURSOR_DOWNLEFT)) + sel_column--; + if (events->count(interface_key::CURSOR_LEFT_FAST) || events->count(interface_key::CURSOR_UPLEFT_FAST) || events->count(interface_key::CURSOR_DOWNLEFT_FAST)) + sel_column -= 10; + if (events->count(interface_key::CURSOR_RIGHT) || events->count(interface_key::CURSOR_UPRIGHT) || events->count(interface_key::CURSOR_DOWNRIGHT)) + sel_column++; + if (events->count(interface_key::CURSOR_RIGHT_FAST) || events->count(interface_key::CURSOR_UPRIGHT_FAST) || events->count(interface_key::CURSOR_DOWNRIGHT_FAST)) + sel_column += 10; + + if ((sel_column != 0) && events->count(interface_key::CURSOR_UP_Z)) + { + // go to beginning of current column group; if already at the beginning, go to the beginning of the previous one + sel_column--; + int cur = columns[sel_column].group; + while ((sel_column > 0) && columns[sel_column - 1].group == cur) + sel_column--; + } + if ((sel_column != NUM_COLUMNS - 1) && events->count(interface_key::CURSOR_DOWN_Z)) + { + // go to beginning of next group + int cur = columns[sel_column].group; + int next = sel_column+1; + while ((next < NUM_COLUMNS) && (columns[next].group == cur)) + next++; + if ((next < NUM_COLUMNS) && (columns[next].group != cur)) + sel_column = next; + } + + if (sel_column < 0) + sel_column = 0; + if (sel_column > NUM_COLUMNS - 1) + sel_column = NUM_COLUMNS - 1; + + if (events->count(interface_key::CURSOR_DOWN_Z) || events->count(interface_key::CURSOR_UP_Z)) + { + // when moving by group, ensure the whole group is shown onscreen + int endgroup_column = sel_column; + while ((endgroup_column < NUM_COLUMNS-1) && columns[endgroup_column+1].group == columns[sel_column].group) + endgroup_column++; + + if (first_column < endgroup_column - col_widths[DISP_COLUMN_LABORS] + 1) + first_column = endgroup_column - col_widths[DISP_COLUMN_LABORS] + 1; + } + + if (sel_column < first_column) + first_column = sel_column; + if (first_column < sel_column - col_widths[DISP_COLUMN_LABORS] + 1) + first_column = sel_column - col_widths[DISP_COLUMN_LABORS] + 1; + + int input_row = sel_row; + int input_column = sel_column; + int input_sort = altsort; + + // Translate mouse input to appropriate keyboard input + if (enabler->tracking_on && gps->mouse_x != -1 && gps->mouse_y != -1) + { + int click_header = DISP_COLUMN_MAX; // group ID of the column header clicked + int click_body = DISP_COLUMN_MAX; // group ID of the column body clicked + + int click_unit = -1; // Index into units[] (-1 if out of range) + int click_labor = -1; // Index into columns[] (-1 if out of range) + + for (int i = 0; i < DISP_COLUMN_MAX; i++) + { + if ((gps->mouse_x >= col_offsets[i]) && + (gps->mouse_x < col_offsets[i] + col_widths[i])) + { + if ((gps->mouse_y >= 1) && (gps->mouse_y <= 2)) + click_header = i; + if ((gps->mouse_y >= 4) && (gps->mouse_y <= 4 + num_rows)) + click_body = i; + } + } + + if ((gps->mouse_x >= col_offsets[DISP_COLUMN_LABORS]) && + (gps->mouse_x < col_offsets[DISP_COLUMN_LABORS] + col_widths[DISP_COLUMN_LABORS])) + click_labor = gps->mouse_x - col_offsets[DISP_COLUMN_LABORS] + first_column; + if ((gps->mouse_y >= 4) && (gps->mouse_y <= 4 + num_rows)) + click_unit = gps->mouse_y - 4 + first_row; + + switch (click_header) + { + case DISP_COLUMN_HAPPINESS: + if (enabler->mouse_lbut || enabler->mouse_rbut) + { + input_sort = ALTSORT_HAPPINESS; + if (enabler->mouse_lbut) + events->insert(interface_key::SECONDSCROLL_PAGEUP); + if (enabler->mouse_rbut) + events->insert(interface_key::SECONDSCROLL_PAGEDOWN); + } + break; + + case DISP_COLUMN_NAME: + if (enabler->mouse_lbut || enabler->mouse_rbut) + { + input_sort = ALTSORT_NAME; + if (enabler->mouse_lbut) + events->insert(interface_key::SECONDSCROLL_PAGEDOWN); + if (enabler->mouse_rbut) + events->insert(interface_key::SECONDSCROLL_PAGEUP); + } + break; + + case DISP_COLUMN_PROFESSION: + if (enabler->mouse_lbut || enabler->mouse_rbut) + { + input_sort = ALTSORT_PROFESSION; + if (enabler->mouse_lbut) + events->insert(interface_key::SECONDSCROLL_PAGEDOWN); + if (enabler->mouse_rbut) + events->insert(interface_key::SECONDSCROLL_PAGEUP); + } + break; + + case DISP_COLUMN_LABORS: + if (enabler->mouse_lbut || enabler->mouse_rbut) + { + input_column = click_labor; + if (enabler->mouse_lbut) + events->insert(interface_key::SECONDSCROLL_UP); + if (enabler->mouse_rbut) + events->insert(interface_key::SECONDSCROLL_DOWN); + } + break; + } + + switch (click_body) + { + case DISP_COLUMN_HAPPINESS: + // do nothing + break; + + case DISP_COLUMN_NAME: + case DISP_COLUMN_PROFESSION: + // left-click to view, right-click to zoom + if (enabler->mouse_lbut) + { + input_row = click_unit; + events->insert(interface_key::UNITJOB_VIEW); + } + if (enabler->mouse_rbut) + { + input_row = click_unit; + events->insert(interface_key::UNITJOB_ZOOM_CRE); + } + break; + + case DISP_COLUMN_LABORS: + // left-click to toggle, right-click to just highlight + if (enabler->mouse_lbut || enabler->mouse_rbut) + { + if (enabler->mouse_lbut) + { + input_row = click_unit; + input_column = click_labor; + events->insert(interface_key::SELECT); + } + if (enabler->mouse_rbut) + { + sel_row = click_unit; + sel_column = click_labor; + } + } + break; + } + enabler->mouse_lbut = enabler->mouse_rbut = 0; + } + + UnitInfo *cur = units[input_row]; + if (events->count(interface_key::SELECT) && (cur->allowEdit) && (columns[input_column].labor != unit_labor::NONE)) + { + df::unit *unit = cur->unit; + const SkillColumn &col = columns[input_column]; + bool newstatus = !unit->status.labors[col.labor]; + if (col.special) + { + if (newstatus) + { + for (int i = 0; i < NUM_COLUMNS; i++) + { + if ((columns[i].labor != unit_labor::NONE) && columns[i].special) + unit->status.labors[columns[i].labor] = false; + } + } + unit->military.pickup_flags.bits.update = true; + } + unit->status.labors[col.labor] = newstatus; + } + if (events->count(interface_key::SELECT_ALL) && (cur->allowEdit)) + { + df::unit *unit = cur->unit; + const SkillColumn &col = columns[input_column]; + bool newstatus = !unit->status.labors[col.labor]; + for (int i = 0; i < NUM_COLUMNS; i++) + { + if (columns[i].group != col.group) + continue; + if (columns[i].special) + { + if (newstatus) + { + for (int j = 0; j < NUM_COLUMNS; j++) + { + if ((columns[j].labor != unit_labor::NONE) && columns[j].special) + unit->status.labors[columns[j].labor] = false; + } + } + unit->military.pickup_flags.bits.update = true; + } + unit->status.labors[columns[i].labor] = newstatus; + } + } + + if (events->count(interface_key::SECONDSCROLL_UP) || events->count(interface_key::SECONDSCROLL_DOWN)) + { + descending = events->count(interface_key::SECONDSCROLL_UP); + sort_skill = columns[input_column].skill; + sort_labor = columns[input_column].labor; + std::sort(units.begin(), units.end(), sortBySkill); + } + + if (events->count(interface_key::SECONDSCROLL_PAGEUP) || events->count(interface_key::SECONDSCROLL_PAGEDOWN)) + { + descending = events->count(interface_key::SECONDSCROLL_PAGEUP); + switch (input_sort) + { + case ALTSORT_NAME: + std::sort(units.begin(), units.end(), sortByName); + break; + case ALTSORT_PROFESSION: + std::sort(units.begin(), units.end(), sortByProfession); + break; + case ALTSORT_HAPPINESS: + std::sort(units.begin(), units.end(), sortByHappiness); + break; + case ALTSORT_ARRIVAL: + std::sort(units.begin(), units.end(), sortByArrival); + break; + } + } + if (events->count(interface_key::CHANGETAB)) + { + switch (altsort) + { + case ALTSORT_NAME: + altsort = ALTSORT_PROFESSION; + break; + case ALTSORT_PROFESSION: + altsort = ALTSORT_HAPPINESS; + break; + case ALTSORT_HAPPINESS: + altsort = ALTSORT_ARRIVAL; + break; + case ALTSORT_ARRIVAL: + altsort = ALTSORT_NAME; + break; + } + } + + if (VIRTUAL_CAST_VAR(unitlist, df::viewscreen_unitlistst, parent)) + { + if (events->count(interface_key::UNITJOB_VIEW) || events->count(interface_key::UNITJOB_ZOOM_CRE)) + { + for (int i = 0; i < unitlist->units[unitlist->page].size(); i++) + { + if (unitlist->units[unitlist->page][i] == units[input_row]->unit) + { + unitlist->cursor_pos[unitlist->page] = i; + unitlist->feed(events); + if (Screen::isDismissed(unitlist)) + Screen::dismiss(this); + else + do_refresh_names = true; + break; + } + } + } + } +} + +void OutputString(int8_t color, int &x, int y, const std::string &text) +{ + Screen::paintString(Screen::Pen(' ', color, 0), x, y, text); + x += text.length(); +} +void viewscreen_unitlaborsst::render() +{ + if (Screen::isDismissed(this)) + return; + + dfhack_viewscreen::render(); + + Screen::clear(); + Screen::drawBorder(" Dwarf Manipulator - Manage Labors "); + + + Screen::paintString(Screen::Pen(' ', 7, 0), col_offsets[DISP_COLUMN_HAPPINESS], 2, "Hap."); + Screen::paintString(Screen::Pen(' ', 7, 0), col_offsets[DISP_COLUMN_NAME], 2, "Name"); + Screen::paintString(Screen::Pen(' ', 7, 0), col_offsets[DISP_COLUMN_PROFESSION], 2, "Profession"); + + for (int col = 0; col < col_widths[DISP_COLUMN_LABORS]; col++) + { + int col_offset = col + first_column; + if (col_offset >= NUM_COLUMNS) + break; + + int8_t fg = columns[col_offset].color; + int8_t bg = 0; + + if (col_offset == sel_column) + { + fg = 0; + bg = 7; + } + + Screen::paintTile(Screen::Pen(columns[col_offset].label[0], fg, bg), col_offsets[DISP_COLUMN_LABORS] + col, 1); + Screen::paintTile(Screen::Pen(columns[col_offset].label[1], fg, bg), col_offsets[DISP_COLUMN_LABORS] + col, 2); + df::profession profession = columns[col_offset].profession; + if ((profession != profession::NONE) && (ui->race_id != -1)) + { + auto graphics = world->raws.creatures.all[ui->race_id]->graphics; + Screen::paintTile( + Screen::Pen(' ', fg, 0, + graphics.profession_add_color[creature_graphics_role::DEFAULT][profession], + graphics.profession_texpos[creature_graphics_role::DEFAULT][profession]), + col_offsets[DISP_COLUMN_LABORS] + col, 3); + } + } + + for (int row = 0; row < num_rows; row++) + { + int row_offset = row + first_row; + if (row_offset >= units.size()) + break; + + UnitInfo *cur = units[row_offset]; + df::unit *unit = cur->unit; + int8_t fg = 15, bg = 0; + + int happy = cur->unit->status.happiness; + string happiness = stl_sprintf("%4i", happy); + if (happy == 0) // miserable + fg = 13; // 5:1 + else if (happy <= 25) // very unhappy + fg = 12; // 4:1 + else if (happy <= 50) // unhappy + fg = 4; // 4:0 + else if (happy < 75) // fine + fg = 14; // 6:1 + else if (happy < 125) // quite content + fg = 6; // 6:0 + else if (happy < 150) // happy + fg = 2; // 2:0 + else // ecstatic + fg = 10; // 2:1 + Screen::paintString(Screen::Pen(' ', fg, bg), col_offsets[DISP_COLUMN_HAPPINESS], 4 + row, happiness); + + fg = 15; + if (row_offset == sel_row) + { + fg = 0; + bg = 7; + } + + string name = cur->name; + name.resize(col_widths[DISP_COLUMN_NAME]); + Screen::paintString(Screen::Pen(' ', fg, bg), col_offsets[DISP_COLUMN_NAME], 4 + row, name); + + string profession = cur->profession; + profession.resize(col_widths[DISP_COLUMN_PROFESSION]); + fg = cur->color; + bg = 0; + + Screen::paintString(Screen::Pen(' ', fg, bg), col_offsets[DISP_COLUMN_PROFESSION], 4 + row, profession); + + // Print unit's skills and labor assignments + for (int col = 0; col < col_widths[DISP_COLUMN_LABORS]; col++) + { + int col_offset = col + first_column; + fg = 15; + bg = 0; + uint8_t c = 0xFA; + if ((col_offset == sel_column) && (row_offset == sel_row)) + fg = 9; + if (columns[col_offset].skill != job_skill::NONE) + { + df::unit_skill *skill = binsearch_in_vector<df::unit_skill,df::enum_field<df::job_skill,int16_t>>(unit->status.current_soul->skills, &df::unit_skill::id, columns[col_offset].skill); + if ((skill != NULL) && (skill->rating || skill->experience)) + { + int level = skill->rating; + if (level > NUM_SKILL_LEVELS - 1) + level = NUM_SKILL_LEVELS - 1; + c = skill_levels[level].abbrev; + } + else + c = '-'; + } + if (columns[col_offset].labor != unit_labor::NONE) + { + if (unit->status.labors[columns[col_offset].labor]) + { + bg = 7; + if (columns[col_offset].skill == job_skill::NONE) + c = 0xF9; + } + } + else + bg = 4; + Screen::paintTile(Screen::Pen(c, fg, bg), col_offsets[DISP_COLUMN_LABORS] + col, 4 + row); + } + } + + UnitInfo *cur = units[sel_row]; + bool canToggle = false; + if (cur != NULL) + { + df::unit *unit = cur->unit; + int x = 1; + Screen::paintString(Screen::Pen(' ', 15, 0), x, 3 + num_rows + 2, cur->transname); + x += cur->transname.length(); + + if (cur->transname.length()) + { + Screen::paintString(Screen::Pen(' ', 15, 0), x, 3 + num_rows + 2, ", "); + x += 2; + } + Screen::paintString(Screen::Pen(' ', 15, 0), x, 3 + num_rows + 2, cur->profession); + x += cur->profession.length(); + Screen::paintString(Screen::Pen(' ', 15, 0), x, 3 + num_rows + 2, ": "); + x += 2; + + string str; + if (columns[sel_column].skill == job_skill::NONE) + { + str = ENUM_ATTR_STR(unit_labor, caption, columns[sel_column].labor); + if (unit->status.labors[columns[sel_column].labor]) + str += " Enabled"; + else + str += " Not Enabled"; + } + else + { + df::unit_skill *skill = binsearch_in_vector<df::unit_skill,df::enum_field<df::job_skill,int16_t>>(unit->status.current_soul->skills, &df::unit_skill::id, columns[sel_column].skill); + if (skill) + { + int level = skill->rating; + if (level > NUM_SKILL_LEVELS - 1) + level = NUM_SKILL_LEVELS - 1; + str = stl_sprintf("%s %s", skill_levels[level].name, ENUM_ATTR_STR(job_skill, caption_noun, columns[sel_column].skill)); + if (level != NUM_SKILL_LEVELS - 1) + str += stl_sprintf(" (%d/%d)", skill->experience, skill_levels[level].points); + } + else + str = stl_sprintf("Not %s (0/500)", ENUM_ATTR_STR(job_skill, caption_noun, columns[sel_column].skill)); + } + Screen::paintString(Screen::Pen(' ', 9, 0), x, 3 + num_rows + 2, str); + + canToggle = (cur->allowEdit) && (columns[sel_column].labor != unit_labor::NONE); + } + + int x = 2; + OutputString(10, x, gps->dimy - 3, "Enter"); // SELECT key + OutputString(canToggle ? 15 : 8, x, gps->dimy - 3, ": Toggle labor, "); + + OutputString(10, x, gps->dimy - 3, "Shift+Enter"); // SELECT_ALL key + OutputString(canToggle ? 15 : 8, x, gps->dimy - 3, ": Toggle Group, "); + + OutputString(10, x, gps->dimy - 3, "v"); // UNITJOB_VIEW key + OutputString(15, x, gps->dimy - 3, ": ViewCre, "); + + OutputString(10, x, gps->dimy - 3, "c"); // UNITJOB_ZOOM_CRE key + OutputString(15, x, gps->dimy - 3, ": Zoom-Cre"); + + x = 2; + OutputString(10, x, gps->dimy - 2, "Esc"); // LEAVESCREEN key + OutputString(15, x, gps->dimy - 2, ": Done, "); + + OutputString(10, x, gps->dimy - 2, "+"); // SECONDSCROLL_DOWN key + OutputString(10, x, gps->dimy - 2, "-"); // SECONDSCROLL_UP key + OutputString(15, x, gps->dimy - 2, ": Sort by Skill, "); + + OutputString(10, x, gps->dimy - 2, "*"); // SECONDSCROLL_PAGEDOWN key + OutputString(10, x, gps->dimy - 2, "/"); // SECONDSCROLL_PAGEUP key + OutputString(15, x, gps->dimy - 2, ": Sort by ("); + OutputString(10, x, gps->dimy - 2, "Tab"); // CHANGETAB key + OutputString(15, x, gps->dimy - 2, ") "); + switch (altsort) + { + case ALTSORT_NAME: + OutputString(15, x, gps->dimy - 2, "Name"); + break; + case ALTSORT_PROFESSION: + OutputString(15, x, gps->dimy - 2, "Profession"); + break; + case ALTSORT_HAPPINESS: + OutputString(15, x, gps->dimy - 2, "Happiness"); + break; + case ALTSORT_ARRIVAL: + OutputString(15, x, gps->dimy - 2, "Arrival"); + break; + default: + OutputString(15, x, gps->dimy - 2, "Unknown"); + break; + } +} + +df::unit *viewscreen_unitlaborsst::getSelectedUnit() +{ + // This query might be from the rename plugin + do_refresh_names = true; + + return units[sel_row]->unit; +} + +struct unitlist_hook : df::viewscreen_unitlistst +{ + typedef df::viewscreen_unitlistst interpose_base; + + DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input)) + { + if (input->count(interface_key::UNITVIEW_PRF_PROF)) + { + if (units[page].size()) + { + Screen::show(new viewscreen_unitlaborsst(units[page], cursor_pos[page])); + return; + } + } + INTERPOSE_NEXT(feed)(input); + } + + DEFINE_VMETHOD_INTERPOSE(void, render, ()) + { + INTERPOSE_NEXT(render)(); + + if (units[page].size()) + { + int x = 2; + OutputString(12, x, gps->dimy - 2, "l"); // UNITVIEW_PRF_PROF key + OutputString(15, x, gps->dimy - 2, ": Manage labors (DFHack)"); + } + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(unitlist_hook, feed); +IMPLEMENT_VMETHOD_INTERPOSE(unitlist_hook, render); + +DFHACK_PLUGIN("manipulator"); + +DFhackCExport command_result plugin_init ( color_ostream &out, vector <PluginCommand> &commands) +{ + if (!gps || !INTERPOSE_HOOK(unitlist_hook, feed).apply() || !INTERPOSE_HOOK(unitlist_hook, render).apply()) + out.printerr("Could not insert Dwarf Manipulator hooks!\n"); + return CR_OK; +} + +DFhackCExport command_result plugin_shutdown ( color_ostream &out ) +{ + INTERPOSE_HOOK(unitlist_hook, feed).remove(); + INTERPOSE_HOOK(unitlist_hook, render).remove(); + return CR_OK; +} diff --git a/plugins/power-meter.cpp b/plugins/power-meter.cpp new file mode 100644 index 00000000..17261adb --- /dev/null +++ b/plugins/power-meter.cpp @@ -0,0 +1,237 @@ +#include "Core.h" +#include <Console.h> +#include <Export.h> +#include <Error.h> +#include <PluginManager.h> +#include <modules/Gui.h> +#include <modules/Screen.h> +#include <modules/Maps.h> +#include <modules/World.h> +#include <TileTypes.h> +#include <vector> +#include <cstdio> +#include <stack> +#include <string> +#include <cmath> +#include <string.h> + +#include <VTableInterpose.h> +#include "df/graphic.h" +#include "df/building_trapst.h" +#include "df/builtin_mats.h" +#include "df/world.h" +#include "df/buildings_other_id.h" +#include "df/machine.h" +#include "df/machine_info.h" +#include "df/building_drawbuffer.h" +#include "df/ui.h" +#include "df/viewscreen_dwarfmodest.h" +#include "df/ui_build_selector.h" +#include "df/flow_info.h" +#include "df/report.h" + +#include "MiscUtils.h" + +using std::vector; +using std::string; +using std::stack; +using namespace DFHack; +using namespace df::enums; + +using df::global::gps; +using df::global::world; +using df::global::ui; +using df::global::ui_build_selector; + +DFHACK_PLUGIN("power-meter"); + +static const uint32_t METER_BIT = 0x80000000U; + +static void init_plate_info(df::pressure_plate_info &plate_info) +{ + plate_info.water_min = 1; + plate_info.water_max = 7; + plate_info.flags.whole = METER_BIT; + plate_info.flags.bits.water = true; + plate_info.flags.bits.resets = true; +} + +/* + * Hook for the pressure plate itself. Implements core logic. + */ + +struct trap_hook : df::building_trapst { + typedef df::building_trapst interpose_base; + + // Engine detection + + bool is_power_meter() + { + return trap_type == trap_type::PressurePlate && + (plate_info.flags.whole & METER_BIT) != 0; + } + + inline bool is_fully_built() + { + return getBuildStage() >= getMaxBuildStage(); + } + + DEFINE_VMETHOD_INTERPOSE(void, getName, (std::string *buf)) + { + if (is_power_meter()) + { + buf->clear(); + *buf += "Power Meter"; + return; + } + + INTERPOSE_NEXT(getName)(buf); + } + + DEFINE_VMETHOD_INTERPOSE(void, updateAction, ()) + { + if (is_power_meter()) + { + auto pdsgn = Maps::getTileDesignation(centerx,centery,z); + + if (pdsgn) + { + bool active = false; + auto &gears = world->buildings.other[buildings_other_id::GEAR_ASSEMBLY]; + + for (size_t i = 0; i < gears.size(); i++) + { + // Adjacent + auto gear = gears[i]; + int deltaxy = abs(centerx - gear->centerx) + abs(centery - gear->centery); + if (gear->z != z || deltaxy != 1) + continue; + // Linked to machine + auto info = gears[i]->getMachineInfo(); + if (!info || info->machine_id < 0) + continue; + // an active machine + auto machine = df::machine::find(info->machine_id); + if (!machine || !machine->flags.bits.active) + continue; + // with adequate power? + int power = machine->cur_power - machine->min_power; + if (power < 0 || machine->cur_power <= 0) + continue; + if (power < plate_info.track_min) + continue; + if (power > plate_info.track_max && plate_info.track_max >= 0) + continue; + + active = true; + break; + } + + if (plate_info.flags.bits.citizens) + active = !active; + + // Temporarily set the tile water amount based on power state + auto old_dsgn = *pdsgn; + pdsgn->bits.liquid_type = tile_liquid::Water; + pdsgn->bits.flow_size = (active ? 7 : 0); + + INTERPOSE_NEXT(updateAction)(); + + *pdsgn = old_dsgn; + return; + } + } + + INTERPOSE_NEXT(updateAction)(); + } + + DEFINE_VMETHOD_INTERPOSE(void, drawBuilding, (df::building_drawbuffer *db, void *unk)) + { + INTERPOSE_NEXT(drawBuilding)(db, unk); + + if (is_power_meter() && is_fully_built()) + { + db->fore[0][0] = 3; + } + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(trap_hook, getName); +IMPLEMENT_VMETHOD_INTERPOSE(trap_hook, updateAction); +IMPLEMENT_VMETHOD_INTERPOSE(trap_hook, drawBuilding); + +static bool enabled = false; + +static void enable_hooks(bool enable) +{ + enabled = enable; + + INTERPOSE_HOOK(trap_hook, getName).apply(enable); + INTERPOSE_HOOK(trap_hook, updateAction).apply(enable); + INTERPOSE_HOOK(trap_hook, drawBuilding).apply(enable); +} + +static bool makePowerMeter(df::pressure_plate_info *info, int min_power, int max_power, bool invert) +{ + CHECK_NULL_POINTER(info); + + if (!enabled) + { + auto pworld = Core::getInstance().getWorld(); + auto entry = pworld->GetPersistentData("power-meter/enabled", NULL); + if (!entry.isValid()) + return false; + + enable_hooks(true); + } + + init_plate_info(*info); + info->track_min = min_power; + info->track_max = max_power; + info->flags.bits.citizens = invert; + return true; +} + +DFHACK_PLUGIN_LUA_FUNCTIONS { + DFHACK_LUA_FUNCTION(makePowerMeter), + DFHACK_LUA_END +}; + +DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event) +{ + switch (event) { + case SC_WORLD_LOADED: + { + auto pworld = Core::getInstance().getWorld(); + bool enable = pworld->GetPersistentData("power-meter/enabled").isValid(); + + if (enable) + { + out.print("Enabling the power meter plugin.\n"); + enable_hooks(true); + } + } + break; + case SC_WORLD_UNLOADED: + enable_hooks(false); + break; + default: + break; + } + + return CR_OK; +} + +DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands) +{ + if (Core::getInstance().isWorldLoaded()) + plugin_onstatechange(out, SC_WORLD_LOADED); + + return CR_OK; +} + +DFhackCExport command_result plugin_shutdown ( color_ostream &out ) +{ + enable_hooks(false); + return CR_OK; +} diff --git a/plugins/probe.cpp b/plugins/probe.cpp index 2ae6846d..45ef1bbf 100644 --- a/plugins/probe.cpp +++ b/plugins/probe.cpp @@ -27,6 +27,7 @@ using namespace std; #include "df/world.h" #include "df/world_raws.h" #include "df/building_def.h" +#include "df/region_map_entry.h" using std::vector; using std::string; @@ -224,8 +225,7 @@ command_result df_probe (color_ostream &out, vector <string> & parameters) int bx = clip_range(block.region_pos.x + (offset % 3) - 1, 0, world->world_data->world_width-1); int by = clip_range(block.region_pos.y + (offset / 3) - 1, 0, world->world_data->world_height-1); - df::world_data::T_region_map* biome = - &world->world_data->region_map[bx][by]; + auto biome = &world->world_data->region_map[bx][by]; int sav = biome->savagery; int evi = biome->evilness; diff --git a/plugins/prospector.cpp b/plugins/prospector.cpp index e2f1e953..5eab897c 100644 --- a/plugins/prospector.cpp +++ b/plugins/prospector.cpp @@ -25,8 +25,12 @@ using namespace std; #include "df/world.h" #include "df/world_data.h" #include "df/world_region_details.h" +#include "df/world_region_feature.h" #include "df/world_geo_biome.h" #include "df/world_geo_layer.h" +#include "df/world_underground_region.h" +#include "df/feature_init.h" +#include "df/region_map_entry.h" #include "df/inclusion_type.h" #include "df/viewscreen_choose_start_sitest.h" @@ -108,9 +112,10 @@ struct compare_pair_second } }; -static void printMatdata(color_ostream &con, const matdata &data) +static void printMatdata(color_ostream &con, const matdata &data, bool only_z = false) { - con << std::setw(9) << data.count; + if (!only_z) + con << std::setw(9) << data.count; if(data.lower_z != data.upper_z) con <<" Z:" << std::setw(4) << data.lower_z << ".." << data.upper_z << std::endl; @@ -225,116 +230,247 @@ static coord2d biome_delta[] = { coord2d(-1,-1), coord2d(0,-1), coord2d(1,-1) }; -static command_result embark_prospector(color_ostream &out, df::viewscreen_choose_start_sitest *screen, - bool showHidden, bool showValue) +struct EmbarkTileLayout { + coord2d biome_off, biome_pos; + df::region_map_entry *biome; + int elevation, max_soil_depth; + int min_z, base_z; + std::map<int, float> penalty; +}; + +bool estimate_underground(color_ostream &out, EmbarkTileLayout &tile, df::world_region_details *details, int x, int y) { - if (!world || !world->world_data) + // Find actual biome + int bv = clip_range(details->biome[x][y] & 15, 1, 9); + tile.biome_off = biome_delta[bv-1]; + + df::world_data *data = world->world_data; + int bx = clip_range(details->pos.x + tile.biome_off.x, 0, data->world_width-1); + int by = clip_range(details->pos.y + tile.biome_off.y, 0, data->world_height-1); + tile.biome_pos = coord2d(bx, by); + tile.biome = &data->region_map[bx][by]; + + // Compute surface elevation + tile.elevation = ( + details->elevation[x][y] + details->elevation[x][y+1] + + details->elevation[x+1][y] + details->elevation[x+1][y+1] + ) / 4; + tile.max_soil_depth = std::max((154-tile.biome->elevation)/5,0); + tile.base_z = tile.elevation; + tile.penalty.clear(); + + auto &features = details->features[x][y]; + + // Collect global feature layer depths and apply penalties + std::map<int, int> layer_bottom, layer_top; + bool sea_found = false; + + for (size_t i = 0; i < features.size(); i++) { - out.printerr("World data is not available.\n"); - return CR_FAILURE; + auto feature = features[i]; + auto layer = df::world_underground_region::find(feature->layer); + if (!layer || feature->min_z == -30000) continue; + + layer_bottom[layer->layer_depth] = feature->min_z; + layer_top[layer->layer_depth] = feature->max_z; + tile.base_z = std::min(tile.base_z, (int)feature->min_z); + + float penalty = 1.0f; + switch (layer->type) { + case df::world_underground_region::Cavern: + penalty = 0.75f; + break; + case df::world_underground_region::MagmaSea: + sea_found = true; + tile.min_z = feature->min_z; + for (int i = feature->min_z; i <= feature->max_z; i++) + tile.penalty[i] = 0.2 + 0.6f*(i-feature->min_z)/(feature->max_z-feature->min_z+1); + break; + case df::world_underground_region::Underworld: + penalty = 0.0f; + break; + } + + if (penalty != 1.0f) + { + for (int i = feature->min_z; i <= feature->max_z; i++) + tile.penalty[i] = penalty; + } } - df::world_data *data = world->world_data; - coord2d cur_region = screen->region_pos; - int d_idx = linear_index(data->region_details, &df::world_region_details::pos, cur_region); - auto cur_details = vector_get(data->region_details, d_idx); + if (!sea_found) + { + out.printerr("Could not find magma sea.\n"); + return false; + } - if (!cur_details) + // Scan for big local features and apply their penalties + for (size_t i = 0; i < features.size(); i++) { - out.printerr("Current region details are not available.\n"); - return CR_FAILURE; + auto feature = features[i]; + auto lfeature = Maps::getLocalInitFeature(details->pos, feature->feature_idx); + if (!lfeature) + continue; + + switch (lfeature->getType()) + { + case feature_type::pit: + case feature_type::magma_pool: + case feature_type::volcano: + for (int i = layer_bottom[lfeature->end_depth]; + i <= layer_top[lfeature->start_depth]; i++) + tile.penalty[i] = std::min(0.4f, map_find(tile.penalty, i, 1.0f)); + break; + default: + break; + } } - // Compute biomes - std::map<coord2d, int> biomes; + return true; +} + +void add_materials(EmbarkTileLayout &tile, matdata &data, float amount, int min_z, int max_z) +{ + for (int z = min_z; z <= max_z; z++) + data.add(z, int(map_find(tile.penalty, z, 1)*amount)); +} + +bool estimate_materials(color_ostream &out, EmbarkTileLayout &tile, MatMap &layerMats, MatMap &veinMats) +{ + using namespace geo_layer_type; + + df::world_geo_biome *geo_biome = df::world_geo_biome::find(tile.biome->geo_index); - if (screen->biome_highlighted) + if (!geo_biome) { - out.print("Processing one embark tile of biome F%d.\n\n", screen->biome_idx+1); - biomes[screen->biome_rgn[screen->biome_idx]]++; + out.printerr("Region geo-biome not found: (%d,%d)\n", + tile.biome_pos.x, tile.biome_pos.y); + return false; } - else + + // soil depth increases by 1 every 5 levels below 150 + int top_z_level = tile.elevation - tile.max_soil_depth; + + for (unsigned i = 0; i < geo_biome->layers.size(); i++) { - for (int x = screen->embark_pos_min.x; x <= screen->embark_pos_max.x; x++) + auto layer = geo_biome->layers[i]; + switch (layer->type) { - for (int y = screen->embark_pos_min.y; y <= screen->embark_pos_max.y; y++) - { - int bv = clip_range(cur_details->biome[x][y], 1, 9); - biomes[cur_region + biome_delta[bv-1]]++; - } + case SOIL: + case SOIL_OCEAN: + case SOIL_SAND: + top_z_level += layer->top_height - layer->bottom_height + 1; + break; + default:; } } - // Compute material maps - MatMap layerMats; - MatMap veinMats; + top_z_level = std::max(top_z_level, tile.elevation)-1; - for (auto biome_it = biomes.begin(); biome_it != biomes.end(); ++biome_it) + for (unsigned i = 0; i < geo_biome->layers.size(); i++) { - int bx = clip_range(biome_it->first.x, 0, data->world_width-1); - int by = clip_range(biome_it->first.y, 0, data->world_height-1); - auto ®ion = data->region_map[bx][by]; - df::world_geo_biome *geo_biome = df::world_geo_biome::find(region.geo_index); + auto layer = geo_biome->layers[i]; - if (!geo_biome) - { - out.printerr("Region geo-biome not found: (%d,%d)\n", bx, by); - return CR_FAILURE; - } + int top_z = std::min(layer->top_height + top_z_level, tile.elevation-1); + int bottom_z = std::max(layer->bottom_height + top_z_level, tile.min_z); + if (i+1 == geo_biome->layers.size()) // stretch layer if needed + bottom_z = tile.min_z; + if (top_z < bottom_z) + continue; + + float layer_size = 48*48; + + int sums[ENUM_LAST_ITEM(inclusion_type)+1] = { 0 }; - int cnt = biome_it->second; + for (unsigned j = 0; j < layer->vein_mat.size(); j++) + if (is_valid_enum_item<df::inclusion_type>(layer->vein_type[j])) + sums[layer->vein_type[j]] += layer->vein_unk_38[j]; - for (unsigned i = 0; i < geo_biome->layers.size(); i++) + for (unsigned j = 0; j < layer->vein_mat.size(); j++) { - auto layer = geo_biome->layers[i]; + // TODO: find out how to estimate the real density + // this code assumes that vein_unk_38 is the weight + // used when choosing the vein material + float size = float(layer->vein_unk_38[j]); + df::inclusion_type type = layer->vein_type[j]; - layerMats[layer->mat_index].add(layer->bottom_height, 0); + switch (type) + { + case inclusion_type::VEIN: + // 3 veins of 80 tiles avg + size = size * 80 * 3 / sums[type]; + break; + case inclusion_type::CLUSTER: + // 1 cluster of 700 tiles avg + size = size * 700 * 1 / sums[type]; + break; + case inclusion_type::CLUSTER_SMALL: + size = size * 6 * 7 / sums[type]; + break; + case inclusion_type::CLUSTER_ONE: + size = size * 1 * 5 / sums[type]; + break; + default: + // shouldn't actually happen + size = 1; + } - int level_cnt = layer->top_height - layer->bottom_height + 1; - int layer_size = 48*48*cnt*level_cnt; + layer_size -= size; - int sums[ENUM_LAST_ITEM(inclusion_type)+1] = { 0 }; + add_materials(tile, veinMats[layer->vein_mat[j]], size, bottom_z, top_z); + } - for (unsigned j = 0; j < layer->vein_mat.size(); j++) - if (is_valid_enum_item<df::inclusion_type>(layer->vein_type[j])) - sums[layer->vein_type[j]] += layer->vein_unk_38[j]; + add_materials(tile, layerMats[layer->mat_index], layer_size, bottom_z, top_z); + } - for (unsigned j = 0; j < layer->vein_mat.size(); j++) - { - // TODO: find out how to estimate the real density - // this code assumes that vein_unk_38 is the weight - // used when choosing the vein material - int size = layer->vein_unk_38[j]*cnt*level_cnt; - df::inclusion_type type = layer->vein_type[j]; + return true; +} - switch (type) - { - case inclusion_type::VEIN: - // 3 veins of 80 tiles avg - size = size * 80 * 3 / sums[type]; - break; - case inclusion_type::CLUSTER: - // 1 cluster of 700 tiles avg - size = size * 700 * 1 / sums[type]; - break; - case inclusion_type::CLUSTER_SMALL: - size = size * 6 * 7 / sums[type]; - break; - case inclusion_type::CLUSTER_ONE: - size = size * 1 * 5 / sums[type]; - break; - default: - // shouldn't actually happen - size = cnt*level_cnt; - } +static command_result embark_prospector(color_ostream &out, df::viewscreen_choose_start_sitest *screen, + bool showHidden, bool showValue) +{ + if (!world || !world->world_data) + { + out.printerr("World data is not available.\n"); + return CR_FAILURE; + } + + df::world_data *data = world->world_data; + coord2d cur_region = screen->region_pos; + int d_idx = linear_index(data->region_details, &df::world_region_details::pos, cur_region); + auto cur_details = vector_get(data->region_details, d_idx); - veinMats[layer->vein_mat[j]].add(layer->bottom_height, 0); - veinMats[layer->vein_mat[j]].add(layer->top_height, size); + if (!cur_details) + { + out.printerr("Current region details are not available.\n"); + return CR_FAILURE; + } - layer_size -= size; - } + // Compute material maps + MatMap layerMats; + MatMap veinMats; + matdata world_bottom; - layerMats[layer->mat_index].add(layer->top_height, std::max(0,layer_size)); + // Compute biomes + std::map<coord2d, int> biomes; + + /*if (screen->biome_highlighted) + { + out.print("Processing one embark tile of biome F%d.\n\n", screen->biome_idx+1); + biomes[screen->biome_rgn[screen->biome_idx]]++; + }*/ + + for (int x = screen->embark_pos_min.x; x <= screen->embark_pos_max.x; x++) + { + for (int y = screen->embark_pos_min.y; y <= screen->embark_pos_max.y; y++) + { + EmbarkTileLayout tile; + if (!estimate_underground(out, tile, cur_details, x, y) || + !estimate_materials(out, tile, layerMats, veinMats)) + return CR_FAILURE; + + world_bottom.add(tile.base_z, 0); + world_bottom.add(tile.elevation-1, 0); } } @@ -348,7 +484,10 @@ static command_result embark_prospector(color_ostream &out, df::viewscreen_choos mats->Finish(); } - out << "Warning: the above data is only a very rough estimate." << std::endl; + out << "Embark depth: " << (world_bottom.upper_z-world_bottom.lower_z+1) << " "; + printMatdata(out, world_bottom, true); + + out << std::endl << "Warning: the above data is only a very rough estimate." << std::endl; return CR_OK; } @@ -536,6 +675,8 @@ command_result prospector (color_ostream &con, vector <string> & parameters) case tiletype_material::LAVA_STONE: // TODO ? break; + default: + break; } } } diff --git a/plugins/proto/rename.proto b/plugins/proto/rename.proto index aa1e95f4..810091fc 100644 --- a/plugins/proto/rename.proto +++ b/plugins/proto/rename.proto @@ -17,3 +17,10 @@ message RenameUnitIn { optional string nickname = 2; optional string profession = 3; } + +// RPC RenameBuilding : RenameBuildingIn -> EmptyMessage +message RenameBuildingIn { + required int32 building_id = 1; + + optional string name = 2; +} diff --git a/plugins/raw/building_steam_engine.txt b/plugins/raw/building_steam_engine.txt new file mode 100644 index 00000000..48657b0c --- /dev/null +++ b/plugins/raw/building_steam_engine.txt @@ -0,0 +1,92 @@ +building_steam_engine
+
+[OBJECT:BUILDING]
+
+[BUILDING_WORKSHOP:STEAM_ENGINE]
+ [NAME:Steam Engine]
+ [NAME_COLOR:4:0:1]
+ [DIM:3:3]
+ [WORK_LOCATION:2:3]
+ [BUILD_LABOR:MECHANIC]
+ [BUILD_KEY:CUSTOM_ALT_S]
+ [BLOCK:1:1:1:1]
+ [BLOCK:2:1:1:1]
+ [BLOCK:3:1:0:1]
+ [TILE:0:1:240:' ':254]
+ [TILE:0:2:' ':' ':128]
+ [TILE:0:3:246:' ':' ']
+ [COLOR:0:1:6:0:0:0:0:0:7:0:0]
+ [COLOR:0:2:0:0:0:0:0:0:7:0:0]
+ [COLOR:0:3:MAT:0:0:0:0:0:0]
+ [TILE:1:1:246:128:' ']
+ [TILE:1:2:' ':' ':254]
+ [TILE:1:3:254:'/':240]
+ [COLOR:1:1:MAT:7:0:0:0:0:0]
+ [COLOR:1:2:0:0:0:0:0:0:7:0:0]
+ [COLOR:1:3:7:0:0:6:0:0:6:0:0]
+ [TILE:2:1:21:' ':128]
+ [TILE:2:2:128:' ':246]
+ [TILE:2:3:177:19:177]
+ [COLOR:2:1:6:0:0:0:0:0:7:0:0]
+ [COLOR:2:2:7:0:0:0:0:0:MAT]
+ [COLOR:2:3:7:0:0:6:0:0:7:0:0]
+ Tile 15 marks places where machines can connect.
+ Tile 19 marks the hearth (color changed to reflect power).
+ [TILE:3:1:15:246:15]
+ [TILE:3:2:'\':19:'/']
+ [TILE:3:3:7:' ':7]
+ Color 1:?:1 water indicator, 4:?:1 magma indicator:
+ [COLOR:3:1:7:0:0:MAT:7:0:0]
+ [COLOR:3:2:6:0:0:0:0:1:6:0:0]
+ [COLOR:3:3:1:7:1:0:0:0:4:7:1]
+ [BUILD_ITEM:1:BARREL:NONE:INORGANIC:NONE][EMPTY][CAN_USE_ARTIFACT]
+ [BUILD_ITEM:1:PIPE_SECTION:NONE:INORGANIC:NONE][CAN_USE_ARTIFACT]
+ [BUILD_ITEM:1:TRAPCOMP:ITEM_TRAPCOMP_STEAM_PISTON:INORGANIC:NONE][CAN_USE_ARTIFACT]
+ [BUILD_ITEM:1:CHAIN:NONE:INORGANIC:NONE][CAN_USE_ARTIFACT]
+ [BUILD_ITEM:1:TRAPPARTS:NONE:NONE:NONE][CAN_USE_ARTIFACT]
+ [BUILD_ITEM:1:BLOCKS:NONE:NONE:NONE][BUILDMAT][FIRE_BUILD_SAFE]
+
+[BUILDING_WORKSHOP:MAGMA_STEAM_ENGINE]
+ [NAME:Magma Steam Engine]
+ [NAME_COLOR:4:0:1]
+ [DIM:3:3]
+ [WORK_LOCATION:2:3]
+ [BUILD_LABOR:MECHANIC]
+ [BUILD_KEY:CUSTOM_ALT_E]
+ [NEEDS_MAGMA]
+ [BLOCK:1:1:1:1]
+ [BLOCK:2:1:1:1]
+ [BLOCK:3:1:0:1]
+ [TILE:0:1:240:' ':254]
+ [TILE:0:2:' ':' ':128]
+ [TILE:0:3:246:' ':' ']
+ [COLOR:0:1:6:0:0:0:0:0:7:0:0]
+ [COLOR:0:2:0:0:0:0:0:0:7:0:0]
+ [COLOR:0:3:MAT:0:0:0:0:0:0]
+ [TILE:1:1:246:128:' ']
+ [TILE:1:2:' ':' ':254]
+ [TILE:1:3:254:'/':240]
+ [COLOR:1:1:MAT:7:0:0:0:0:0]
+ [COLOR:1:2:0:0:0:0:0:0:7:0:0]
+ [COLOR:1:3:7:0:0:6:0:0:6:0:0]
+ [TILE:2:1:21:' ':128]
+ [TILE:2:2:128:' ':246]
+ [TILE:2:3:177:19:177]
+ [COLOR:2:1:6:0:0:0:0:0:7:0:0]
+ [COLOR:2:2:7:0:0:0:0:0:MAT]
+ [COLOR:2:3:7:0:0:6:0:0:7:0:0]
+ Tile 15 marks places where machines can connect.
+ Tile 19 marks the hearth (color changed to reflect power).
+ [TILE:3:1:15:246:15]
+ [TILE:3:2:'\':19:'/']
+ [TILE:3:3:7:' ':7]
+ Color 1:?:1 water indicator, 4:?:1 magma indicator:
+ [COLOR:3:1:7:0:0:MAT:7:0:0]
+ [COLOR:3:2:6:0:0:0:0:1:6:0:0]
+ [COLOR:3:3:1:7:1:0:0:0:4:7:1]
+ [BUILD_ITEM:1:BARREL:NONE:INORGANIC:NONE][EMPTY][CAN_USE_ARTIFACT]
+ [BUILD_ITEM:1:PIPE_SECTION:NONE:INORGANIC:NONE][CAN_USE_ARTIFACT]
+ [BUILD_ITEM:1:TRAPCOMP:ITEM_TRAPCOMP_STEAM_PISTON:INORGANIC:NONE][CAN_USE_ARTIFACT]
+ [BUILD_ITEM:1:CHAIN:NONE:INORGANIC:NONE][CAN_USE_ARTIFACT]
+ [BUILD_ITEM:1:TRAPPARTS:NONE:NONE:NONE][CAN_USE_ARTIFACT]
+ [BUILD_ITEM:1:BLOCKS:NONE:NONE:NONE][BUILDMAT][MAGMA_BUILD_SAFE]
diff --git a/plugins/raw/entity_default.diff b/plugins/raw/entity_default.diff new file mode 100644 index 00000000..2ffc1363 --- /dev/null +++ b/plugins/raw/entity_default.diff @@ -0,0 +1,29 @@ +--- ../objects.old/entity_default.txt 2012-09-17 17:59:28.853898702 +0400 ++++ entity_default.txt 2012-09-17 17:59:28.684899429 +0400 +@@ -49,6 +49,7 @@ + [TRAPCOMP:ITEM_TRAPCOMP_SPIKEDBALL]
+ [TRAPCOMP:ITEM_TRAPCOMP_LARGESERRATEDDISC]
+ [TRAPCOMP:ITEM_TRAPCOMP_MENACINGSPIKE]
++ [TRAPCOMP:ITEM_TRAPCOMP_STEAM_PISTON]
+ [TOY:ITEM_TOY_PUZZLEBOX]
+ [TOY:ITEM_TOY_BOAT]
+ [TOY:ITEM_TOY_HAMMER]
+@@ -204,6 +205,8 @@ + [PERMITTED_JOB:WAX_WORKER]
+ [PERMITTED_BUILDING:SOAP_MAKER]
+ [PERMITTED_BUILDING:SCREW_PRESS]
++ [PERMITTED_BUILDING:STEAM_ENGINE]
++ [PERMITTED_BUILDING:MAGMA_STEAM_ENGINE]
+ [PERMITTED_REACTION:TAN_A_HIDE]
+ [PERMITTED_REACTION:RENDER_FAT]
+ [PERMITTED_REACTION:MAKE_SOAP_FROM_TALLOW]
+@@ -248,6 +251,9 @@ + [PERMITTED_REACTION:ROSE_GOLD_MAKING]
+ [PERMITTED_REACTION:BISMUTH_BRONZE_MAKING]
+ [PERMITTED_REACTION:ADAMANTINE_WAFERS]
++ [PERMITTED_REACTION:STOKE_BOILER]
++ [PERMITTED_REACTION:SPATTER_ADD_WEAPON_EXTRACT]
++ [PERMITTED_REACTION:SPATTER_ADD_AMMO_EXTRACT]
+ [WORLD_CONSTRUCTION:TUNNEL]
+ [WORLD_CONSTRUCTION:BRIDGE]
+ [WORLD_CONSTRUCTION:ROAD]
diff --git a/plugins/raw/item_trapcomp_steam_engine.txt b/plugins/raw/item_trapcomp_steam_engine.txt new file mode 100644 index 00000000..c35f6ef4 --- /dev/null +++ b/plugins/raw/item_trapcomp_steam_engine.txt @@ -0,0 +1,12 @@ +item_trapcomp_steam_engine
+
+[OBJECT:ITEM]
+
+[ITEM_TRAPCOMP:ITEM_TRAPCOMP_STEAM_PISTON]
+[NAME:piston:pistons]
+[ADJECTIVE:heavy]
+[SIZE:1800]
+[HITS:1]
+[MATERIAL_SIZE:6]
+[METAL]
+[ATTACK:BLUNT:40:200:bash:bashes:NO_SUB:2000]
diff --git a/plugins/raw/material_template_default.diff b/plugins/raw/material_template_default.diff new file mode 100644 index 00000000..8b6ef327 --- /dev/null +++ b/plugins/raw/material_template_default.diff @@ -0,0 +1,10 @@ +--- ../objects.old/material_template_default.txt 2012-09-17 17:59:28.907898469 +0400 ++++ material_template_default.txt 2012-09-17 17:59:28.695899382 +0400 +@@ -2374,6 +2374,7 @@ + [MAX_EDGE:500]
+ [ABSORPTION:100]
+ [LIQUID_MISC_CREATURE]
++ [REACTION_CLASS:CREATURE_EXTRACT]
+ [ROTS]
+
+ This is for creatures that are "made of fire". Right now there isn't a good format for that.
diff --git a/plugins/raw/reaction_spatter.txt b/plugins/raw/reaction_spatter.txt new file mode 100644 index 00000000..81f9a2b6 --- /dev/null +++ b/plugins/raw/reaction_spatter.txt @@ -0,0 +1,154 @@ +reaction_spatter
+
+[OBJECT:REACTION]
+
+Reaction name must start with 'SPATTER_ADD_':
+
+[REACTION:SPATTER_ADD_OBJECT_LIQUID]
+ [NAME:coat object with liquid]
+ [ADVENTURE_MODE_ENABLED]
+ [SKILL:WAX_WORKING]
+ [REAGENT:extract:150:LIQUID_MISC:NONE:NONE:NONE]
+ [MIN_DIMENSION:150]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ [REAGENT:extract container:1:NONE:NONE:NONE:NONE]
+ [CONTAINS:extract]
+ [PRESERVE_REAGENT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ The object to improve must be after the input mat, so that it is known:
+ [REAGENT:object:1:NONE:NONE:NONE:NONE]
+ [PRESERVE_REAGENT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ Need some excuse why the spatter is water-resistant:
+ [REAGENT:grease:1:GLOB:NONE:NONE:NONE][REACTION_CLASS:FAT][UNROTTEN]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ The probability is used as spatter size; Legendary gives +90%:
+ COVERED = liquid, GLAZED = solid, BANDS = paste, SPIKES = powder
+ [IMPROVEMENT:800:object:COVERED:GET_MATERIAL_FROM_REAGENT:extract:NONE]
+
+[REACTION:SPATTER_ADD_WEAPON_EXTRACT]
+ [NAME:coat weapon with extract]
+ [BUILDING:CRAFTSMAN:NONE]
+ [SKILL:WAX_WORKING]
+ [REAGENT:extract:150:LIQUID_MISC:NONE:NONE:NONE]
+ [MIN_DIMENSION:150]
+ [REACTION_CLASS:CREATURE_EXTRACT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ [REAGENT:extract container:1:NONE:NONE:NONE:NONE]
+ [CONTAINS:extract]
+ [PRESERVE_REAGENT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ The object to improve must be after the input mat, so that it is known:
+ [REAGENT:object:1:WEAPON:NONE:NONE:NONE]
+ [PRESERVE_REAGENT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ Need some excuse why the spatter is water-resistant:
+ [REAGENT:grease:1:GLOB:NONE:NONE:NONE][REACTION_CLASS:TALLOW][UNROTTEN]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ The probability is used as spatter size; Legendary gives +90%:
+ COVERED = liquid, GLAZED = solid, BANDS = paste, SPIKES = powder
+ [IMPROVEMENT:800:object:COVERED:GET_MATERIAL_FROM_REAGENT:extract:NONE]
+
+[REACTION:SPATTER_ADD_AMMO_EXTRACT]
+ [NAME:coat ammo with extract]
+ [BUILDING:CRAFTSMAN:NONE]
+ [SKILL:WAX_WORKING]
+ [REAGENT:extract:50:LIQUID_MISC:NONE:NONE:NONE]
+ [MIN_DIMENSION:50]
+ [REACTION_CLASS:CREATURE_EXTRACT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ [REAGENT:extract container:1:NONE:NONE:NONE:NONE]
+ [CONTAINS:extract]
+ [PRESERVE_REAGENT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ The object to improve must be after the input mat, so that it is known:
+ [REAGENT:object:1:AMMO:NONE:NONE:NONE]
+ [PRESERVE_REAGENT]
+ [MIN_DIMENSION:5] don't waste materials on single bolts
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ Need some excuse why the spatter is water-resistant:
+ [REAGENT:grease:1:GLOB:NONE:NONE:NONE][REACTION_CLASS:TALLOW][UNROTTEN]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ The probability is used as spatter size; Legendary gives +90%:
+ COVERED = liquid, GLAZED = solid, BANDS = paste, SPIKES = powder
+ [IMPROVEMENT:200:object:COVERED:GET_MATERIAL_FROM_REAGENT:extract:NONE]
+
+[REACTION:SPATTER_ADD_WEAPON_GCS]
+ [NAME:coat weapon with GCS venom]
+ [BUILDING:CRAFTSMAN:NONE]
+ [SKILL:WAX_WORKING]
+ [REAGENT:extract:150:LIQUID_MISC:NONE:CAVE_SPIDER_GIANT:POISON]
+ [MIN_DIMENSION:150]
+ [REACTION_CLASS:CREATURE_EXTRACT]
+ [REAGENT:extract container:1:NONE:NONE:NONE:NONE]
+ [CONTAINS:extract]
+ [PRESERVE_REAGENT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ The object to improve must be after the input mat, so that it is known:
+ [REAGENT:object:1:WEAPON:NONE:NONE:NONE]
+ [PRESERVE_REAGENT]
+ Need some excuse why the spatter is water-resistant:
+ [REAGENT:grease:1:GLOB:NONE:NONE:NONE][REACTION_CLASS:TALLOW][UNROTTEN]
+ The probability is used as spatter size; Legendary gives +90%:
+ COVERED = liquid, GLAZED = solid, BANDS = paste, SPIKES = powder
+ [IMPROVEMENT:800:object:COVERED:GET_MATERIAL_FROM_REAGENT:extract:NONE]
+
+[REACTION:SPATTER_ADD_AMMO_GCS]
+ [NAME:coat ammo with GCS venom]
+ [BUILDING:CRAFTSMAN:NONE]
+ [SKILL:WAX_WORKING]
+ [REAGENT:extract:50:LIQUID_MISC:NONE:CAVE_SPIDER_GIANT:POISON]
+ [MIN_DIMENSION:50]
+ [REACTION_CLASS:CREATURE_EXTRACT]
+ [REAGENT:extract container:1:NONE:NONE:NONE:NONE]
+ [CONTAINS:extract]
+ [PRESERVE_REAGENT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ The object to improve must be after the input mat, so that it is known:
+ [REAGENT:object:1:AMMO:NONE:NONE:NONE]
+ [PRESERVE_REAGENT]
+ Need some excuse why the spatter is water-resistant:
+ [REAGENT:grease:1:GLOB:NONE:NONE:NONE][REACTION_CLASS:TALLOW][UNROTTEN]
+ The probability is used as spatter size; Legendary gives +90%:
+ COVERED = liquid, GLAZED = solid, BANDS = paste, SPIKES = powder
+ [IMPROVEMENT:200:object:COVERED:GET_MATERIAL_FROM_REAGENT:extract:NONE]
+
+[REACTION:SPATTER_ADD_WEAPON_GDS]
+ [NAME:coat weapon with GDS venom]
+ [BUILDING:CRAFTSMAN:NONE]
+ [SKILL:WAX_WORKING]
+ [REAGENT:extract:150:LIQUID_MISC:NONE:SCORPION_DESERT_GIANT:POISON]
+ [MIN_DIMENSION:150]
+ [REACTION_CLASS:CREATURE_EXTRACT]
+ [REAGENT:extract container:1:NONE:NONE:NONE:NONE]
+ [CONTAINS:extract]
+ [PRESERVE_REAGENT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ The object to improve must be after the input mat, so that it is known:
+ [REAGENT:object:1:WEAPON:NONE:NONE:NONE]
+ [PRESERVE_REAGENT]
+ Need some excuse why the spatter is water-resistant:
+ [REAGENT:grease:1:GLOB:NONE:NONE:NONE][REACTION_CLASS:TALLOW][UNROTTEN]
+ The probability is used as spatter size; Legendary gives +90%:
+ COVERED = liquid, GLAZED = solid, BANDS = paste, SPIKES = powder
+ [IMPROVEMENT:800:object:COVERED:GET_MATERIAL_FROM_REAGENT:extract:NONE]
+
+[REACTION:SPATTER_ADD_AMMO_GDS]
+ [NAME:coat ammo with GDS venom]
+ [BUILDING:CRAFTSMAN:NONE]
+ [SKILL:WAX_WORKING]
+ [REAGENT:extract:50:LIQUID_MISC:NONE:SCORPION_DESERT_GIANT:POISON]
+ [MIN_DIMENSION:50]
+ [REACTION_CLASS:CREATURE_EXTRACT]
+ [REAGENT:extract container:1:NONE:NONE:NONE:NONE]
+ [CONTAINS:extract]
+ [PRESERVE_REAGENT]
+ [DOES_NOT_DETERMINE_PRODUCT_AMOUNT]
+ The object to improve must be after the input mat, so that it is known:
+ [REAGENT:object:1:AMMO:NONE:NONE:NONE]
+ [PRESERVE_REAGENT]
+ Need some excuse why the spatter is water-resistant:
+ [REAGENT:grease:1:GLOB:NONE:NONE:NONE][REACTION_CLASS:TALLOW][UNROTTEN]
+ The probability is used as spatter size; Legendary gives +90%:
+ COVERED = liquid, GLAZED = solid, BANDS = paste, SPIKES = powder
+ [IMPROVEMENT:200:object:COVERED:GET_MATERIAL_FROM_REAGENT:extract:NONE]
diff --git a/plugins/raw/reaction_steam_engine.txt b/plugins/raw/reaction_steam_engine.txt new file mode 100644 index 00000000..175ffdd5 --- /dev/null +++ b/plugins/raw/reaction_steam_engine.txt @@ -0,0 +1,14 @@ +reaction_steam_engine
+
+[OBJECT:REACTION]
+
+[REACTION:STOKE_BOILER]
+ [NAME:stoke the boiler]
+ [BUILDING:STEAM_ENGINE:CUSTOM_S]
+ [BUILDING:MAGMA_STEAM_ENGINE:CUSTOM_S]
+ [FUEL]
+ [SKILL:SMELT]
+ Dimension is the number of days it can produce 100 power * 100.
+ I.e. with 2000 it means energy of 1 job = 1 water wheel for 20 days.
+ [PRODUCT:100:1:LIQUID_MISC:NONE:WATER][PRODUCT_DIMENSION:2000]
+
diff --git a/plugins/rename.cpp b/plugins/rename.cpp index 1871d0f7..ecebbb90 100644 --- a/plugins/rename.cpp +++ b/plugins/rename.cpp @@ -3,12 +3,18 @@ #include "Export.h" #include "PluginManager.h" +#include <Error.h> +#include <LuaTools.h> + #include "modules/Gui.h" #include "modules/Translation.h" #include "modules/Units.h" +#include "modules/World.h" +#include "modules/Screen.h" -#include "DataDefs.h" +#include <VTableInterpose.h> #include "df/ui.h" +#include "df/ui_sidebar_menus.h" #include "df/world.h" #include "df/squad.h" #include "df/unit.h" @@ -18,6 +24,13 @@ #include "df/historical_figure_info.h" #include "df/assumed_identity.h" #include "df/language_name.h" +#include "df/building_stockpilest.h" +#include "df/building_workshopst.h" +#include "df/building_furnacest.h" +#include "df/building_trapst.h" +#include "df/building_siegeenginest.h" +#include "df/building_civzonest.h" +#include "df/viewscreen_dwarfmodest.h" #include "RemoteServer.h" #include "rename.pb.h" @@ -34,8 +47,11 @@ using namespace df::enums; using namespace dfproto; using df::global::ui; +using df::global::ui_sidebar_menus; using df::global::world; +DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event); + static command_result rename(color_ostream &out, vector <string> & parameters); DFHACK_PLUGIN("rename"); @@ -51,8 +67,32 @@ DFhackCExport command_result plugin_init (color_ostream &out, std::vector <Plugi " rename unit \"nickname\"\n" " rename unit-profession \"custom profession\"\n" " (a unit must be highlighted in the ui)\n" + " rename building \"nickname\"\n" + " (a building must be highlighted via 'q')\n" )); + + if (Core::getInstance().isWorldLoaded()) + plugin_onstatechange(out, SC_WORLD_LOADED); } + + return CR_OK; +} + +static void init_buildings(bool enable); + +DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event) +{ + switch (event) { + case SC_WORLD_LOADED: + init_buildings(true); + break; + case SC_WORLD_UNLOADED: + init_buildings(false); + break; + default: + break; + } + return CR_OK; } @@ -61,6 +101,165 @@ DFhackCExport command_result plugin_shutdown ( color_ostream &out ) return CR_OK; } +/* + * Building renaming - it needs some per-type hacking. + */ + +#define KNOWN_BUILDINGS \ + BUILDING('p', building_stockpilest, "Stockpile") \ + BUILDING('w', building_workshopst, NULL) \ + BUILDING('e', building_furnacest, NULL) \ + BUILDING('T', building_trapst, NULL) \ + BUILDING('i', building_siegeenginest, NULL) \ + BUILDING('Z', building_civzonest, "Zone") + +#define BUILDING(code, cname, tag) \ + struct cname##_hook : df::cname { \ + typedef df::cname interpose_base; \ + DEFINE_VMETHOD_INTERPOSE(void, getName, (std::string *buf)) { \ + if (!name.empty()) {\ + buf->clear(); \ + *buf += name; \ + *buf += " ("; \ + if (tag) *buf += (const char*)tag; \ + else { std::string tmp; INTERPOSE_NEXT(getName)(&tmp); *buf += tmp; } \ + *buf += ")"; \ + return; \ + } \ + else \ + INTERPOSE_NEXT(getName)(buf); \ + } \ + }; \ + IMPLEMENT_VMETHOD_INTERPOSE_PRIO(cname##_hook, getName, 100); +KNOWN_BUILDINGS +#undef BUILDING + +struct dwarf_render_zone_hook : df::viewscreen_dwarfmodest { + typedef df::viewscreen_dwarfmodest interpose_base; + + DEFINE_VMETHOD_INTERPOSE(void, render, ()) + { + INTERPOSE_NEXT(render)(); + + if (ui->main.mode == ui_sidebar_mode::Zones && + ui_sidebar_menus && ui_sidebar_menus->zone.selected && + !ui_sidebar_menus->zone.selected->name.empty()) + { + auto dims = Gui::getDwarfmodeViewDims(); + int width = dims.menu_x2 - dims.menu_x1 - 1; + + Screen::Pen pen(' ',COLOR_WHITE); + Screen::fillRect(pen, dims.menu_x1, dims.y1+1, dims.menu_x2, dims.y1+1); + + std::string name; + ui_sidebar_menus->zone.selected->getName(&name); + Screen::paintString(pen, dims.menu_x1+1, dims.y1+1, name.substr(0, width)); + } + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(dwarf_render_zone_hook, render); + +static char getBuildingCode(df::building *bld) +{ + CHECK_NULL_POINTER(bld); + +#define BUILDING(code, cname, tag) \ + if (strict_virtual_cast<df::cname>(bld)) return code; +KNOWN_BUILDINGS +#undef BUILDING + + return 0; +} + +static bool enable_building_rename(char code, bool enable) +{ + if (code == 'Z') + INTERPOSE_HOOK(dwarf_render_zone_hook, render).apply(enable); + + switch (code) { +#define BUILDING(code, cname, tag) \ + case code: return INTERPOSE_HOOK(cname##_hook, getName).apply(enable); +KNOWN_BUILDINGS +#undef BUILDING + default: + return false; + } +} + +static void disable_building_rename() +{ + INTERPOSE_HOOK(dwarf_render_zone_hook, render).remove(); + +#define BUILDING(code, cname, tag) \ + INTERPOSE_HOOK(cname##_hook, getName).remove(); +KNOWN_BUILDINGS +#undef BUILDING +} + +static bool is_enabled_building(char code) +{ + switch (code) { +#define BUILDING(code, cname, tag) \ + case code: return INTERPOSE_HOOK(cname##_hook, getName).is_applied(); +KNOWN_BUILDINGS +#undef BUILDING + default: + return false; + } +} + +static void init_buildings(bool enable) +{ + disable_building_rename(); + + if (enable) + { + auto pworld = Core::getInstance().getWorld(); + auto entry = pworld->GetPersistentData("rename/building_types"); + + if (entry.isValid()) + { + std::string val = entry.val(); + for (size_t i = 0; i < val.size(); i++) + enable_building_rename(val[i], true); + } + } +} + +static bool canRenameBuilding(df::building *bld) +{ + return getBuildingCode(bld) != 0; +} + +static bool isRenamingBuilding(df::building *bld) +{ + return is_enabled_building(getBuildingCode(bld)); +} + +static bool renameBuilding(df::building *bld, std::string name) +{ + char code = getBuildingCode(bld); + if (code == 0 && !name.empty()) + return false; + + if (!name.empty() && !is_enabled_building(code)) + { + auto pworld = Core::getInstance().getWorld(); + auto entry = pworld->GetPersistentData("rename/building_types", NULL); + if (!entry.isValid()) + return false; + + if (!enable_building_rename(code, true)) + return false; + + entry.val().push_back(code); + } + + bld->name = name; + return true; +} + static df::squad *getSquadByIndex(unsigned idx) { auto entity = df::historical_entity::find(ui->group_id); @@ -101,14 +300,37 @@ static command_result RenameUnit(color_ostream &stream, const RenameUnitIn *in) return CR_OK; } +static command_result RenameBuilding(color_ostream &stream, const RenameBuildingIn *in) +{ + auto building = df::building::find(in->building_id()); + if (!building) + return CR_NOT_FOUND; + + if (in->has_name()) + { + if (!renameBuilding(building, in->name())) + return CR_FAILURE; + } + + return CR_OK; +} + DFhackCExport RPCService *plugin_rpcconnect(color_ostream &) { RPCService *svc = new RPCService(); svc->addFunction("RenameSquad", RenameSquad); svc->addFunction("RenameUnit", RenameUnit); + svc->addFunction("RenameBuilding", RenameBuilding); return svc; } +DFHACK_PLUGIN_LUA_FUNCTIONS { + DFHACK_LUA_FUNCTION(canRenameBuilding), + DFHACK_LUA_FUNCTION(isRenamingBuilding), + DFHACK_LUA_FUNCTION(renameBuilding), + DFHACK_LUA_END +}; + static command_result rename(color_ostream &out, vector <string> ¶meters) { CoreSuspender suspend; @@ -167,6 +389,21 @@ static command_result rename(color_ostream &out, vector <string> ¶meters) unit->custom_profession = parameters[1]; } + else if (cmd == "building") + { + if (parameters.size() != 2) + return CR_WRONG_USAGE; + + df::building *bld = Gui::getSelectedBuilding(out, true); + if (!bld) + return CR_WRONG_USAGE; + + if (!renameBuilding(bld, parameters[1])) + { + out.printerr("This type of building is not supported.\n"); + return CR_FAILURE; + } + } else { if (!parameters.empty() && cmd != "?") diff --git a/plugins/ruby/README b/plugins/ruby/README index 8a473f33..9246fec8 100644 --- a/plugins/ruby/README +++ b/plugins/ruby/README @@ -177,7 +177,7 @@ Symbol. This works for array indexes too. ex: df.unit_find(:selected).status.labors[:HAUL_FOOD] = true df.map_tile_at(df.cursor).designation.liquid_type = :Water -Virtual method calls are supported for C++ objects, with a maximum of 4 +Virtual method calls are supported for C++ objects, with a maximum of 6 arguments. Arguments / return value are interpreted as Compound/Enums as specified in the vmethod definition in the xmls. @@ -213,8 +213,7 @@ Find the raws name of the plant under cursor p df.world.raws.plants.all[plant.mat_index].id Dig a channel under the cursor - df.map_designation_at(df.cursor).dig = :Channel - df.map_block_at(df.cursor).flags.designated = true + df.map_tile_at(df.cursor).dig(:Channel) Spawn 2/7 magma on the tile of the dwarf nicknamed 'hotfeet' hot = df.unit_citizens.find { |u| u.name.nickname == 'hotfeet' } diff --git a/plugins/ruby/building.rb b/plugins/ruby/building.rb index ab029ac2..59f71551 100644 --- a/plugins/ruby/building.rb +++ b/plugins/ruby/building.rb @@ -8,6 +8,8 @@ module DFHack k.building if k.type == :Building when :BuildingItems, :QueryBuilding world.selected_building + when :Zones, :ZonesPenInfo, :ZonesPitInfo, :ZonesHospitalInfo + ui_sidebar_menus.zone.selected end elsif what.kind_of?(Integer) @@ -21,8 +23,8 @@ module DFHack if b.room.extents dx = x - b.room.x dy = y - b.room.y - dx >= 0 and dx <= b.room.width and - dy >= 0 and dy <= b.room.height and + dx >= 0 and dx < b.room.width and + dy >= 0 and dy < b.room.height and b.room.extents[ dy*b.room.width + dx ] > 0 else b.x1 <= x and b.x2 >= x and @@ -46,12 +48,17 @@ module DFHack raise "invalid building type #{type.inspect}" if not cls bld = cls.cpp_new bld.race = ui.race_id - bld.setSubtype(subtype) if subtype != -1 - bld.setCustomType(custom) if custom != -1 + subtype = WorkshopType.int(subtype) if subtype.kind_of?(::Symbol) and type == :Workshop + subtype = FurnaceType.int(subtype) if subtype.kind_of?(::Symbol) and type == :Furnace + subtype = CivzoneType.int(subtype) if subtype.kind_of?(::Symbol) and type == :Civzone + subtype = TrapType.int(subtype) if subtype.kind_of?(::Symbol) and type == :Trap + bld.setSubtype(subtype) + bld.setCustomType(custom) case type when :Furnace; bld.melt_remainder[world.raws.inorganics.length] = 0 when :Coffin; bld.initBurialFlags when :Trap; bld.unk_cc = 500 if bld.trap_type == :PressurePlate + when :Floodgate; bld.gate_flags.closed = true end bld end @@ -176,9 +183,20 @@ module DFHack # set building at position, with optional width/height def building_position(bld, pos, w=nil, h=nil) - bld.x1 = pos.x - bld.y1 = pos.y - bld.z = pos.z + if pos.respond_to?(:x1) + x, y, z = pos.x1, pos.y1, pos.z + w ||= pos.x2-pos.x1+1 if pos.respond_to?(:x2) + h ||= pos.y2-pos.y1+1 if pos.respond_to?(:y2) + elsif pos.respond_to?(:x) + x, y, z = pos.x, pos.y, pos.z + else + x, y, z = pos + end + w ||= pos.w if pos.respond_to?(:w) + h ||= pos.h if pos.respond_to?(:h) + bld.x1 = x + bld.y1 = y + bld.z = z bld.x2 = bld.x1+w-1 if w bld.y2 = bld.y1+h-1 if h building_setsize(bld) @@ -193,7 +211,7 @@ module DFHack z = bld.z (bld.x1..bld.x2).each { |x| (bld.y1..bld.y2).each { |y| - next if !extents or bld.room.extents[bld.room.width*(y-bld.room.y)+(x-bld.room.x)] == 0 + next if extents and bld.room.extents[bld.room.width*(y-bld.room.y)+(x-bld.room.x)] == 0 next if not mb = map_block_at(x, y, z) des = mb.designation[x%16][y%16] des.pile = stockpile @@ -207,17 +225,24 @@ module DFHack } end - # link bld into other rooms if it is inside their extents + # link bld into other rooms if it is inside their extents or vice versa def building_linkrooms(bld) - didstuff = false world.buildings.other[:ANY_FREE].each { |ob| - next if !ob.is_room or ob.z != bld.z - next if !ob.room.extents or !ob.isExtentShaped or ob.room.extents[ob.room.width*(bld.y1-ob.room.y)+(bld.x1-ob.room.x)] == 0 - didstuff = true - ob.children << bld - bld.parents << ob + next if ob.z != bld.z + if bld.is_room and bld.room.extents + next if ob.is_room or ob.x1 < bld.room.x or ob.x1 >= bld.room.x+bld.room.width or ob.y1 < bld.room.y or ob.y1 >= bld.room.y+bld.room.height + next if bld.room.extents[bld.room.width*(ob.y1-bld.room.y)+(ob.x1-bld.room.x)] == 0 + ui.equipment.update.buildings = true + bld.children << ob + ob.parents << bld + elsif ob.is_room and ob.room.extents + next if bld.is_room or bld.x1 < ob.room.x or bld.x1 >= ob.room.x+ob.room.width or bld.y1 < ob.room.y or bld.y1 >= ob.room.y+ob.room.height + next if ob.room.extents[ob.room.width*(bld.y1-ob.room.y)+(bld.x1-ob.room.x)].to_i == 0 + ui.equipment.update.buildings = true + ob.children << bld + bld.parents << ob + end } - ui.equipment.update.buildings = true if didstuff end # link the building into the world, set map data, link rooms, bld.id @@ -274,14 +299,55 @@ module DFHack building_createdesign(bld, rough) end + # construct an abstract building (stockpile, farmplot, ...) + def building_construct_abstract(bld) + case bld.getType + when :Stockpile + max = df.world.buildings.other[:STOCKPILE].map { |s| s.stockpile_number }.max + bld.stockpile_number = max.to_i + 1 + when :Civzone + max = df.world.buildings.other[:ANY_ZONE].map { |z| z.zone_num }.max + bld.zone_num = max.to_i + 1 + end + building_link bld + if !bld.flags.exists + bld.flags.exists = true + bld.initFarmSeasons + end + end + + def building_setowner(bld, unit) + return unless bld.is_room + return if bld.owner == unit + + if bld.owner + if idx = bld.owner.owned_buildings.index { |ob| ob.id == bld.id } + bld.owner.owned_buildings.delete_at(idx) + end + if spouse = bld.owner.relations.spouse_tg and + idx = spouse.owned_buildings.index { |ob| ob.id == bld.id } + spouse.owned_buildings.delete_at(idx) + end + end + bld.owner = unit + if unit + unit.owned_buildings << bld + if spouse = bld.owner.relations.spouse_tg and + !spouse.owned_buildings.index { |ob| ob.id == bld.id } and + bld.canUseSpouseRoom + spouse.owned_buildings << bld + end + end + end + # creates a job to deconstruct the building def building_deconstruct(bld) job = Job.cpp_new refbuildingholder = GeneralRefBuildingHolderst.cpp_new job.job_type = :DestroyBuilding - refbuildingholder.building_id = building.id + refbuildingholder.building_id = bld.id job.references << refbuildingholder - building.jobs << job + bld.jobs << job job_link job job end diff --git a/plugins/ruby/codegen.pl b/plugins/ruby/codegen.pl index 593216d7..a615ab96 100755 --- a/plugins/ruby/codegen.pl +++ b/plugins/ruby/codegen.pl @@ -788,6 +788,7 @@ sub render_item_number { my $subtype = $item->getAttribute('ld:subtype'); my $meta = $item->getAttribute('ld:meta'); my $initvalue = $item->getAttribute('init-value'); + $initvalue ||= -1 if $item->getAttribute('refers-to') or $item->getAttribute('ref-target'); my $typename = $item->getAttribute('type-name'); undef $typename if ($meta and $meta eq 'bitfield-type'); my $g = $global_types{$typename} if ($typename); @@ -964,7 +965,7 @@ sub render_item_bytes { my $subtype = $item->getAttribute('ld:subtype'); if ($subtype eq 'padding') { } elsif ($subtype eq 'static-string') { - my $size = $item->getAttribute('size'); + my $size = $item->getAttribute('size') || -1; push @lines_rb, "static_string($size)"; } else { print "no render bytes $subtype\n"; diff --git a/plugins/ruby/item.rb b/plugins/ruby/item.rb index 34b40450..fc840f7a 100644 --- a/plugins/ruby/item.rb +++ b/plugins/ruby/item.rb @@ -4,9 +4,14 @@ module DFHack # arg similar to unit.rb/unit_find; no arg = 'k' menu def item_find(what=:selected, y=nil, z=nil) if what == :selected - if curview._rtti_classname == :viewscreen_itemst + case curview._rtti_classname + when :viewscreen_itemst ref = curview.entry_ref[curview.cursor_pos] ref.item_tg if ref.kind_of?(GeneralRefItem) + when :viewscreen_storesst # z/stocks + if curview.in_group_mode == 0 and curview.in_right_list == 1 + curview.items[curview.item_cursor] + end else case ui.main.mode when :LookAround @@ -26,6 +31,8 @@ module DFHack u = world.units.active[ui_selected_unit] u.inventory[ui_look_cursor].item if u and u.pos.z == cursor.z and ui_unit_view_mode.value == :Inventory and u.inventory[ui_look_cursor] + else + ui.follow_item_tg if ui.follow_item != -1 end end elsif what.kind_of?(Integer) diff --git a/plugins/ruby/map.rb b/plugins/ruby/map.rb index c99d5b88..37161470 100644 --- a/plugins/ruby/map.rb +++ b/plugins/ruby/map.rb @@ -26,7 +26,7 @@ module DFHack end end - def map_tile_at(x, y=nil, z=nil) + def map_tile_at(x=df.cursor, y=nil, z=nil) x = x.pos if x.respond_to?(:pos) x, y, z = x.x, x.y, x.z if x.respond_to?(:x) b = map_block_at(x, y, z) @@ -67,6 +67,14 @@ module DFHack @mapblock = b end + def offset(dx, dy=nil, dz=0) + if dx.respond_to?(:x) + dz = dx.z if dx.respond_to?(:z) + dx, dy = dx.x, dx.y + end + df.map_tile_at(@x+dx, @y+dy, @z+dz) + end + def designation @mapblock.designation[@dx][@dy] end @@ -188,6 +196,28 @@ module DFHack "#<MapTile pos=[#@x, #@y, #@z] shape=#{shape} tilemat=#{tilemat} material=#{mat_info.token}>" end + def dig(mode=:Default) + if mode == :Smooth + if (tilemat == :STONE or tilemat == :MINERAL) and caption !~ /smooth|pillar|fortification/i and # XXX caption.. + designation.smooth == 0 and (designation.hidden or not df.world.job_list.find { |j| + # the game removes 'smooth' designation as soon as it assigns a job, if we + # re-set it the game may queue another :DetailWall that will carve a fortification + (j.job_type == :DetailWall or j.job_type == :DetailFloor) and df.same_pos?(j, self) + }) + designation.dig = :No + designation.smooth = 1 + mapblock.flags.designated = true + end + else + return if mode != :No and designation.dig == :No and not designation.hidden and df.world.job_list.find { |j| + # someone already enroute to dig here, avoid 'Inappropriate dig square' spam + JobType::Type[j.job_type] == :Digging and df.same_pos?(j, self) + } + designation.dig = mode + mapblock.flags.designated = true if mode != :No + end + end + def spawn_liquid(quantity, is_magma=false, flowing=true) designation.flow_size = quantity designation.liquid_type = (is_magma ? :Magma : :Water) diff --git a/plugins/ruby/plant.rb b/plugins/ruby/plant.rb index 5d6b9d72..2f5a1c7c 100644 --- a/plugins/ruby/plant.rb +++ b/plugins/ruby/plant.rb @@ -51,7 +51,7 @@ module DFHack end SaplingToTreeAge = 120960 - def cuttrees(material=nil, count_max=100) + def cuttrees(material=nil, count_max=100, quiet=false) if !material # list trees cnt = Hash.new(0) @@ -62,7 +62,7 @@ module DFHack } cnt.sort_by { |mat, c| c }.each { |mat, c| name = @raws_tree_name[mat] - puts " #{name} #{c}" + puts " #{name} #{c}" unless quiet } else cnt = 0 @@ -78,11 +78,11 @@ module DFHack break if cnt == count_max end } - puts "Updated #{cnt} plant designations" + puts "Updated #{cnt} plant designations" unless quiet end end - def growtrees(material=nil, count_max=100) + def growtrees(material=nil, count_max=100, quiet=false) if !material # list plants cnt = Hash.new(0) @@ -93,7 +93,7 @@ module DFHack } cnt.sort_by { |mat, c| c }.each { |mat, c| name = @raws_tree_name[mat] - puts " #{name} #{c}" + puts " #{name} #{c}" unless quiet } else cnt = 0 @@ -104,7 +104,7 @@ module DFHack cnt += 1 break if cnt == count_max } - puts "Grown #{cnt} saplings" + puts "Grown #{cnt} saplings" unless quiet end end end diff --git a/plugins/ruby/ruby-autogen-defs.rb b/plugins/ruby/ruby-autogen-defs.rb index 3507508e..64c08fac 100644 --- a/plugins/ruby/ruby-autogen-defs.rb +++ b/plugins/ruby/ruby-autogen-defs.rb @@ -124,15 +124,17 @@ module DFHack case h when Hash; h.each { |k, v| send("#{k}=", v) } when Array; names = _field_names ; raise 'bad size' if names.length != h.length ; names.zip(h).each { |n, a| send("#{n}=", a) } - when Compound; _field_names.each { |n| send("#{n}=", h.send(n)) } - else raise 'wut?' + else _field_names.each { |n| send("#{n}=", h.send(n)) } end end def _fields ; self.class._fields.to_a ; end def _fields_ancestors ; self.class._fields_ancestors.to_a ; end def _field_names ; _fields_ancestors.map { |n, o, s| n } ; end def _rtti_classname ; self.class._rtti_classname ; end + def _raw_rtti_classname ; df.get_rtti_classname(df.get_vtable_ptr(@_memaddr)) if self.class._rtti_classname ; end def _sizeof ; self.class._sizeof ; end + def ==(o) ; o.kind_of?(Compound) and o._memaddr == _memaddr ; end + @@inspecting = {} # avoid infinite recursion on mutually-referenced objects def inspect cn = self.class.name.sub(/^DFHack::/, '') @@ -289,12 +291,12 @@ module DFHack # XXX shaky... def _set(v) - if v.kind_of?(Pointer) - DFHack.memory_write_int32(@_memaddr, v._getp) - elsif v.kind_of?(MemStruct) - DFHack.memory_write_int32(@_memaddr, v._memaddr) - else - _get._set(v) + case v + when Pointer; DFHack.memory_write_int32(@_memaddr, v._getp) + when MemStruct; DFHack.memory_write_int32(@_memaddr, v._memaddr) + when Integer; DFHack.memory_write_int32(@_memaddr, v) + when nil; DFHack.memory_write_int32(@_memaddr, 0) + else _get._set(v) end end @@ -328,6 +330,16 @@ module DFHack self end + def _set(v) + case v + when Pointer; DFHack.memory_write_int32(@_memaddr, v._getp) + when MemStruct; DFHack.memory_write_int32(@_memaddr, v._memaddr) + when Integer; DFHack.memory_write_int32(@_memaddr, v) + when nil; DFHack.memory_write_int32(@_memaddr, 0) + else raise "cannot PointerAry._set(#{v.inspect})" + end + end + def [](i) addr = _getp(i) return if addr == 0 @@ -411,11 +423,20 @@ module DFHack def initialize(length) @_length = length end + def length + if @_length == -1 + maxlen = 4096 - (@_memaddr & 0xfff) + maxlen += 4096 until len = DFHack.memory_read(@_memaddr, maxlen).index(?\0) + len + else + @_length + end + end def _get - DFHack.memory_read(@_memaddr, @_length) + DFHack.memory_read(@_memaddr, length) end def _set(v) - DFHack.memory_write(@_memaddr, v[0, @_length]) + DFHack.memory_write(@_memaddr, v[0, length]) end end @@ -464,7 +485,7 @@ module DFHack def []=(idx, v) idx += length if idx < 0 if idx >= length - insert_at(idx, 0) + insert_at(length, 0) while idx >= length elsif idx < 0 raise 'index out of bounds' end @@ -666,9 +687,9 @@ module DFHack @_tg = tg end - field(:_ptr, 0) { number 32, false } - field(:_prev, 4) { number 32, false } - field(:_next, 8) { number 32, false } + field(:_ptr, 0) { pointer } + field(:_prev, 4) { pointer } + field(:_next, 8) { pointer } def item # With the current xml structure, currently _tg designate @@ -682,22 +703,24 @@ module DFHack def item=(v) #addr = _ptr - #raise 'null pointer' if addr == 0 + #raise 'null pointer' if not addr #@_tg.at(addr)._set(v) raise 'null pointer' end def prev addr = _prev - return if addr == 0 + return if not addr @_tg._at(addr)._get end def next addr = _next - return if addr == 0 + return if not addr @_tg._at(addr)._get end + alias next= _next= + alias prev= _prev= include Enumerable def each @@ -745,6 +768,52 @@ module DFHack end end + class StlSet + attr_accessor :_memaddr, :_enum + def self.cpp_new(init=nil, enum=nil) + ret = new DFHack.memory_stlset_new, enum + init.each { |k| ret.set(k) } if init + ret + end + + def initialize(addr, enum=nil) + addr = nil if addr == 0 + @_memaddr = addr + @_enum = enum + end + + def isset(key) + raise unless @_memaddr + key = @_enum.int(key) if _enum + DFHack.memory_stlset_isset(@_memaddr, key) + end + alias is_set? isset + + def set(key) + raise unless @_memaddr + key = @_enum.int(key) if _enum + DFHack.memory_stlset_set(@_memaddr, key) + end + + def delete(key) + raise unless @_memaddr + key = @_enum.int(key) if _enum + DFHack.memory_stlset_deletekey(@_memaddr, key) + end + + def clear + raise unless @_memaddr + DFHack.memory_stlset_clear(@_memaddr) + end + + def _cpp_delete + raise unless @_memaddr + DFHack.memory_stlset_delete(@_memaddr) + @_memaddr = nil + end + end + + # cpp rtti name -> rb class @rtti_n2c = {} @rtti_c2n = {} @@ -793,8 +862,12 @@ module DFHack v if v != 0 end - def self.vmethod_call(obj, voff, a0=0, a1=0, a2=0, a3=0, a4=0) - vmethod_do_call(obj._memaddr, voff, vmethod_arg(a0), vmethod_arg(a1), vmethod_arg(a2), vmethod_arg(a3)) + def self.vmethod_call(obj, voff, a0=0, a1=0, a2=0, a3=0, a4=0, a5=0) + this = obj._memaddr + vt = df.get_vtable_ptr(this) + fptr = df.memory_read_int32(vt + voff) & 0xffffffff + vmethod_do_call(this, fptr, vmethod_arg(a0), vmethod_arg(a1), vmethod_arg(a2), + vmethod_arg(a3), vmethod_arg(a4), vmethod_arg(a5)) end def self.vmethod_arg(arg) @@ -803,7 +876,7 @@ module DFHack when true; 1 when Integer; arg #when String; [arg].pack('p').unpack('L')[0] # raw pointer to buffer - when MemHack::Compound; arg._memaddr + when MemHack::Compound, StlSet; arg._memaddr else raise "bad vmethod arg #{arg.class}" end end diff --git a/plugins/ruby/ruby.cpp b/plugins/ruby/ruby.cpp index 1391faa4..7bd6d13e 100644 --- a/plugins/ruby/ruby.cpp +++ b/plugins/ruby/ruby.cpp @@ -4,6 +4,7 @@ #include "Export.h" #include "PluginManager.h" #include "VersionInfo.h" +#include "MemAccess.h" #include "DataDefs.h" #include "df/global_objects.h" @@ -204,8 +205,6 @@ DFhackCExport command_result plugin_onstatechange ( color_ostream &out, state_ch static command_result df_rubyeval(color_ostream &out, std::vector <std::string> & parameters) { - command_result ret; - if (parameters.size() == 1 && (parameters[0] == "help" || parameters[0] == "?")) { out.print("This command executes an arbitrary ruby statement.\n"); @@ -597,6 +596,45 @@ static VALUE rb_dfmemory_write_float(VALUE self, VALUE addr, VALUE val) return Qtrue; } +// return memory permissions at address (eg "rx", nil if unmapped) +static VALUE rb_dfmemory_check(VALUE self, VALUE addr) +{ + void *ptr = (void*)rb_num2ulong(addr); + std::vector<t_memrange> ranges; + Core::getInstance().p->getMemRanges(ranges); + + unsigned i = 0; + while (i < ranges.size() && ranges[i].end <= ptr) + i++; + + if (i >= ranges.size() || ranges[i].start > ptr || !ranges[i].valid) + return Qnil; + + std::string perm = ""; + if (ranges[i].read) + perm += "r"; + if (ranges[i].write) + perm += "w"; + if (ranges[i].execute) + perm += "x"; + if (ranges[i].shared) + perm += "s"; + + return rb_str_new(perm.c_str(), perm.length()); +} + +// memory write (tmp override page permissions, eg patch code) +static VALUE rb_dfmemory_patch(VALUE self, VALUE addr, VALUE raw) +{ + int strlen = FIX2INT(rb_funcall(raw, rb_intern("length"), 0)); + bool ret; + + ret = Core::getInstance().p->patchMemory((void*)rb_num2ulong(addr), + rb_string_value_ptr(&raw), strlen); + + return ret ? Qtrue : Qfalse; +} + // stl::string static VALUE rb_dfmemory_stlstring_new(VALUE self) @@ -795,11 +833,54 @@ static VALUE rb_dfmemory_bitarray_set(VALUE self, VALUE addr, VALUE idx, VALUE v return Qtrue; } +// add basic support for std::set<uint32> used for passing keyboard keys to viewscreens +#include <set> +static VALUE rb_dfmemory_set_new(VALUE self) +{ + std::set<unsigned long> *ptr = new std::set<unsigned long>; + return rb_uint2inum((uint32_t)ptr); +} + +static VALUE rb_dfmemory_set_delete(VALUE self, VALUE set) +{ + std::set<unsigned long> *ptr = (std::set<unsigned long>*)rb_num2ulong(set); + if (ptr) + delete ptr; + return Qtrue; +} + +static VALUE rb_dfmemory_set_set(VALUE self, VALUE set, VALUE key) +{ + std::set<unsigned long> *ptr = (std::set<unsigned long>*)rb_num2ulong(set); + ptr->insert(rb_num2ulong(key)); + return Qtrue; +} + +static VALUE rb_dfmemory_set_isset(VALUE self, VALUE set, VALUE key) +{ + std::set<unsigned long> *ptr = (std::set<unsigned long>*)rb_num2ulong(set); + return ptr->count(rb_num2ulong(key)) ? Qtrue : Qfalse; +} + +static VALUE rb_dfmemory_set_deletekey(VALUE self, VALUE set, VALUE key) +{ + std::set<unsigned long> *ptr = (std::set<unsigned long>*)rb_num2ulong(set); + ptr->erase(rb_num2ulong(key)); + return Qtrue; +} + +static VALUE rb_dfmemory_set_clear(VALUE self, VALUE set) +{ + std::set<unsigned long> *ptr = (std::set<unsigned long>*)rb_num2ulong(set); + ptr->clear(); + return Qtrue; +} + /* call an arbitrary object virtual method */ #ifdef WIN32 -__declspec(naked) static int raw_vcall(char **that, unsigned long voff, unsigned long a0, - unsigned long a1, unsigned long a2, unsigned long a3) +__declspec(naked) static int raw_vcall(void *that, void *fptr, unsigned long a0, + unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5) { // __thiscall requires that the callee cleans up the stack // here we dont know how many arguments it will take, so @@ -808,6 +889,8 @@ __declspec(naked) static int raw_vcall(char **that, unsigned long voff, unsigned push ebp mov ebp, esp + push a5 + push a4 push a3 push a2 push a1 @@ -815,9 +898,7 @@ __declspec(naked) static int raw_vcall(char **that, unsigned long voff, unsigned mov ecx, that - mov eax, [ecx] - add eax, voff - call [eax] + call fptr mov esp, ebp pop ebp @@ -825,25 +906,25 @@ __declspec(naked) static int raw_vcall(char **that, unsigned long voff, unsigned } } #else -static int raw_vcall(char **that, unsigned long voff, unsigned long a0, - unsigned long a1, unsigned long a2, unsigned long a3) +static int raw_vcall(void *that, void *fptr, unsigned long a0, + unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5) { - int (*fptr)(char **me, int, int, int, int); - fptr = (decltype(fptr))*(void**)(*that + voff); - return fptr(that, a0, a1, a2, a3); + int (*t_fptr)(void *me, int, int, int, int, int, int); + t_fptr = (decltype(t_fptr))fptr; + return t_fptr(that, a0, a1, a2, a3, a4, a5); } #endif // call an arbitrary vmethod, convert args/ret to native values for raw_vcall -static VALUE rb_dfvcall(VALUE self, VALUE cppobj, VALUE cppvoff, VALUE a0, VALUE a1, VALUE a2, VALUE a3) +static VALUE rb_dfvcall(VALUE self, VALUE cppobj, VALUE fptr, VALUE a0, VALUE a1, VALUE a2, VALUE a3, VALUE a4, VALUE a5) { - return rb_int2inum(raw_vcall((char**)rb_num2ulong(cppobj), rb_num2ulong(cppvoff), + return rb_int2inum(raw_vcall((void*)rb_num2ulong(cppobj), (void*)rb_num2ulong(fptr), rb_num2ulong(a0), rb_num2ulong(a1), - rb_num2ulong(a2), rb_num2ulong(a3))); + rb_num2ulong(a2), rb_num2ulong(a3), + rb_num2ulong(a4), rb_num2ulong(a5))); } - // define module DFHack and its methods static void ruby_bind_dfhack(void) { rb_cDFHack = rb_define_module("DFHack"); @@ -862,7 +943,7 @@ static void ruby_bind_dfhack(void) { rb_define_singleton_method(rb_cDFHack, "print_err", RUBY_METHOD_FUNC(rb_dfprint_err), 1); rb_define_singleton_method(rb_cDFHack, "malloc", RUBY_METHOD_FUNC(rb_dfmalloc), 1); rb_define_singleton_method(rb_cDFHack, "free", RUBY_METHOD_FUNC(rb_dffree), 1); - rb_define_singleton_method(rb_cDFHack, "vmethod_do_call", RUBY_METHOD_FUNC(rb_dfvcall), 6); + rb_define_singleton_method(rb_cDFHack, "vmethod_do_call", RUBY_METHOD_FUNC(rb_dfvcall), 8); rb_define_singleton_method(rb_cDFHack, "memory_read", RUBY_METHOD_FUNC(rb_dfmemory_read), 2); rb_define_singleton_method(rb_cDFHack, "memory_read_int8", RUBY_METHOD_FUNC(rb_dfmemory_read_int8), 1); @@ -875,6 +956,8 @@ static void ruby_bind_dfhack(void) { rb_define_singleton_method(rb_cDFHack, "memory_write_int16", RUBY_METHOD_FUNC(rb_dfmemory_write_int16), 2); rb_define_singleton_method(rb_cDFHack, "memory_write_int32", RUBY_METHOD_FUNC(rb_dfmemory_write_int32), 2); rb_define_singleton_method(rb_cDFHack, "memory_write_float", RUBY_METHOD_FUNC(rb_dfmemory_write_float), 2); + rb_define_singleton_method(rb_cDFHack, "memory_check", RUBY_METHOD_FUNC(rb_dfmemory_check), 1); + rb_define_singleton_method(rb_cDFHack, "memory_patch", RUBY_METHOD_FUNC(rb_dfmemory_patch), 2); rb_define_singleton_method(rb_cDFHack, "memory_stlstring_new", RUBY_METHOD_FUNC(rb_dfmemory_stlstring_new), 0); rb_define_singleton_method(rb_cDFHack, "memory_stlstring_delete", RUBY_METHOD_FUNC(rb_dfmemory_stlstring_delete), 1); @@ -908,4 +991,10 @@ static void ruby_bind_dfhack(void) { rb_define_singleton_method(rb_cDFHack, "memory_bitarray_resize", RUBY_METHOD_FUNC(rb_dfmemory_bitarray_resize), 2); rb_define_singleton_method(rb_cDFHack, "memory_bitarray_isset", RUBY_METHOD_FUNC(rb_dfmemory_bitarray_isset), 2); rb_define_singleton_method(rb_cDFHack, "memory_bitarray_set", RUBY_METHOD_FUNC(rb_dfmemory_bitarray_set), 3); + rb_define_singleton_method(rb_cDFHack, "memory_stlset_new", RUBY_METHOD_FUNC(rb_dfmemory_set_new), 0); + rb_define_singleton_method(rb_cDFHack, "memory_stlset_delete", RUBY_METHOD_FUNC(rb_dfmemory_set_delete), 1); + rb_define_singleton_method(rb_cDFHack, "memory_stlset_set", RUBY_METHOD_FUNC(rb_dfmemory_set_set), 2); + rb_define_singleton_method(rb_cDFHack, "memory_stlset_isset", RUBY_METHOD_FUNC(rb_dfmemory_set_isset), 2); + rb_define_singleton_method(rb_cDFHack, "memory_stlset_deletekey", RUBY_METHOD_FUNC(rb_dfmemory_set_deletekey), 2); + rb_define_singleton_method(rb_cDFHack, "memory_stlset_clear", RUBY_METHOD_FUNC(rb_dfmemory_set_clear), 1); } diff --git a/plugins/ruby/ruby.rb b/plugins/ruby/ruby.rb index 8c2c9796..81b73b7c 100644 --- a/plugins/ruby/ruby.rb +++ b/plugins/ruby/ruby.rb @@ -25,11 +25,11 @@ end module DFHack class OnupdateCallback attr_accessor :callback, :timelimit, :minyear, :minyeartick - def initialize(cb, tl) + def initialize(cb, tl, initdelay=0) @callback = cb @ticklimit = tl @minyear = (tl ? df.cur_year : 0) - @minyeartick = (tl ? df.cur_year_tick : 0) + @minyeartick = (tl ? df.cur_year_tick+initdelay : 0) end # run callback if timedout @@ -61,9 +61,9 @@ module DFHack # register a callback to be called every gframe or more # ex: DFHack.onupdate_register { DFHack.world.units[0].counters.job_counter = 0 } - def onupdate_register(ticklimit=nil, &b) + def onupdate_register(ticklimit=nil, initialtickdelay=0, &b) @onupdate_list ||= [] - @onupdate_list << OnupdateCallback.new(b, ticklimit) + @onupdate_list << OnupdateCallback.new(b, ticklimit, initialtickdelay) DFHack.onupdate_active = true if onext = @onupdate_list.sort.first DFHack.onupdate_minyear = onext.minyear @@ -81,6 +81,13 @@ module DFHack end end + # same as onupdate_register, but remove the callback once it returns true + def onupdate_register_once(*a) + handle = onupdate_register(*a) { + onupdate_unregister(handle) if yield + } + end + TICKS_PER_YEAR = 1200*28*12 # this method is called by dfhack every 'onupdate' if onupdate_active is true def onupdate @@ -112,6 +119,14 @@ module DFHack @onstatechange_list.delete b end + # same as onstatechange_register, but auto-unregisters if the block returns true + def onstatechange_register_once + handle = onstatechange_register { |st| + onstatechange_unregister(handle) if yield(st) + } + end + + # this method is called by dfhack every 'onstatechange' def onstatechange(newstate) @onstatechange_list ||= [] diff --git a/plugins/ruby/ui.rb b/plugins/ruby/ui.rb index 9dded66c..a9dd0543 100644 --- a/plugins/ruby/ui.rb +++ b/plugins/ruby/ui.rb @@ -66,11 +66,12 @@ module DFHack world.status.reports << rep world.status.announcements << rep world.status.display_timer = 2000 + yield rep if block_given? end end - # add an announcement to display in a game popup message - # (eg "the megabeast foobar arrived") + # add an announcement to display in a game popup message + # (eg "the megabeast foobar arrived") def popup_announcement(str, color=nil, bright=nil) pop = PopupMessage.cpp_new(:text => str) pop.color = color if color @@ -78,4 +79,13 @@ module DFHack world.status.popups << pop end end + + class Viewscreen + def feed_keys(*keys) + keyset = StlSet.cpp_new(keys, InterfaceKey) + ret = feed(keyset) + keyset._cpp_delete + ret + end + end end diff --git a/plugins/ruby/unit.rb b/plugins/ruby/unit.rb index ebcf249d..139a375b 100644 --- a/plugins/ruby/unit.rb +++ b/plugins/ruby/unit.rb @@ -12,9 +12,15 @@ module DFHack ref.unit_tg if ref.kind_of?(GeneralRefUnit) when :viewscreen_unitlistst v = curview - # TODO fix xml to use enums everywhere - page = DFHack::ViewscreenUnitlistst_TPage.int(v.page) - v.units[page][v.cursor_pos[page]] + v.units[v.page][v.cursor_pos[v.page]] + when :viewscreen_petst + v = curview + case v.mode + when :List + v.animal[v.cursor].unit if !v.is_vermin[v.cursor] + when :SelectTrainer + v.trainer_unit[v.trainer_cursor] + end else case ui.main.mode when :ViewUnits @@ -24,6 +30,8 @@ module DFHack when :LookAround k = ui_look_list.items[ui_look_cursor] k.unit if k.type == :Unit + else + ui.follow_unit_tg if ui.follow_unit != -1 end end elsif what.kind_of?(Integer) @@ -41,48 +49,60 @@ module DFHack # returns an Array of all units that are current fort citizen (dwarves, on map, not hostile) def unit_citizens - race = ui.race_id - civ = ui.civ_id world.units.active.find_all { |u| - u.race == race and u.civ_id == civ and !u.flags1.dead and !u.flags1.merchant and - !u.flags1.diplomat and !u.flags2.resident and !u.flags3.ghostly and - !u.curse.add_tags1.OPPOSED_TO_LIFE and !u.curse.add_tags1.CRAZED and - u.mood != :Berserk - # TODO check curse ; currently this should keep vampires, but may include werebeasts + unit_iscitizen(u) } end + def unit_iscitizen(u) + u.race == ui.race_id and u.civ_id == ui.civ_id and !u.flags1.dead and !u.flags1.merchant and !u.flags1.forest and + !u.flags1.diplomat and !u.flags2.resident and !u.flags3.ghostly and + !u.curse.add_tags1.OPPOSED_TO_LIFE and !u.curse.add_tags1.CRAZED and + u.mood != :Berserk + # TODO check curse ; currently this should keep vampires, but may include werebeasts + end + # list workers (citizen, not crazy / child / inmood / noble) def unit_workers - unit_citizens.find_all { |u| - u.mood == :None and - u.profession != :CHILD and - u.profession != :BABY and - # TODO MENIAL_WORK_EXEMPTION_SPOUSE - !unit_entitypositions(u).find { |pos| pos.flags[:MENIAL_WORK_EXEMPTION] } + world.units.active.find_all { |u| + unit_isworker(u) } end + def unit_isworker(u) + unit_iscitizen(u) and + u.mood == :None and + u.profession != :CHILD and + u.profession != :BABY and + # TODO MENIAL_WORK_EXEMPTION_SPOUSE + !unit_entitypositions(u).find { |pos| pos.flags[:MENIAL_WORK_EXEMPTION] } + end + # list currently idle workers def unit_idlers - unit_workers.find_all { |u| - # current_job includes eat/drink/sleep/pickupequip - !u.job.current_job and - # filter 'attend meeting' - not u.specific_refs.find { |s| s.type == :ACTIVITY } and - # filter soldiers (TODO check schedule) - u.military.squad_index == -1 and - # filter 'on break' - not u.status.misc_traits.find { |t| t.id == :OnBreak } + world.units.active.find_all { |u| + unit_isidler(u) } end + def unit_isidler(u) + unit_isworker(u) and + # current_job includes eat/drink/sleep/pickupequip + !u.job.current_job and + # filter 'attend meeting' + not u.specific_refs.find { |s| s.type == :ACTIVITY } and + # filter soldiers (TODO check schedule) + u.military.squad_index == -1 and + # filter 'on break' + not u.status.misc_traits.find { |t| t.id == :OnBreak } + end + def unit_entitypositions(unit) list = [] - return list if not hf = world.history.figures.binsearch(unit.hist_figure_id) + return list if not hf = unit.hist_figure_tg hf.entity_links.each { |el| next if el._rtti_classname != :histfig_entity_link_positionst - next if not ent = world.entities.all.binsearch(el.entity_id) + next if not ent = el.entity_tg next if not pa = ent.positions.assignments.binsearch(el.assignment_id) next if not pos = ent.positions.own.binsearch(pa.position_id) list << pos @@ -92,7 +112,7 @@ module DFHack end class LanguageName - def to_s(english=true) + def to_s(english=false) df.translate_name(self, english) end end diff --git a/plugins/siege-engine.cpp b/plugins/siege-engine.cpp new file mode 100644 index 00000000..7c880351 --- /dev/null +++ b/plugins/siege-engine.cpp @@ -0,0 +1,1871 @@ +#include "Core.h" +#include <Console.h> +#include <Export.h> +#include <Error.h> +#include <PluginManager.h> +#include <modules/Gui.h> +#include <modules/Screen.h> +#include <modules/Maps.h> +#include <modules/MapCache.h> +#include <modules/World.h> +#include <modules/Units.h> +#include <modules/Job.h> +#include <modules/Materials.h> +#include <LuaTools.h> +#include <TileTypes.h> +#include <vector> +#include <cstdio> +#include <stack> +#include <string> +#include <cmath> +#include <string.h> + +#include <VTableInterpose.h> +#include "df/graphic.h" +#include "df/building_siegeenginest.h" +#include "df/builtin_mats.h" +#include "df/world.h" +#include "df/buildings_other_id.h" +#include "df/job.h" +#include "df/building_drawbuffer.h" +#include "df/ui.h" +#include "df/viewscreen_dwarfmodest.h" +#include "df/ui_build_selector.h" +#include "df/flow_info.h" +#include "df/report.h" +#include "df/proj_itemst.h" +#include "df/unit.h" +#include "df/unit_soul.h" +#include "df/unit_skill.h" +#include "df/physical_attribute_type.h" +#include "df/creature_raw.h" +#include "df/caste_raw.h" +#include "df/caste_raw_flags.h" +#include "df/assumed_identity.h" +#include "df/game_mode.h" +#include "df/unit_misc_trait.h" +#include "df/job.h" +#include "df/job_item.h" +#include "df/item_actual.h" +#include "df/items_other_id.h" +#include "df/building_stockpilest.h" +#include "df/stockpile_links.h" +#include "df/workshop_profile.h" +#include "df/strain_type.h" +#include "df/material.h" +#include "df/flow_type.h" + +#include "MiscUtils.h" + +using std::vector; +using std::string; +using std::stack; +using namespace DFHack; +using namespace df::enums; + +using df::global::gamemode; +using df::global::gps; +using df::global::world; +using df::global::ui; +using df::global::ui_build_selector; + +using Screen::Pen; + +DFHACK_PLUGIN("siege-engine"); + +/* + * Misc. utils + */ + +typedef std::pair<df::coord, df::coord> coord_range; + +static void set_range(coord_range *target, df::coord p1, df::coord p2) +{ + if (!p1.isValid() || !p2.isValid()) + { + *target = coord_range(); + } + else + { + target->first.x = std::min(p1.x, p2.x); + target->first.y = std::min(p1.y, p2.y); + target->first.z = std::min(p1.z, p2.z); + target->second.x = std::max(p1.x, p2.x); + target->second.y = std::max(p1.y, p2.y); + target->second.z = std::max(p1.z, p2.z); + } +} + +static bool is_range_valid(const coord_range &target) +{ + return target.first.isValid() && target.second.isValid(); +} + +static bool is_in_range(const coord_range &target, df::coord pos) +{ + return target.first.isValid() && target.second.isValid() && + target.first.x <= pos.x && pos.x <= target.second.x && + target.first.y <= pos.y && pos.y <= target.second.y && + target.first.z <= pos.z && pos.z <= target.second.z; +} + +static std::pair<int, int> get_engine_range(df::building_siegeenginest *bld) +{ + if (bld->type == siegeengine_type::Ballista) + return std::make_pair(1, 200); + else + return std::make_pair(30, 100); +} + +static void orient_engine(df::building_siegeenginest *bld, df::coord target) +{ + int dx = target.x - bld->centerx; + int dy = target.y - bld->centery; + + if (abs(dx) > abs(dy)) + bld->facing = (dx > 0) ? + df::building_siegeenginest::Right : + df::building_siegeenginest::Left; + else + bld->facing = (dy > 0) ? + df::building_siegeenginest::Down : + df::building_siegeenginest::Up; +} + +static int random_int(int val) +{ + return int(int64_t(rand())*val/RAND_MAX); +} + +static int point_distance(df::coord speed) +{ + return std::max(abs(speed.x), std::max(abs(speed.y), abs(speed.z))); +} + +inline void normalize(float &x, float &y, float &z) +{ + float dist = sqrtf(x*x + y*y + z*z); + if (dist == 0.0f) return; + x /= dist; y /= dist; z /= dist; +} + +static void random_direction(float &x, float &y, float &z) +{ + float a, b, d; + for (;;) { + a = (rand() + 0.5f)*2.0f/RAND_MAX - 1.0f; + b = (rand() + 0.5f)*2.0f/RAND_MAX - 1.0f; + d = a*a + b*b; + if (d < 1.0f) + break; + } + + float sq = sqrtf(1-d); + x = 2.0f*a*sq; + y = 2.0f*b*sq; + z = 1.0f - 2.0f*d; +} + +static const int WEAR_TICKS = 806400; + +static bool apply_impact_damage(df::item *item, int minv, int maxv) +{ + MaterialInfo info(item); + if (!info.isValid()) + { + item->setWear(3); + return false; + } + + auto &strength = info.material->strength; + + // Use random strain type excluding COMPRESSIVE (conveniently last) + int type = random_int(strain_type::COMPRESSIVE); + int power = minv + random_int(maxv-minv+1); + + // High elasticity materials just bend + if (strength.strain_at_yield[type] >= 5000) + return true; + + // Instant fracture? + int fracture = strength.fracture[type]; + if (fracture <= power) + { + item->setWear(3); + return false; + } + + // Impact within elastic strain range? + int yield = strength.yield[type]; + if (yield > power) + return true; + + // Can wear? + auto actual = virtual_cast<df::item_actual>(item); + if (!actual) + return false; + + // Transform plastic deformation to wear + int max_wear = WEAR_TICKS * 4; + int cur_wear = WEAR_TICKS * actual->wear + actual->wear_timer; + cur_wear += int64_t(power - yield)*max_wear/(fracture - yield); + + if (cur_wear >= max_wear) + { + actual->wear = 3; + return false; + } + else + { + actual->wear = cur_wear / WEAR_TICKS; + actual->wear_timer = cur_wear % WEAR_TICKS; + return true; + } +} + +/* + * Configuration object + */ + +static bool enable_plugin(); + +struct EngineInfo { + int id; + df::building_siegeenginest *bld; + + df::coord center; + coord_range building_rect; + + bool is_catapult; + int proj_speed, hit_delay; + std::pair<int, int> fire_range; + + coord_range target; + + df::job_item_vector_id ammo_vector_id; + df::item_type ammo_item_type; + + int operator_id, operator_frame; + + std::set<int> stockpiles; + df::stockpile_links links; + df::workshop_profile profile; + + bool hasTarget() { return is_range_valid(target); } + bool onTarget(df::coord pos) { return is_in_range(target, pos); } + df::coord getTargetSize() { return target.second - target.first; } + + bool isInRange(int dist) { + return dist >= fire_range.first && dist <= fire_range.second; + } +}; + +static std::map<df::building*, EngineInfo*> engines; +static std::map<df::coord, df::building*> coord_engines; + +static EngineInfo *find_engine(df::building *bld, bool create = false) +{ + auto ebld = strict_virtual_cast<df::building_siegeenginest>(bld); + if (!ebld) + return NULL; + + auto &obj = engines[bld]; + + if (obj) + { + obj->bld = ebld; + return obj; + } + + if (!create) + return NULL; + + obj = new EngineInfo(); + + obj->id = bld->id; + obj->bld = ebld; + obj->center = df::coord(bld->centerx, bld->centery, bld->z); + obj->building_rect = coord_range( + df::coord(bld->x1, bld->y1, bld->z), + df::coord(bld->x2, bld->y2, bld->z) + ); + obj->is_catapult = (ebld->type == siegeengine_type::Catapult); + obj->proj_speed = 2; + obj->hit_delay = obj->is_catapult ? 2 : -1; + obj->fire_range = get_engine_range(ebld); + + obj->ammo_vector_id = job_item_vector_id::BOULDER; + obj->ammo_item_type = item_type::BOULDER; + + obj->operator_id = obj->operator_frame = -1; + + coord_engines[obj->center] = bld; + return obj; +} + +static EngineInfo *find_engine(lua_State *L, int idx, bool create = false, bool silent = false) +{ + auto bld = Lua::CheckDFObject<df::building_siegeenginest>(L, idx); + + auto engine = find_engine(bld, create); + if (!engine && !silent) + luaL_error(L, "no such engine"); + + return engine; +} + +static EngineInfo *find_engine(df::coord pos) +{ + auto engine = find_engine(coord_engines[pos]); + + if (engine) + { + auto bld0 = df::building::find(engine->id); + auto bld = strict_virtual_cast<df::building_siegeenginest>(bld0); + if (!bld) + return NULL; + + engine->bld = bld; + } + + return engine; +} + +/* + * Configuration management + */ + +static void clear_engines() +{ + for (auto it = engines.begin(); it != engines.end(); ++it) + delete it->second; + engines.clear(); + coord_engines.clear(); +} + +static void load_engines() +{ + clear_engines(); + + auto pworld = Core::getInstance().getWorld(); + std::vector<PersistentDataItem> vec; + + pworld->GetPersistentData(&vec, "siege-engine/target/", true); + for (auto it = vec.begin(); it != vec.end(); ++it) + { + auto engine = find_engine(df::building::find(it->ival(0)), true); + if (!engine) continue; + engine->target.first = df::coord(it->ival(1), it->ival(2), it->ival(3)); + engine->target.second = df::coord(it->ival(4), it->ival(5), it->ival(6)); + } + + pworld->GetPersistentData(&vec, "siege-engine/ammo/", true); + for (auto it = vec.begin(); it != vec.end(); ++it) + { + auto engine = find_engine(df::building::find(it->ival(0)), true); + if (!engine) continue; + engine->ammo_vector_id = (df::job_item_vector_id)it->ival(1); + engine->ammo_item_type = (df::item_type)it->ival(2); + } + + pworld->GetPersistentData(&vec, "siege-engine/stockpiles/", true); + for (auto it = vec.begin(); it != vec.end(); ++it) + { + auto engine = find_engine(df::building::find(it->ival(0)), true); + if (!engine) + continue; + auto pile = df::building::find(it->ival(1)); + if (!pile || pile->getType() != building_type::Stockpile) + { + pworld->DeletePersistentData(*it); + continue;; + } + + engine->stockpiles.insert(it->ival(1)); + } + + pworld->GetPersistentData(&vec, "siege-engine/profiles/", true); + for (auto it = vec.begin(); it != vec.end(); ++it) + { + auto engine = find_engine(df::building::find(it->ival(0)), true); + if (!engine) continue; + engine->profile.min_level = it->ival(1); + engine->profile.max_level = it->ival(2); + } + + pworld->GetPersistentData(&vec, "siege-engine/profile-workers/", true); + for (auto it = vec.begin(); it != vec.end(); ++it) + { + auto engine = find_engine(df::building::find(it->ival(0)), true); + if (!engine) + continue; + auto unit = df::unit::find(it->ival(1)); + if (!unit || !Units::isCitizen(unit)) + { + pworld->DeletePersistentData(*it); + continue; + } + engine->profile.permitted_workers.push_back(it->ival(1)); + } +} + +static int getTargetArea(lua_State *L) +{ + auto engine = find_engine(L, 1, false, true); + + if (engine && engine->hasTarget()) + { + Lua::Push(L, engine->target.first); + Lua::Push(L, engine->target.second); + } + else + { + lua_pushnil(L); + lua_pushnil(L); + } + + return 2; +} + +static void clearTargetArea(df::building_siegeenginest *bld) +{ + CHECK_NULL_POINTER(bld); + + if (auto engine = find_engine(bld)) + engine->target = coord_range(); + + auto pworld = Core::getInstance().getWorld(); + auto key = stl_sprintf("siege-engine/target/%d", bld->id); + pworld->DeletePersistentData(pworld->GetPersistentData(key)); +} + +static bool setTargetArea(df::building_siegeenginest *bld, df::coord target_min, df::coord target_max) +{ + CHECK_NULL_POINTER(bld); + CHECK_INVALID_ARGUMENT(target_min.isValid() && target_max.isValid()); + + if (!enable_plugin()) + return false; + + auto pworld = Core::getInstance().getWorld(); + auto key = stl_sprintf("siege-engine/target/%d", bld->id); + auto entry = pworld->GetPersistentData(key, NULL); + if (!entry.isValid()) + return false; + + auto engine = find_engine(bld, true); + + set_range(&engine->target, target_min, target_max); + + entry.ival(0) = bld->id; + entry.ival(1) = engine->target.first.x; + entry.ival(2) = engine->target.first.y; + entry.ival(3) = engine->target.first.z; + entry.ival(4) = engine->target.second.x; + entry.ival(5) = engine->target.second.y; + entry.ival(6) = engine->target.second.z; + + df::coord sum = target_min + target_max; + orient_engine(bld, df::coord(sum.x/2, sum.y/2, sum.z/2)); + + return true; +} + +static int getAmmoItem(lua_State *L) +{ + auto engine = find_engine(L, 1, false, true); + if (!engine) + Lua::Push(L, item_type::BOULDER); + else + Lua::Push(L, engine->ammo_item_type); + return 1; +} + +static int setAmmoItem(lua_State *L) +{ + if (!enable_plugin()) + return 0; + + auto engine = find_engine(L, 1, true); + auto item_type = (df::item_type)luaL_optint(L, 2, item_type::BOULDER); + if (!is_valid_enum_item(item_type)) + luaL_argerror(L, 2, "invalid item type"); + + auto pworld = Core::getInstance().getWorld(); + auto key = stl_sprintf("siege-engine/ammo/%d", engine->id); + auto entry = pworld->GetPersistentData(key, NULL); + if (!entry.isValid()) + return 0; + + engine->ammo_vector_id = job_item_vector_id::ANY_FREE; + engine->ammo_item_type = item_type; + + FOR_ENUM_ITEMS(job_item_vector_id, id) + { + auto other = ENUM_ATTR(job_item_vector_id, other, id); + auto type = ENUM_ATTR(items_other_id, item, other); + if (type == item_type) + { + engine->ammo_vector_id = id; + break; + } + } + + entry.ival(0) = engine->id; + entry.ival(1) = engine->ammo_vector_id; + entry.ival(2) = engine->ammo_item_type; + + lua_pushboolean(L, true); + return 1; +} + +static void forgetStockpileLink(EngineInfo *engine, int pile_id) +{ + engine->stockpiles.erase(pile_id); + + auto pworld = Core::getInstance().getWorld(); + auto key = stl_sprintf("siege-engine/stockpiles/%d/%d", engine->id, pile_id); + pworld->DeletePersistentData(pworld->GetPersistentData(key)); +} + +static void update_stockpile_links(EngineInfo *engine) +{ + engine->links.take_from_pile.clear(); + + for (auto it = engine->stockpiles.begin(); it != engine->stockpiles.end(); ) + { + int id = *it; ++it; + auto pile = df::building::find(id); + + if (!pile || pile->getType() != building_type::Stockpile) + forgetStockpileLink(engine, id); + else + // The vector is sorted, but we are iterating through a sorted set + engine->links.take_from_pile.push_back(pile); + } +} + +static int getStockpileLinks(lua_State *L) +{ + auto engine = find_engine(L, 1, false, true); + if (!engine || engine->stockpiles.empty()) + return 0; + + update_stockpile_links(engine); + + auto &links = engine->links.take_from_pile; + lua_createtable(L, links.size(), 0); + + for (size_t i = 0; i < links.size(); i++) + { + Lua::Push(L, links[i]); + lua_rawseti(L, -2, i+1); + } + + return 1; +} + +static bool isLinkedToPile(df::building_siegeenginest *bld, df::building_stockpilest *pile) +{ + CHECK_NULL_POINTER(bld); + CHECK_NULL_POINTER(pile); + + auto engine = find_engine(bld); + + return engine && engine->stockpiles.count(pile->id); +} + +static bool addStockpileLink(df::building_siegeenginest *bld, df::building_stockpilest *pile) +{ + CHECK_NULL_POINTER(bld); + CHECK_NULL_POINTER(pile); + + if (!enable_plugin()) + return false; + + auto pworld = Core::getInstance().getWorld(); + auto key = stl_sprintf("siege-engine/stockpiles/%d/%d", bld->id, pile->id); + auto entry = pworld->GetPersistentData(key, NULL); + if (!entry.isValid()) + return false; + + auto engine = find_engine(bld, true); + + entry.ival(0) = bld->id; + entry.ival(1) = pile->id; + + engine->stockpiles.insert(pile->id); + return true; +} + +static bool removeStockpileLink(df::building_siegeenginest *bld, df::building_stockpilest *pile) +{ + CHECK_NULL_POINTER(bld); + CHECK_NULL_POINTER(pile); + + if (auto engine = find_engine(bld)) + { + forgetStockpileLink(engine, pile->id); + return true; + } + + return false; +} + +static df::workshop_profile *saveWorkshopProfile(df::building_siegeenginest *bld) +{ + CHECK_NULL_POINTER(bld); + + if (!enable_plugin()) + return NULL; + + // Save skill limits + auto pworld = Core::getInstance().getWorld(); + auto key = stl_sprintf("siege-engine/profiles/%d", bld->id); + auto entry = pworld->GetPersistentData(key, NULL); + if (!entry.isValid()) + return NULL; + + auto engine = find_engine(bld, true); + + entry.ival(0) = engine->id; + entry.ival(1) = engine->profile.min_level; + entry.ival(2) = engine->profile.max_level; + + // Save worker list + std::vector<PersistentDataItem> vec; + auto &workers = engine->profile.permitted_workers; + + key = stl_sprintf("siege-engine/profile-workers/%d", bld->id); + pworld->GetPersistentData(&vec, key, true); + + for (auto it = vec.begin(); it != vec.end(); ++it) + { + if (linear_index(workers, it->ival(1)) < 0) + pworld->DeletePersistentData(*it); + } + + for (size_t i = 0; i < workers.size(); i++) + { + key = stl_sprintf("siege-engine/profile-workers/%d/%d", bld->id, workers[i]); + entry = pworld->GetPersistentData(key, NULL); + if (!entry.isValid()) + continue; + entry.ival(0) = engine->id; + entry.ival(1) = workers[i]; + } + + return &engine->profile; +} + +static int getOperatorSkill(df::building_siegeenginest *bld, bool force = false) +{ + CHECK_NULL_POINTER(bld); + + auto engine = find_engine(bld); + if (!engine) + return 0; + + if (engine->operator_id != -1 && + (world->frame_counter - engine->operator_frame) <= 5) + { + auto op_unit = df::unit::find(engine->operator_id); + if (op_unit) + return Units::getEffectiveSkill(op_unit, job_skill::SIEGEOPERATE); + } + + if (force) + { + color_ostream_proxy out(Core::getInstance().getConsole()); + out.print("Forced siege operator search\n"); + + auto &active = world->units.active; + for (size_t i = 0; i < active.size(); i++) + if (active[i]->pos == engine->center && Units::isCitizen(active[i])) + return Units::getEffectiveSkill(active[i], job_skill::SIEGEOPERATE); + } + + return 0; +} + +/* + * Trajectory raytracing + */ + +struct ProjectilePath { + static const int DEFAULT_FUDGE = 31; + + df::coord origin, goal, target, fudge_delta; + int divisor, fudge_factor; + df::coord speed, direction; + + ProjectilePath(df::coord origin, df::coord goal) : + origin(origin), goal(goal), fudge_factor(1) + { + fudge_delta = df::coord(0,0,0); + calc_line(); + } + + ProjectilePath(df::coord origin, df::coord goal, df::coord delta, int factor) : + origin(origin), goal(goal), fudge_delta(delta), fudge_factor(factor) + { + calc_line(); + } + + ProjectilePath(df::coord origin, df::coord goal, float zdelta, int factor = DEFAULT_FUDGE) : + origin(origin), goal(goal), fudge_factor(factor) + { + fudge_delta = df::coord(0,0,int(factor * zdelta)); + calc_line(); + } + + void calc_line() + { + speed = goal - origin; + speed.x *= fudge_factor; + speed.y *= fudge_factor; + speed.z *= fudge_factor; + speed = speed + fudge_delta; + target = origin + speed; + divisor = point_distance(speed); + if (divisor <= 0) divisor = 1; + direction = df::coord(speed.x>=0?1:-1,speed.y>=0?1:-1,speed.z>=0?1:-1); + } + + df::coord operator[] (int i) const + { + int div2 = divisor * 2; + int bias = divisor-1; + return origin + df::coord( + (2*speed.x*i + direction.x*bias)/div2, + (2*speed.y*i + direction.y*bias)/div2, + (2*speed.z*i + direction.z*bias)/div2 + ); + } +}; + +static ProjectilePath decode_path(lua_State *L, int idx, df::coord origin) +{ + idx = lua_absindex(L, idx); + + Lua::StackUnwinder frame(L); + df::coord goal; + + lua_getfield(L, idx, "target"); + Lua::CheckDFAssign(L, &goal, frame[1]); + + lua_getfield(L, idx, "delta"); + + if (!lua_isnil(L, frame[2])) + { + lua_getfield(L, idx, "factor"); + int factor = luaL_optnumber(L, frame[3], ProjectilePath::DEFAULT_FUDGE); + + if (lua_isnumber(L, frame[2])) + return ProjectilePath(origin, goal, lua_tonumber(L, frame[2]), factor); + + df::coord delta; + Lua::CheckDFAssign(L, &delta, frame[2]); + + return ProjectilePath(origin, goal, delta, factor); + } + + return ProjectilePath(origin, goal); +} + +static int projPosAtStep(lua_State *L) +{ + auto engine = find_engine(L, 1); + auto path = decode_path(L, 2, engine->center); + int step = luaL_checkint(L, 3); + Lua::Push(L, path[step]); + return 1; +} + +static bool isPassableTile(df::coord pos) +{ + auto ptile = Maps::getTileType(pos); + + return !ptile || FlowPassable(*ptile); +} + +static bool isTargetableTile(df::coord pos) +{ + auto ptile = Maps::getTileType(pos); + + return ptile && FlowPassable(*ptile) && !isOpenTerrain(*ptile); +} + +static bool isTreeTile(df::coord pos) +{ + auto ptile = Maps::getTileType(pos); + + return ptile && tileShape(*ptile) == tiletype_shape::TREE; +} + +static bool adjustToTarget(EngineInfo *engine, df::coord *pos) +{ + if (isTargetableTile(*pos)) + return true; + + for (df::coord fudge = *pos; + fudge.z <= engine->target.second.z; fudge.z++) + { + if (!isTargetableTile(fudge)) + continue; + *pos = fudge; + return true; + } + + for (df::coord fudge = *pos; + fudge.z >= engine->target.first.z; fudge.z--) + { + if (!isTargetableTile(fudge)) + continue; + *pos = fudge; + return true; + } + + return false; +} + +static int adjustToTarget(lua_State *L) +{ + auto engine = find_engine(L, 1, true); + df::coord pos; + Lua::CheckDFAssign(L, &pos, 2); + bool ok = adjustToTarget(engine, &pos); + Lua::Push(L, pos); + Lua::Push(L, ok); + return 2; +} + +static const char* const hit_type_names[] = { + "wall", "floor", "ceiling", "map_edge", "tree" +}; + +struct PathMetrics { + enum CollisionType { + Impassable, + Floor, + Ceiling, + MapEdge, + Tree + } hit_type; + + int collision_step, collision_z_step; + int goal_step, goal_z_step, goal_distance; + + bool hits() const { return collision_step > goal_step; } + + PathMetrics(const ProjectilePath &path) + { + compute(path); + } + + void compute(const ProjectilePath &path) + { + collision_step = goal_step = goal_z_step = 1000000; + collision_z_step = 0; + + goal_distance = point_distance(path.origin - path.goal); + + int step = 0; + df::coord prev_pos = path.origin; + + for (;;) { + df::coord cur_pos = path[++step]; + if (cur_pos == prev_pos) + break; + + if (cur_pos.z == path.goal.z) + { + goal_z_step = std::min(step, goal_z_step); + if (cur_pos == path.goal) + goal_step = step; + } + + if (!Maps::isValidTilePos(cur_pos)) + { + hit_type = PathMetrics::MapEdge; + break; + } + + if (!isPassableTile(cur_pos)) + { + if (isTreeTile(cur_pos)) + { + // The projectile code has a bug where it will + // hit a tree on the same tick as a Z level change. + if (cur_pos.z != prev_pos.z) + { + hit_type = Tree; + break; + } + } + else + { + hit_type = Impassable; + break; + } + } + + if (cur_pos.z != prev_pos.z) + { + int top_z = std::max(prev_pos.z, cur_pos.z); + auto ptile = Maps::getTileType(cur_pos.x, cur_pos.y, top_z); + + if (ptile && !LowPassable(*ptile)) + { + hit_type = (cur_pos.z > prev_pos.z ? Ceiling : Floor); + break; + } + + collision_z_step = step; + } + + prev_pos = cur_pos; + } + + collision_step = step; + } +}; + +enum TargetTileStatus { + TARGET_OK, TARGET_RANGE, TARGET_BLOCKED, TARGET_SEMIBLOCKED +}; +static const char* const target_tile_type_names[] = { + "ok", "out_of_range", "blocked", "semi_blocked" +}; + +static TargetTileStatus calcTileStatus(EngineInfo *engine, const PathMetrics &raytrace) +{ + if (raytrace.hits()) + { + if (engine->isInRange(raytrace.goal_step)) + return TARGET_OK; + else + return TARGET_RANGE; + } + else + return TARGET_BLOCKED; +} + +static int projPathMetrics(lua_State *L) +{ + auto engine = find_engine(L, 1); + auto path = decode_path(L, 2, engine->center); + + PathMetrics info(path); + + lua_createtable(L, 0, 7); + Lua::SetField(L, hit_type_names[info.hit_type], -1, "hit_type"); + Lua::SetField(L, info.collision_step, -1, "collision_step"); + Lua::SetField(L, info.collision_z_step, -1, "collision_z_step"); + Lua::SetField(L, info.goal_distance, -1, "goal_distance"); + if (info.goal_step < info.collision_step) + Lua::SetField(L, info.goal_step, -1, "goal_step"); + if (info.goal_z_step < info.collision_step) + Lua::SetField(L, info.goal_z_step, -1, "goal_z_step"); + Lua::SetField(L, target_tile_type_names[calcTileStatus(engine, info)], -1, "status"); + return 1; +} + +static TargetTileStatus calcTileStatus(EngineInfo *engine, df::coord target, float zdelta) +{ + ProjectilePath path(engine->center, target, zdelta); + PathMetrics raytrace(path); + return calcTileStatus(engine, raytrace); +} + +static TargetTileStatus calcTileStatus(EngineInfo *engine, df::coord target) +{ + auto status = calcTileStatus(engine, target, 0.0f); + + if (status == TARGET_BLOCKED) + { + if (calcTileStatus(engine, target, 0.5f) < TARGET_BLOCKED) + return TARGET_SEMIBLOCKED; + + if (calcTileStatus(engine, target, -0.5f) < TARGET_BLOCKED) + return TARGET_SEMIBLOCKED; + } + + return status; +} + +static std::string getTileStatus(df::building_siegeenginest *bld, df::coord tile_pos) +{ + auto engine = find_engine(bld, true); + if (!engine) + return "invalid"; + + return target_tile_type_names[calcTileStatus(engine, tile_pos)]; +} + +static void paintAimScreen(df::building_siegeenginest *bld, df::coord view, df::coord2d ltop, df::coord2d size) +{ + auto engine = find_engine(bld, true); + CHECK_NULL_POINTER(engine); + + for (int x = 0; x < size.x; x++) + { + for (int y = 0; y < size.y; y++) + { + df::coord tile_pos = view + df::coord(x,y,0); + if (is_in_range(engine->building_rect, tile_pos)) + continue; + + Pen cur_tile = Screen::readTile(ltop.x+x, ltop.y+y); + if (!cur_tile.valid()) + continue; + + int color; + + switch (calcTileStatus(engine, tile_pos)) + { + case TARGET_OK: + color = COLOR_GREEN; + break; + case TARGET_RANGE: + color = COLOR_CYAN; + break; + case TARGET_BLOCKED: + color = COLOR_RED; + break; + case TARGET_SEMIBLOCKED: + color = COLOR_BROWN; + break; + } + + if (cur_tile.fg && cur_tile.ch != ' ') + { + cur_tile.fg = color; + cur_tile.bg = 0; + } + else + { + cur_tile.fg = 0; + cur_tile.bg = color; + } + + cur_tile.bold = engine->onTarget(tile_pos); + + if (cur_tile.tile) + cur_tile.tile_mode = Pen::CharColor; + + Screen::paintTile(cur_tile, ltop.x+x, ltop.y+y); + } + } +} + +/* + * Unit tracking + */ + +static const float MAX_TIME = 1000000.0f; + +struct UnitPath { + df::unit *unit; + std::map<float, df::coord> path; + + struct Hit { + UnitPath *path; + df::coord pos; + int dist; + float time, lmargin, rmargin; + }; + + static std::map<df::unit*, UnitPath*> cache; + + static UnitPath *get(df::unit *unit) + { + auto &cv = cache[unit]; + if (!cv) cv = new UnitPath(unit); + return cv; + }; + + UnitPath(df::unit *unit) : unit(unit) + { + if (unit->flags1.bits.rider) + { + auto mount = df::unit::find(unit->relations.rider_mount_id); + + if (mount) + { + path = get(mount)->path; + return; + } + } + + df::coord pos = unit->pos; + df::coord dest = unit->path.dest; + auto &upath = unit->path.path; + + if (dest.isValid() && !upath.x.empty()) + { + float time = unit->counters.job_counter+0.5f; + float speed = Units::computeMovementSpeed(unit)/100.0f; + + if (unit->counters.unconscious > 0) + time += unit->counters.unconscious; + + for (size_t i = 0; i < upath.size(); i++) + { + df::coord new_pos = upath[i]; + if (new_pos == pos) + continue; + + float delay = speed; + if (new_pos.x != pos.x && new_pos.y != pos.y) + delay *= 362.0/256.0; + + path[time] = pos; + pos = new_pos; + time += delay + 1; + } + } + + path[MAX_TIME] = pos; + } + + void get_margin(std::map<float,df::coord>::iterator &it, float time, float *lmargin, float *rmargin) + { + auto it2 = it; + *lmargin = (it == path.begin()) ? MAX_TIME : time - (--it2)->first; + *rmargin = (it->first == MAX_TIME) ? MAX_TIME : it->first - time; + } + + df::coord posAtTime(float time, float *lmargin = NULL, float *rmargin = NULL) + { + CHECK_INVALID_ARGUMENT(time < MAX_TIME); + + auto it = path.upper_bound(time); + if (lmargin) + get_margin(it, time, lmargin, rmargin); + return it->second; + } + + bool findHits(EngineInfo *engine, std::vector<Hit> *hit_points, float bias) + { + df::coord origin = engine->center; + + Hit info; + info.path = this; + + for (auto it = path.begin(); it != path.end(); ++it) + { + info.pos = it->second; + info.dist = point_distance(origin - info.pos); + info.time = float(info.dist)*(engine->proj_speed+1) + engine->hit_delay + bias; + get_margin(it, info.time, &info.lmargin, &info.rmargin); + + if (info.lmargin > 0 && info.rmargin > 0) + { + if (engine->onTarget(info.pos) && engine->isInRange(info.dist)) + hit_points->push_back(info); + } + } + + return !hit_points->empty(); + } +}; + +std::map<df::unit*, UnitPath*> UnitPath::cache; + +static void push_margin(lua_State *L, float margin) +{ + if (margin == MAX_TIME) + lua_pushnil(L); + else + lua_pushnumber(L, margin); +} + +static int traceUnitPath(lua_State *L) +{ + auto unit = Lua::CheckDFObject<df::unit>(L, 1); + + CHECK_NULL_POINTER(unit); + + size_t idx = 1; + auto info = UnitPath::get(unit); + lua_createtable(L, info->path.size(), 0); + + float last_time = 0.0f; + for (auto it = info->path.begin(); it != info->path.end(); ++it) + { + Lua::Push(L, it->second); + if (idx > 1) + { + lua_pushnumber(L, last_time); + lua_setfield(L, -2, "from"); + } + if (idx < info->path.size()) + { + lua_pushnumber(L, it->first); + lua_setfield(L, -2, "to"); + } + lua_rawseti(L, -2, idx++); + last_time = it->first; + } + + return 1; +} + +static int unitPosAtTime(lua_State *L) +{ + auto unit = Lua::CheckDFObject<df::unit>(L, 1); + float time = luaL_checknumber(L, 2); + + CHECK_NULL_POINTER(unit); + + float lmargin, rmargin; + auto info = UnitPath::get(unit); + + Lua::Push(L, info->posAtTime(time, &lmargin, &rmargin)); + push_margin(L, lmargin); + push_margin(L, rmargin); + return 3; +} + +static bool canTargetUnit(df::unit *unit) +{ + CHECK_NULL_POINTER(unit); + + if (unit->flags1.bits.dead || + unit->flags3.bits.ghostly || + unit->flags1.bits.caged || + unit->flags1.bits.hidden_in_ambush) + return false; + + return true; +} + +static void proposeUnitHits(EngineInfo *engine, std::vector<UnitPath::Hit> *hits, float bias) +{ + auto &active = world->units.active; + + for (size_t i = 0; i < active.size(); i++) + { + auto unit = active[i]; + + if (!canTargetUnit(unit)) + continue; + + UnitPath::get(unit)->findHits(engine, hits, bias); + } +} + +static int proposeUnitHits(lua_State *L) +{ + auto engine = find_engine(L, 1); + float bias = luaL_optnumber(L, 2, 0); + + if (!engine->hasTarget()) + luaL_error(L, "target not set"); + + std::vector<UnitPath::Hit> hits; + proposeUnitHits(engine, &hits, bias); + + lua_createtable(L, hits.size(), 0); + + for (size_t i = 0; i < hits.size(); i++) + { + auto &hit = hits[i]; + lua_createtable(L, 0, 6); + Lua::SetField(L, hit.path->unit, -1, "unit"); + Lua::SetField(L, hit.pos, -1, "pos"); + Lua::SetField(L, hit.dist, -1, "dist"); + Lua::SetField(L, hit.time, -1, "time"); + push_margin(L, hit.lmargin); lua_setfield(L, -2, "lmargin"); + push_margin(L, hit.rmargin); lua_setfield(L, -2, "rmargin"); + lua_rawseti(L, -2, i+1); + } + + return 1; +} + +static int computeNearbyWeight(lua_State *L) +{ + auto engine = find_engine(L, 1); + luaL_checktype(L, 2, LUA_TTABLE); + luaL_checktype(L, 3, LUA_TTABLE); + const char *fname = luaL_optstring(L, 4, "nearby_weight"); + + std::vector<UnitPath*> units; + std::vector<float> weights; + + lua_pushnil(L); + + while (lua_next(L, 3)) + { + df::unit *unit; + if (lua_isnumber(L, -2)) + unit = df::unit::find(lua_tointeger(L, -2)); + else + unit = Lua::CheckDFObject<df::unit>(L, -2); + if (!unit) + continue; + units.push_back(UnitPath::get(unit)); + weights.push_back(lua_tonumber(L, -1)); + lua_pop(L, 1); + } + + lua_pushnil(L); + + while (lua_next(L, 2)) + { + Lua::StackUnwinder frame(L, 1); + + lua_getfield(L, frame[1], "unit"); + df::unit *unit = Lua::CheckDFObject<df::unit>(L, -1); + + lua_getfield(L, frame[1], "time"); + float time = luaL_checknumber(L, lua_gettop(L)); + + df::coord pos; + + lua_getfield(L, frame[1], "pos"); + if (lua_isnil(L, -1)) + { + if (!unit) luaL_error(L, "either unit or pos is required"); + pos = UnitPath::get(unit)->posAtTime(time); + } + else + Lua::CheckDFAssign(L, &pos, -1); + + float sum = 0.0f; + + for (size_t i = 0; i < units.size(); i++) + { + if (units[i]->unit == unit) + continue; + + auto diff = units[i]->posAtTime(time) - pos; + float dist = 1 + sqrtf(diff.x*diff.x + diff.y*diff.y + diff.z*diff.z); + sum += weights[i]/(dist*dist); + } + + lua_pushnumber(L, sum); + lua_setfield(L, frame[1], fname); + } + + return 0; +} + +/* + * Projectile hook + */ + +static const int offsets[8][2] = { + { -1, -1 }, { 0, -1 }, { 1, -1 }, + { -1, 0 }, { 1, 0 }, + { -1, 1 }, { 0, 1 }, { 1, 1 } +}; + +struct projectile_hook : df::proj_itemst { + typedef df::proj_itemst interpose_base; + + void aimAtPoint(EngineInfo *engine, const ProjectilePath &path) + { + target_pos = path.target; + + // Debug + Maps::getTileOccupancy(path.goal)->bits.arrow_color = COLOR_LIGHTMAGENTA; + + PathMetrics raytrace(path); + + // Materialize map blocks, or the projectile will crash into them + for (int i = 0; i < raytrace.collision_step; i++) + Maps::ensureTileBlock(path[i]); + + // Find valid hit point for catapult stones + if (flags.bits.high_flying) + { + if (raytrace.hits()) + fall_threshold = raytrace.goal_step; + else + fall_threshold = (raytrace.collision_z_step+raytrace.collision_step-1)/2; + + while (fall_threshold < raytrace.collision_step-1) + { + if (isTargetableTile(path[fall_threshold])) + break; + + fall_threshold++; + } + } + + fall_threshold = std::max(fall_threshold, engine->fire_range.first); + fall_threshold = std::min(fall_threshold, engine->fire_range.second); + } + + void aimAtPoint(EngineInfo *engine, int skill, const ProjectilePath &path) + { + df::coord fail_target = path.goal; + + orient_engine(engine->bld, path.goal); + + // Debug + Maps::getTileOccupancy(path.goal)->bits.arrow_color = COLOR_LIGHTRED; + + // Dabbling always hit in 7x7 area + if (skill < skill_rating::Novice) + { + fail_target.x += random_int(7)-3; + fail_target.y += random_int(7)-3; + aimAtPoint(engine, ProjectilePath(path.origin, fail_target)); + return; + } + + // Exact hit chance + float hit_chance = 1.04f - powf(0.8f, skill); + + if (float(rand())/RAND_MAX < hit_chance) + { + aimAtPoint(engine, path); + return; + } + + // Otherwise perturb + if (skill <= skill_rating::Proficient) + { + // 5x5 + fail_target.x += random_int(5)-2; + fail_target.y += random_int(5)-2; + } + else + { + // 3x3 + int idx = random_int(8); + fail_target.x += offsets[idx][0]; + fail_target.y += offsets[idx][1]; + } + + ProjectilePath fail(path.origin, fail_target, path.fudge_delta, path.fudge_factor); + aimAtPoint(engine, fail); + } + + void aimAtArea(EngineInfo *engine, int skill) + { + df::coord target, last_passable; + df::coord tbase = engine->target.first; + df::coord tsize = engine->getTargetSize(); + bool success = false; + + for (int i = 0; i < 50; i++) + { + target = tbase + df::coord( + random_int(tsize.x), random_int(tsize.y), random_int(tsize.z) + ); + + if (adjustToTarget(engine, &target)) + last_passable = target; + else + continue; + + ProjectilePath path(engine->center, target, engine->is_catapult ? 0.5f : 0.0f); + PathMetrics raytrace(path); + + if (raytrace.hits() && engine->isInRange(raytrace.goal_step)) + { + aimAtPoint(engine, skill, path); + return; + } + } + + if (!last_passable.isValid()) + last_passable = target; + + aimAtPoint(engine, skill, ProjectilePath(engine->center, last_passable)); + } + + static int safeAimProjectile(lua_State *L) + { + color_ostream &out = *Lua::GetOutput(L); + auto proj = (projectile_hook*)lua_touserdata(L, 1); + auto engine = (EngineInfo*)lua_touserdata(L, 2); + int skill = lua_tointeger(L, 3); + + if (!Lua::PushModulePublic(out, L, "plugins.siege-engine", "doAimProjectile")) + luaL_error(L, "Projectile aiming AI not available"); + + Lua::PushDFObject(L, engine->bld); + Lua::Push(L, proj->item); + Lua::Push(L, engine->target.first); + Lua::Push(L, engine->target.second); + Lua::Push(L, skill); + + lua_call(L, 5, 1); + + if (lua_isnil(L, -1)) + proj->aimAtArea(engine, skill); + else + proj->aimAtPoint(engine, skill, decode_path(L, -1, engine->center)); + + return 0; + } + + void doCheckMovement() + { + if (flags.bits.parabolic || distance_flown != 0 || + fall_counter != fall_delay || item == NULL) + return; + + auto engine = find_engine(origin_pos); + if (!engine || !engine->hasTarget()) + return; + + auto L = Lua::Core::State; + CoreSuspendClaimer suspend; + color_ostream_proxy out(Core::getInstance().getConsole()); + + int skill = getOperatorSkill(engine->bld, true); + + // Dabbling can't aim + if (skill < skill_rating::Novice) + aimAtArea(engine, skill); + else + { + lua_pushcfunction(L, safeAimProjectile); + lua_pushlightuserdata(L, this); + lua_pushlightuserdata(L, engine); + lua_pushinteger(L, skill); + + if (!Lua::Core::SafeCall(out, 3, 0)) + aimAtArea(engine, skill); + } + + switch (item->getType()) + { + case item_type::CAGE: + flags.bits.bouncing = false; + break; + case item_type::BIN: + case item_type::BARREL: + flags.bits.bouncing = false; + break; + default: + break; + } + } + + void doLaunchContents() + { + // Translate cartoon flight speed to parabolic + float speed = 100000.0f / (fall_delay + 1); + int min_zspeed = (fall_delay+1)*4900; + + float bonus = 1.0f + 0.1f*(origin_pos.z -cur_pos.z); + bonus *= 1.0f + (distance_flown - 60) / 200.0f; + speed *= bonus; + + // Flight direction vector + df::coord dist = target_pos - origin_pos; + float vx = dist.x, vy = dist.y, vz = fabs((float)dist.z); + normalize(vx, vy, vz); + + int start_z = 0; + + // Start at tile top, if hit a wall + ProjectilePath path(origin_pos, target_pos); + auto next_pos = path[distance_flown+1]; + if (next_pos.z == cur_pos.z && !isPassableTile(next_pos)) + start_z = 49000; + + bool forbid_ammo = DF_GLOBAL_VALUE(standing_orders_forbid_used_ammo, false); + + MapExtras::MapCache mc; + std::vector<df::item*> contents; + Items::getContainedItems(item, &contents); + + for (size_t i = 0; i < contents.size(); i++) + { + auto child = contents[i]; + + if (forbid_ammo) + child->flags.bits.forbid = true; + + // Liquids are vaporized so that they cover nearby units + if (child->isLiquid()) + { + auto flow = Maps::spawnFlow( + cur_pos, + flow_type::MaterialVapor, + child->getMaterial(), child->getMaterialIndex(), + 100 + ); + + // should it leave a puddle too?.. + if (flow && Items::remove(mc, child)) + continue; + } + + auto proj = Items::makeProjectile(mc, child); + if (!proj) continue; + + bool keep = apply_impact_damage(child, 50000, int(250000*bonus)); + + proj->flags.bits.no_impact_destroy = keep; + //proj->flags.bits.bouncing = true; + proj->flags.bits.piercing = true; + proj->flags.bits.parabolic = true; + proj->flags.bits.unk9 = true; + proj->flags.bits.no_collide = true; + + proj->pos_z = start_z; + + float sx, sy, sz; + random_direction(sx, sy, sz); + sx += vx*0.7; sy += vy*0.7; sz += vz*0.7; + if (sz < 0) sz = -sz; + normalize(sx, sy, sz); + + proj->speed_x = int(speed * sx); + proj->speed_y = int(speed * sy); + proj->speed_z = std::max(min_zspeed, int(speed * sz)); + } + } + + DEFINE_VMETHOD_INTERPOSE(bool, checkMovement, ()) + { + if (flags.bits.high_flying || flags.bits.piercing) + doCheckMovement(); + + return INTERPOSE_NEXT(checkMovement)(); + } + + DEFINE_VMETHOD_INTERPOSE(bool, checkImpact, (bool no_damage_floor)) + { + if (!flags.bits.has_hit_ground && !flags.bits.parabolic && + flags.bits.high_flying && !flags.bits.bouncing && + !flags.bits.no_impact_destroy && target_pos != origin_pos && + item && item->flags.bits.container) + { + doLaunchContents(); + } + + return INTERPOSE_NEXT(checkImpact)(no_damage_floor); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(projectile_hook, checkMovement); +IMPLEMENT_VMETHOD_INTERPOSE(projectile_hook, checkImpact); + +/* + * Building hook + */ + +struct building_hook : df::building_siegeenginest { + typedef df::building_siegeenginest interpose_base; + + DEFINE_VMETHOD_INTERPOSE(df::workshop_profile*, getWorkshopProfile, ()) + { + if (auto engine = find_engine(this)) + return &engine->profile; + + return INTERPOSE_NEXT(getWorkshopProfile)(); + } + + DEFINE_VMETHOD_INTERPOSE(df::stockpile_links*, getStockpileLinks, ()) + { + if (auto engine = find_engine(this)) + { + update_stockpile_links(engine); + return &engine->links; + } + + return INTERPOSE_NEXT(getStockpileLinks)(); + } + + DEFINE_VMETHOD_INTERPOSE(void, updateAction, ()) + { + INTERPOSE_NEXT(updateAction)(); + + if (jobs.empty()) + return; + + if (auto engine = find_engine(this)) + { + auto job = jobs[0]; + bool save_op = false; + + switch (job->job_type) + { + case job_type::LoadCatapult: + if (!job->job_items.empty()) + { + auto item = job->job_items[0]; + item->item_type = engine->ammo_item_type; + item->vector_id = engine->ammo_vector_id; + + switch (item->item_type) + { + case item_type::NONE: + case item_type::BOULDER: + case item_type::BLOCKS: + item->mat_type = 0; + break; + + case item_type::BIN: + case item_type::BARREL: + item->mat_type = -1; + // A hack to make it take objects assigned to stockpiles. + // Since reaction_id is not set, the actual value is not used. + item->contains.resize(1); + break; + + default: + item->mat_type = -1; + break; + } + } + // fallthrough + + case job_type::LoadBallista: + case job_type::FireCatapult: + case job_type::FireBallista: + if (auto worker = Job::getWorker(job)) + { + engine->operator_id = worker->id; + engine->operator_frame = world->frame_counter; + } + break; + + default: + break; + } + } + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(building_hook, getWorkshopProfile); +IMPLEMENT_VMETHOD_INTERPOSE(building_hook, getStockpileLinks); +IMPLEMENT_VMETHOD_INTERPOSE(building_hook, updateAction); + +/* + * Initialization + */ + +DFHACK_PLUGIN_LUA_FUNCTIONS { + DFHACK_LUA_FUNCTION(clearTargetArea), + DFHACK_LUA_FUNCTION(setTargetArea), + DFHACK_LUA_FUNCTION(isLinkedToPile), + DFHACK_LUA_FUNCTION(addStockpileLink), + DFHACK_LUA_FUNCTION(removeStockpileLink), + DFHACK_LUA_FUNCTION(saveWorkshopProfile), + DFHACK_LUA_FUNCTION(getTileStatus), + DFHACK_LUA_FUNCTION(paintAimScreen), + DFHACK_LUA_FUNCTION(canTargetUnit), + DFHACK_LUA_FUNCTION(isPassableTile), + DFHACK_LUA_FUNCTION(isTreeTile), + DFHACK_LUA_FUNCTION(isTargetableTile), + DFHACK_LUA_END +}; + +DFHACK_PLUGIN_LUA_COMMANDS { + DFHACK_LUA_COMMAND(getTargetArea), + DFHACK_LUA_COMMAND(getAmmoItem), + DFHACK_LUA_COMMAND(setAmmoItem), + DFHACK_LUA_COMMAND(getStockpileLinks), + DFHACK_LUA_COMMAND(projPosAtStep), + DFHACK_LUA_COMMAND(projPathMetrics), + DFHACK_LUA_COMMAND(adjustToTarget), + DFHACK_LUA_COMMAND(traceUnitPath), + DFHACK_LUA_COMMAND(unitPosAtTime), + DFHACK_LUA_COMMAND(proposeUnitHits), + DFHACK_LUA_COMMAND(computeNearbyWeight), + DFHACK_LUA_END +}; + +static bool is_enabled = false; + +static void enable_hooks(bool enable) +{ + is_enabled = enable; + + INTERPOSE_HOOK(projectile_hook, checkMovement).apply(enable); + INTERPOSE_HOOK(projectile_hook, checkImpact).apply(enable); + + INTERPOSE_HOOK(building_hook, getWorkshopProfile).apply(enable); + INTERPOSE_HOOK(building_hook, getStockpileLinks).apply(enable); + INTERPOSE_HOOK(building_hook, updateAction).apply(enable); + + if (enable) + load_engines(); + else + clear_engines(); +} + +static bool enable_plugin() +{ + if (is_enabled) + return true; + + auto pworld = Core::getInstance().getWorld(); + auto entry = pworld->GetPersistentData("siege-engine/enabled", NULL); + if (!entry.isValid()) + return false; + + enable_hooks(true); + return true; +} + +static void clear_caches(color_ostream &out) +{ + if (!UnitPath::cache.empty()) + { + for (auto it = UnitPath::cache.begin(); it != UnitPath::cache.end(); ++it) + delete it->second; + + UnitPath::cache.clear(); + } +} + +DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event) +{ + switch (event) { + case SC_MAP_LOADED: + if (!gamemode || *gamemode == game_mode::DWARF) + { + auto pworld = Core::getInstance().getWorld(); + bool enable = pworld->GetPersistentData("siege-engine/enabled").isValid(); + + if (enable) + { + out.print("Enabling the siege engine plugin.\n"); + enable_hooks(true); + } + else + enable_hooks(false); + } + break; + case SC_MAP_UNLOADED: + enable_hooks(false); + break; + default: + break; + } + + return CR_OK; +} + +DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands) +{ + if (Core::getInstance().isMapLoaded()) + plugin_onstatechange(out, SC_MAP_LOADED); + + return CR_OK; +} + +DFhackCExport command_result plugin_shutdown ( color_ostream &out ) +{ + enable_hooks(false); + return CR_OK; +} + +DFhackCExport command_result plugin_onupdate ( color_ostream &out ) +{ + clear_caches(out); + return CR_OK; +} diff --git a/plugins/sort.cpp b/plugins/sort.cpp index ff51fc77..95ae109a 100644 --- a/plugins/sort.cpp +++ b/plugins/sort.cpp @@ -228,7 +228,7 @@ static void sort_null_first(vector<string> ¶meters) vector_insert_at(parameters, 0, std::string("<exists")); } -static df::layer_object_listst *getLayerList(df::viewscreen_layerst *layer, int idx) +static df::layer_object_listst *getLayerList(df::viewscreen_layer *layer, int idx) { return virtual_cast<df::layer_object_listst>(vector_get(layer->layer_objects,idx)); } @@ -356,7 +356,7 @@ DEFINE_SORT_HANDLER(unit_sorters, pet, "/List", animals) std::vector<df::unit*> units; for (size_t i = 0; i < animals->animal.size(); i++) - units.push_back(animals->is_vermin[i] ? NULL : (df::unit*)animals->animal[i]); + units.push_back(animals->is_vermin[i] ? NULL : animals->animal[i].unit); if (compute_order(*pout, L, top, &order, units)) { diff --git a/plugins/steam-engine.cpp b/plugins/steam-engine.cpp new file mode 100644 index 00000000..d884191e --- /dev/null +++ b/plugins/steam-engine.cpp @@ -0,0 +1,1007 @@ +#include "Core.h" +#include <Console.h> +#include <Export.h> +#include <PluginManager.h> +#include <modules/Gui.h> +#include <modules/Screen.h> +#include <modules/Maps.h> +#include <TileTypes.h> +#include <vector> +#include <cstdio> +#include <stack> +#include <string> +#include <cmath> +#include <string.h> + +#include <VTableInterpose.h> +#include "df/graphic.h" +#include "df/building_workshopst.h" +#include "df/building_def_workshopst.h" +#include "df/item_liquid_miscst.h" +#include "df/power_info.h" +#include "df/workshop_type.h" +#include "df/builtin_mats.h" +#include "df/world.h" +#include "df/buildings_other_id.h" +#include "df/machine.h" +#include "df/job.h" +#include "df/building_drawbuffer.h" +#include "df/ui.h" +#include "df/viewscreen_dwarfmodest.h" +#include "df/ui_build_selector.h" +#include "df/flow_info.h" +#include "df/report.h" + +#include "MiscUtils.h" + +/* + * This plugin implements a steam engine workshop. It activates + * if there are any workshops in the raws with STEAM_ENGINE in + * their token, and provides the necessary behavior. + * + * Construction: + * + * The workshop needs water as its input, which it takes via a + * passable floor tile below it, like usual magma workshops do. + * The magma version also needs magma. + * + * ISSUE: Since this building is a machine, and machine collapse + * code cannot be modified, it would collapse over true open space. + * As a loophole, down stair provides support to machines, while + * being passable, so use them. + * + * After constructing the building itself, machines can be connected + * to the edge tiles that look like gear boxes. Their exact position + * is extracted from the workshop raws. + * + * ISSUE: Like with collapse above, part of the code involved in + * machine connection cannot be modified. As a result, the workshop + * can only immediately connect to machine components built AFTER it. + * This also means that engines cannot be chained without intermediate + * short axles that can be built later. + * + * Operation: + * + * In order to operate the engine, queue the Stoke Boiler job. + * 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 appropriate liquids from below the workshop. + * + * Every such item gives 100 power, up to a limit of 300 for coal, + * and 500 for a magma engine. The building can host twice that + * amount of items to provide longer autonomous running. When the + * boiler gets filled to capacity, all queued jobs are suspended; + * once it drops back to 3+1 or 5+1 items, they are re-enabled. + * + * While the engine is providing power, steam is being consumed. + * The consumption speed includes a fixed 10% waste rate, and + * the remaining 90% are applied proportionally to the actual + * load in the machine. With the engine at nominal 300 power with + * 150 load in the system, it will consume steam for actual + * 300*(10% + 90%*150/300) = 165 power. + * + * Masterpiece mechanism and chain will decrease the mechanical + * power drawn by the engine itself from 10 to 5. Masterpiece + * barrel decreases waste rate by 4%. Masterpiece piston and pipe + * decrease it by further 4%, and also decrease the whole steam + * use rate by 10%. + * + * Explosions: + * + * The engine must be constructed using barrel, pipe and piston + * from fire-safe, or in the magma version magma-safe metals. + * + * During operation weak parts get gradually worn out, and + * eventually the engine explodes. It should also explode if + * toppled during operation by a building destroyer, or a + * tantruming dwarf. + * + * Save files: + * + * It should be safe to load and view fortresses using engines + * 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. + */ + +using std::vector; +using std::string; +using std::stack; +using namespace DFHack; +using namespace df::enums; + +using df::global::gps; +using df::global::world; +using df::global::ui; +using df::global::ui_build_selector; + +DFHACK_PLUGIN("steam-engine"); + +/* + * List of known steam engine workshop raws. + */ + +struct steam_engine_workshop { + int id; + df::building_def_workshopst *def; + // Cached properties + bool is_magma; + int max_power, max_capacity; + int wear_temp; + // Special tiles (relative position) + std::vector<df::coord2d> gear_tiles; + df::coord2d hearth_tile; + df::coord2d water_tile; + df::coord2d magma_tile; +}; + +std::vector<steam_engine_workshop> engines; + +steam_engine_workshop *find_steam_engine(int id) +{ + for (size_t i = 0; i < engines.size(); i++) + if (engines[i].id == id) + return &engines[i]; + + return NULL; +} + +/* + * Misc utilities. + */ + +static const int hearth_colors[6][2] = { + { COLOR_BLACK, 1 }, + { COLOR_BROWN, 0 }, + { COLOR_RED, 0 }, + { COLOR_RED, 1 }, + { COLOR_BROWN, 1 }, + { COLOR_GREY, 1 } +}; + +void enable_updates_at(df::coord pos, bool flow, bool temp) +{ + static const int delta[4][2] = { { -1, -1 }, { 1, -1 }, { -1, 1 }, { 1, 1 } }; + + for (int i = 0; i < 4; i++) + { + auto blk = Maps::getTileBlock(pos.x+delta[i][0], pos.y+delta[i][1], pos.z); + Maps::enableBlockUpdates(blk, flow, temp); + } +} + +void decrement_flow(df::coord pos, int amount) +{ + auto pldes = Maps::getTileDesignation(pos); + if (!pldes) return; + + int nsize = std::max(0, int(pldes->bits.flow_size - amount)); + pldes->bits.flow_size = nsize; + pldes->bits.flow_forbid = (nsize > 3 || pldes->bits.liquid_type == tile_liquid::Magma); + + enable_updates_at(pos, true, false); +} + +void make_explosion(df::coord center, int power) +{ + static const int bias[9] = { + 60, 30, 60, + 30, 0, 30, + 60, 30, 60 + }; + + int mat_type = builtin_mats::WATER, mat_index = -1; + int i = 0; + + for (int dx = -1; dx <= 1; dx++) + { + for (int dy = -1; dy <= 1; dy++) + { + int size = power - bias[i++]; + auto pos = center + df::coord(dx,dy,0); + + if (size > 0) + Maps::spawnFlow(pos, flow_type::MaterialDust, mat_type, mat_index, size); + } + } + + Gui::showAutoAnnouncement( + announcement_type::CAVE_COLLAPSE, center, + "A boiler has exploded!", COLOR_RED, true + ); +} + +static const int WEAR_TICKS = 806400; + +bool add_wear_nodestroy(df::item_actual *item, int rate) +{ + if (item->incWearTimer(rate)) + { + while (item->wear_timer >= WEAR_TICKS) + { + item->wear_timer -= WEAR_TICKS; + item->wear++; + } + } + + return item->wear > 3; +} + +/* + * Hook for the liquid item. Implements a special 'boiling' + * matter state with a modified description and temperature + * locked at boiling-1. + */ + +struct liquid_hook : df::item_liquid_miscst { + typedef df::item_liquid_miscst interpose_base; + + static const uint32_t BOILING_FLAG = 0x80000000U; + + DEFINE_VMETHOD_INTERPOSE(void, getItemDescription, (std::string *buf, int8_t mode)) + { + if (mat_state.whole & BOILING_FLAG) + buf->append("boiling "); + + INTERPOSE_NEXT(getItemDescription)(buf, mode); + } + + DEFINE_VMETHOD_INTERPOSE(bool, adjustTemperature, (uint16_t temp, int32_t unk)) + { + if (mat_state.whole & BOILING_FLAG) + temp = std::max(int(temp), getBoilingPoint()-1); + + return INTERPOSE_NEXT(adjustTemperature)(temp, unk); + } + + DEFINE_VMETHOD_INTERPOSE(bool, checkTemperatureDamage, ()) + { + if (mat_state.whole & BOILING_FLAG) + temperature = std::max(int(temperature), getBoilingPoint()-1); + + return INTERPOSE_NEXT(checkTemperatureDamage)(); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(liquid_hook, getItemDescription); +IMPLEMENT_VMETHOD_INTERPOSE(liquid_hook, adjustTemperature); +IMPLEMENT_VMETHOD_INTERPOSE(liquid_hook, checkTemperatureDamage); + +/* + * Hook for the workshop itself. Implements core logic. + */ + +struct workshop_hook : df::building_workshopst { + typedef df::building_workshopst interpose_base; + + // Engine detection + + steam_engine_workshop *get_steam_engine() + { + if (type == workshop_type::Custom) + return find_steam_engine(custom_type); + + return NULL; + } + + inline bool is_fully_built() + { + return getBuildStage() >= getMaxBuildStage(); + } + + // Use high bits of flags to store current steam amount. + // This is necessary for consistency if items disappear unexpectedly. + + int get_steam_amount() + { + return (flags.whole >> 28) & 15; + } + + void set_steam_amount(int count) + { + flags.whole = (flags.whole & 0x0FFFFFFFU) | uint32_t((count & 15) << 28); + } + + // Find liquids to consume below the engine. + + bool find_liquids(df::coord *pwater, df::coord *pmagma, bool is_magma, int min_level) + { + if (!is_magma) + pmagma = NULL; + + for (int x = x1; x <= x2; x++) + { + for (int y = y1; y <= y2; y++) + { + auto ptile = Maps::getTileType(x,y,z); + if (!ptile || !LowPassable(*ptile)) + continue; + + auto pltile = Maps::getTileType(x,y,z-1); + if (!pltile || !FlowPassable(*pltile)) + continue; + + auto pldes = Maps::getTileDesignation(x,y,z-1); + if (!pldes || pldes->bits.flow_size < min_level) + continue; + + if (pldes->bits.liquid_type == tile_liquid::Magma) + { + if (pmagma) + *pmagma = df::coord(x,y,z-1); + if (pwater->isValid()) + return true; + } + else + { + *pwater = df::coord(x,y,z-1); + if (!pmagma || pmagma->isValid()) + return true; + } + } + } + + return false; + } + + // Absorbs a water item produced by stoke reaction into the engine. + + bool absorb_unit(steam_engine_workshop *engine, df::item_liquid_miscst *liquid) + { + // Consume liquid inputs + df::coord water, magma; + + if (!find_liquids(&water, &magma, engine->is_magma, 1)) + { + // Destroy the item with enormous wear amount. + liquid->addWear(WEAR_TICKS*5, true, false); + return false; + } + + decrement_flow(water, 1); + if (engine->is_magma) + decrement_flow(magma, 1); + + // Update flags + liquid->flags.bits.in_building = true; + liquid->mat_state.whole |= liquid_hook::BOILING_FLAG; + liquid->temperature = liquid->getBoilingPoint()-1; + liquid->temperature_fraction = 0; + + // This affects where the steam appears to come from + if (engine->hearth_tile.isValid()) + liquid->pos = df::coord(x1+engine->hearth_tile.x, y1+engine->hearth_tile.y, z); + + // Enable block temperature updates + enable_updates_at(liquid->pos, false, true); + return true; + } + + bool boil_unit(df::item_liquid_miscst *liquid) + { + liquid->wear = 4; + liquid->flags.bits.in_building = false; + liquid->temperature = liquid->getBoilingPoint() + 10; + + return liquid->checkMeltBoil(); + } + + void suspend_jobs(bool suspend) + { + for (size_t i = 0; i < jobs.size(); i++) + if (jobs[i]->job_type == job_type::CustomReaction) + jobs[i]->flags.bits.suspend = suspend; + } + + // Scan contained items for boiled steam to absorb. + + df::item_liquid_miscst *collect_steam(steam_engine_workshop *engine, int *count) + { + df::item_liquid_miscst *first = NULL; + *count = 0; + + for (int i = contained_items.size()-1; i >= 0; i--) + { + auto item = contained_items[i]; + if (item->use_mode != 0) + continue; + + auto liquid = strict_virtual_cast<df::item_liquid_miscst>(item->item); + if (!liquid) + continue; + + if (!liquid->flags.bits.in_building) + { + if (liquid->mat_type != builtin_mats::WATER || + liquid->age > 1 || + liquid->wear != 0) + continue; + + // This may destroy the item + if (!absorb_unit(engine, liquid)) + continue; + } + + if (*count < engine->max_capacity) + { + first = liquid; + ++*count; + } + else + { + // Overpressure valve + boil_unit(liquid); + suspend_jobs(true); + } + } + + return first; + } + + void random_boil() + { + int cnt = 0; + + for (int i = contained_items.size()-1; i >= 0; i--) + { + auto item = contained_items[i]; + if (item->use_mode != 0 || !item->item->flags.bits.in_building) + continue; + + auto liquid = strict_virtual_cast<df::item_liquid_miscst>(item->item); + if (!liquid) + continue; + + if (cnt == 0 || rand() < RAND_MAX/2) + { + cnt++; + boil_unit(liquid); + } + } + } + + int classify_component(df::building_actual::T_contained_items *item) + { + if (item->use_mode != 2 || item->item->isBuildMat()) + return -1; + + switch (item->item->getType()) + { + case item_type::TRAPPARTS: + case item_type::CHAIN: + return 0; + case item_type::BARREL: + return 2; + default: + return 1; + } + } + + bool check_component_wear(steam_engine_workshop *engine, int count, int power) + { + int coeffs[3] = { 0, power, count }; + + for (int i = contained_items.size()-1; i >= 0; i--) + { + int type = classify_component(contained_items[i]); + if (type < 0) + continue; + + df::item *item = contained_items[i]->item; + int melt_temp = item->getMeltingPoint(); + if (coeffs[type] == 0 || melt_temp >= engine->wear_temp) + continue; + + // let 500 degree delta at 4 pressure work 1 season + float ticks = coeffs[type]*(engine->wear_temp - melt_temp)*3.0f/500.0f/4.0f; + if (item->addWear(int(8*(1 + ticks)), true, true)) + return true; + } + + return false; + } + + float get_component_quality(int use_type) + { + float sum = 0, cnt = 0; + + for (size_t i = 0; i < contained_items.size(); i++) + { + int type = classify_component(contained_items[i]); + if (type != use_type) + continue; + + sum += contained_items[i]->item->getQuality(); + cnt += 1; + } + + return (cnt > 0 ? sum/cnt : 0); + } + + int get_steam_use_rate(steam_engine_workshop *engine, int dimension, int power_level) + { + // total ticks to wear off completely + float ticks = WEAR_TICKS * 4.0f; + // dimension == days it lasts * 100 + ticks /= 1200.0f * dimension / 100.0f; + // true power use + float power_rate = 1.0f; + // check the actual load + if (auto mptr = df::machine::find(machine.machine_id)) + { + if (mptr->cur_power >= mptr->min_power) + power_rate = float(mptr->min_power) / mptr->cur_power; + else + power_rate = 0.0f; + } + // waste rate: 1-10% depending on piston assembly quality + float piston_qual = get_component_quality(1); + float waste = 0.1f - 0.016f * 0.5f * (piston_qual + get_component_quality(2)); + float efficiency_coeff = 1.0f - 0.02f * piston_qual; + // apply rate and waste factor + ticks *= (waste + 0.9f*power_rate)*power_level*efficiency_coeff; + // end result + return std::max(1, int(ticks)); + } + + void update_under_construction(steam_engine_workshop *engine) + { + if (machine.machine_id != -1) + return; + + int cur_count = 0; + + if (auto first = collect_steam(engine, &cur_count)) + { + if (add_wear_nodestroy(first, WEAR_TICKS*4/10)) + { + boil_unit(first); + cur_count--; + } + } + + set_steam_amount(cur_count); + } + + void update_working(steam_engine_workshop *engine) + { + int old_count = get_steam_amount(); + int old_power = std::min(engine->max_power, old_count); + int cur_count = 0; + + if (auto first = collect_steam(engine, &cur_count)) + { + int rate = get_steam_use_rate(engine, first->dimension, old_power); + + if (add_wear_nodestroy(first, rate)) + { + boil_unit(first); + cur_count--; + } + + if (check_component_wear(engine, old_count, old_power)) + return; + } + + if (old_count < engine->max_capacity && cur_count == engine->max_capacity) + suspend_jobs(true); + else if (cur_count <= engine->max_power+1 && old_count > engine->max_power+1) + suspend_jobs(false); + + set_steam_amount(cur_count); + + int cur_power = std::min(engine->max_power, cur_count); + if (cur_power != old_power) + { + auto mptr = df::machine::find(machine.machine_id); + if (mptr) + mptr->cur_power += (cur_power - old_power)*100; + } + } + + // Furnaces need architecture, and this is a workshop + // only because furnaces cannot connect to machines. + DEFINE_VMETHOD_INTERPOSE(bool, needsDesign, ()) + { + if (get_steam_engine()) + return true; + + return INTERPOSE_NEXT(needsDesign)(); + } + + // Machine interface + DEFINE_VMETHOD_INTERPOSE(void, getPowerInfo, (df::power_info *info)) + { + if (auto engine = get_steam_engine()) + { + info->produced = std::min(engine->max_power, get_steam_amount())*100; + info->consumed = 10 - int(get_component_quality(0)); + return; + } + + INTERPOSE_NEXT(getPowerInfo)(info); + } + + DEFINE_VMETHOD_INTERPOSE(df::machine_info*, getMachineInfo, ()) + { + if (get_steam_engine()) + return &machine; + + return INTERPOSE_NEXT(getMachineInfo)(); + } + + DEFINE_VMETHOD_INTERPOSE(bool, isPowerSource, ()) + { + if (get_steam_engine()) + return true; + + return INTERPOSE_NEXT(isPowerSource)(); + } + + DEFINE_VMETHOD_INTERPOSE(void, categorize, (bool free)) + { + if (get_steam_engine()) + { + auto &vec = world->buildings.other[buildings_other_id::ANY_MACHINE]; + insert_into_vector(vec, &df::building::id, (df::building*)this); + } + + INTERPOSE_NEXT(categorize)(free); + } + + DEFINE_VMETHOD_INTERPOSE(void, uncategorize, ()) + { + if (get_steam_engine()) + { + auto &vec = world->buildings.other[buildings_other_id::ANY_MACHINE]; + erase_from_vector(vec, &df::building::id, id); + } + + INTERPOSE_NEXT(uncategorize)(); + } + + DEFINE_VMETHOD_INTERPOSE(bool, canConnectToMachine, (df::machine_tile_set *info)) + { + if (auto engine = get_steam_engine()) + { + int real_cx = centerx, real_cy = centery; + bool ok = false; + + for (size_t i = 0; i < engine->gear_tiles.size(); i++) + { + // the original function connects to the center tile + centerx = x1 + engine->gear_tiles[i].x; + centery = y1 + engine->gear_tiles[i].y; + + if (!INTERPOSE_NEXT(canConnectToMachine)(info)) + continue; + + ok = true; + break; + } + + centerx = real_cx; centery = real_cy; + return ok; + } + else + return INTERPOSE_NEXT(canConnectToMachine)(info); + } + + // Operation logic + DEFINE_VMETHOD_INTERPOSE(bool, isUnpowered, ()) + { + if (auto engine = get_steam_engine()) + { + df::coord water, magma; + return !find_liquids(&water, &magma, engine->is_magma, 3); + } + + return INTERPOSE_NEXT(isUnpowered)(); + } + + DEFINE_VMETHOD_INTERPOSE(void, updateAction, ()) + { + if (auto engine = get_steam_engine()) + { + if (is_fully_built()) + update_working(engine); + else + update_under_construction(engine); + + if (flags.bits.almost_deleted) + return; + } + + INTERPOSE_NEXT(updateAction)(); + } + + DEFINE_VMETHOD_INTERPOSE(void, drawBuilding, (df::building_drawbuffer *db, void *unk)) + { + INTERPOSE_NEXT(drawBuilding)(db, unk); + + if (auto engine = get_steam_engine()) + { + if (!is_fully_built()) + return; + + // If machine is running, tweak gear assemblies + auto mptr = df::machine::find(machine.machine_id); + if (mptr && (mptr->visual_phase & 1) != 0) + { + for (size_t i = 0; i < engine->gear_tiles.size(); i++) + { + auto pos = engine->gear_tiles[i]; + db->tile[pos.x][pos.y] = 42; + } + } + + // Use the hearth color to display power level + if (engine->hearth_tile.isValid()) + { + auto pos = engine->hearth_tile; + int power = std::min(engine->max_power, get_steam_amount()); + db->fore[pos.x][pos.y] = hearth_colors[power][0]; + db->bright[pos.x][pos.y] = hearth_colors[power][1]; + } + + // Set liquid indicator state + if (engine->water_tile.isValid() || engine->magma_tile.isValid()) + { + df::coord water, magma; + find_liquids(&water, &magma, engine->is_magma, 3); + df::coord dwater, dmagma; + find_liquids(&dwater, &dmagma, engine->is_magma, 5); + + if (engine->water_tile.isValid()) + { + if (!water.isValid()) + db->fore[engine->water_tile.x][engine->water_tile.y] = 0; + else if (!dwater.isValid()) + db->bright[engine->water_tile.x][engine->water_tile.y] = 0; + } + if (engine->magma_tile.isValid() && engine->is_magma) + { + if (!magma.isValid()) + db->fore[engine->magma_tile.x][engine->magma_tile.y] = 0; + else if (!dmagma.isValid()) + db->bright[engine->magma_tile.x][engine->magma_tile.y] = 0; + } + } + } + } + + DEFINE_VMETHOD_INTERPOSE(void, deconstructItems, (bool noscatter, bool lost)) + { + if (get_steam_engine()) + { + // Explode if any steam left + if (int amount = get_steam_amount()) + { + make_explosion( + df::coord((x1+x2)/2, (y1+y2)/2, z), + 40 + amount * 20 + ); + + random_boil(); + } + } + + INTERPOSE_NEXT(deconstructItems)(noscatter, lost); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, needsDesign); +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, getPowerInfo); +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, getMachineInfo); +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, isPowerSource); +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, categorize); +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, uncategorize); +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, canConnectToMachine); +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, isUnpowered); +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, updateAction); +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, drawBuilding); +IMPLEMENT_VMETHOD_INTERPOSE(workshop_hook, deconstructItems); + +/* + * Hook for the dwarfmode screen. Tweaks the build menu + * behavior to suit the steam engine building more. + */ + +struct dwarfmode_hook : df::viewscreen_dwarfmodest +{ + typedef df::viewscreen_dwarfmodest interpose_base; + + steam_engine_workshop *get_steam_engine() + { + if (ui->main.mode == ui_sidebar_mode::Build && + ui_build_selector->stage == 1 && + ui_build_selector->building_type == building_type::Workshop && + ui_build_selector->building_subtype == workshop_type::Custom) + { + return find_steam_engine(ui_build_selector->custom_type); + } + + return NULL; + } + + void check_hanging_tiles(steam_engine_workshop *engine) + { + using df::global::cursor; + + if (!engine) return; + + bool error = false; + + int x1 = cursor->x - engine->def->workloc_x; + int y1 = cursor->y - engine->def->workloc_y; + + for (int x = 0; x < engine->def->dim_x; x++) + { + for (int y = 0; y < engine->def->dim_y; y++) + { + if (ui_build_selector->tiles[x][y] >= 5) + continue; + + auto ptile = Maps::getTileType(x1+x,y1+y,cursor->z); + if (ptile && !isOpenTerrain(*ptile)) + continue; + + ui_build_selector->tiles[x][y] = 6; + error = true; + } + } + + if (error) + { + const char *msg = "Hanging - cover channels with down stairs."; + ui_build_selector->errors.push_back(new std::string(msg)); + } + } + + DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input)) + { + steam_engine_workshop *engine = get_steam_engine(); + + // Selector insists that workshops cannot be placed hanging + // unless they require magma, so pretend we always do. + if (engine) + engine->def->needs_magma = true; + + INTERPOSE_NEXT(feed)(input); + + // Restore the flag + if (engine) + engine->def->needs_magma = engine->is_magma; + + // And now, check for open space. Since these workshops + // are machines, they will collapse over true open space. + check_hanging_tiles(get_steam_engine()); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(dwarfmode_hook, feed); + +/* + * Scan raws for matching workshop buildings. + */ + +static bool find_engines() +{ + engines.clear(); + + auto &wslist = world->raws.buildings.workshops; + + for (size_t i = 0; i < wslist.size(); i++) + { + if (strstr(wslist[i]->code.c_str(), "STEAM_ENGINE") == NULL) + continue; + + steam_engine_workshop ws; + ws.def = wslist[i]; + ws.id = ws.def->id; + + int bs = ws.def->build_stages; + for (int x = 0; x < ws.def->dim_x; x++) + { + for (int y = 0; y < ws.def->dim_y; y++) + { + switch (ws.def->tile[bs][x][y]) + { + case 15: + ws.gear_tiles.push_back(df::coord2d(x,y)); + break; + case 19: + ws.hearth_tile = df::coord2d(x,y); + break; + } + + if (ws.def->tile_color[2][bs][x][y]) + { + switch (ws.def->tile_color[0][bs][x][y]) + { + case 1: + ws.water_tile = df::coord2d(x,y); + break; + case 4: + ws.magma_tile = df::coord2d(x,y); + break; + } + } + } + } + + ws.is_magma = ws.def->needs_magma; + ws.max_power = ws.is_magma ? 5 : 3; + ws.max_capacity = ws.is_magma ? 10 : 6; + ws.wear_temp = ws.is_magma ? 12000 : 11000; + + if (!ws.gear_tiles.empty()) + engines.push_back(ws); + } + + return !engines.empty(); +} + +static void enable_hooks(bool enable) +{ + INTERPOSE_HOOK(liquid_hook, getItemDescription).apply(enable); + INTERPOSE_HOOK(liquid_hook, adjustTemperature).apply(enable); + INTERPOSE_HOOK(liquid_hook, checkTemperatureDamage).apply(enable); + + INTERPOSE_HOOK(workshop_hook, needsDesign).apply(enable); + INTERPOSE_HOOK(workshop_hook, getPowerInfo).apply(enable); + INTERPOSE_HOOK(workshop_hook, getMachineInfo).apply(enable); + INTERPOSE_HOOK(workshop_hook, isPowerSource).apply(enable); + INTERPOSE_HOOK(workshop_hook, categorize).apply(enable); + INTERPOSE_HOOK(workshop_hook, uncategorize).apply(enable); + INTERPOSE_HOOK(workshop_hook, canConnectToMachine).apply(enable); + INTERPOSE_HOOK(workshop_hook, isUnpowered).apply(enable); + INTERPOSE_HOOK(workshop_hook, updateAction).apply(enable); + INTERPOSE_HOOK(workshop_hook, drawBuilding).apply(enable); + INTERPOSE_HOOK(workshop_hook, deconstructItems).apply(enable); + + INTERPOSE_HOOK(dwarfmode_hook, feed).apply(enable); +} + +DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event) +{ + switch (event) { + case SC_WORLD_LOADED: + if (find_engines()) + { + out.print("Detected steam engine workshops - enabling plugin.\n"); + enable_hooks(true); + } + else + enable_hooks(false); + break; + case SC_WORLD_UNLOADED: + enable_hooks(false); + engines.clear(); + break; + default: + break; + } + + return CR_OK; +} + +DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands) +{ + if (Core::getInstance().isWorldLoaded()) + plugin_onstatechange(out, SC_WORLD_LOADED); + + return CR_OK; +} + +DFhackCExport command_result plugin_shutdown ( color_ostream &out ) +{ + enable_hooks(false); + return CR_OK; +} diff --git a/plugins/stonesense b/plugins/stonesense -Subproject 5d4f06d785f8a9933679fe3caa12c18215e9674 +Subproject 75df766263b23182820a1e07b330e64f87d5c9b diff --git a/plugins/tiletypes.cpp b/plugins/tiletypes.cpp index 190bda7c..6af94f2e 100644 --- a/plugins/tiletypes.cpp +++ b/plugins/tiletypes.cpp @@ -767,7 +767,7 @@ command_result executePaintJob(color_ostream &out) } // Remove liquid from walls, etc - if (type != -1 && !DFHack::FlowPassable(type)) + if (type != (df::tiletype)-1 && !DFHack::FlowPassable(type)) { des.bits.flow_size = 0; //des.bits.liquid_type = DFHack::liquid_water; diff --git a/plugins/tweak.cpp b/plugins/tweak.cpp index 2daa9063..d54c4a5e 100644 --- a/plugins/tweak.cpp +++ b/plugins/tweak.cpp @@ -7,12 +7,14 @@ #include "PluginManager.h" #include "modules/Gui.h" +#include "modules/Screen.h" #include "modules/Units.h" #include "modules/Items.h" #include "MiscUtils.h" #include "DataDefs.h" +#include <VTableInterpose.h> #include "df/ui.h" #include "df/world.h" #include "df/squad.h" @@ -26,6 +28,24 @@ #include "df/death_info.h" #include "df/criminal_case.h" #include "df/unit_inventory_item.h" +#include "df/viewscreen_dwarfmodest.h" +#include "df/viewscreen_layer_unit_actionst.h" +#include "df/squad_order_trainst.h" +#include "df/ui_build_selector.h" +#include "df/building_trapst.h" +#include "df/item_actual.h" +#include "df/item_liquipowder.h" +#include "df/item_barst.h" +#include "df/item_threadst.h" +#include "df/item_clothst.h" +#include "df/contaminant.h" +#include "df/layer_object.h" +#include "df/reaction.h" +#include "df/reaction_reagent_itemst.h" +#include "df/reaction_reagent_flags.h" +#include "df/viewscreen_layer_assigntradest.h" +#include "df/viewscreen_tradegoodsst.h" +#include "df/viewscreen_layer_militaryst.h" #include <stdlib.h> @@ -37,8 +57,12 @@ using namespace df::enums; using df::global::ui; using df::global::world; +using df::global::ui_build_selector; +using df::global::ui_menu_width; +using df::global::ui_area_map_width; using namespace DFHack::Gui; +using Screen::Pen; static command_result tweak(color_ostream &out, vector <string> & parameters); @@ -67,6 +91,38 @@ DFhackCExport command_result plugin_init (color_ostream &out, std::vector <Plugi " (humans, elves) can be put to work, but you can't assign rooms\n" " to them and they don't show up in DwarfTherapist because the\n" " game treats them like pets.\n" + " tweak stable-cursor [disable]\n" + " Keeps exact position of dwarfmode cursor during exits to main menu.\n" + " E.g. allows switching between t/q/k/d without losing position.\n" + " tweak patrol-duty [disable]\n" + " Causes 'Train' orders to no longer be considered 'patrol duty' so\n" + " soldiers will stop getting unhappy thoughts. Does NOT fix the problem\n" + " when soldiers go off-duty (i.e. civilian).\n" + " tweak readable-build-plate [disable]\n" + " Fixes rendering of creature weight limits in pressure plate build menu.\n" + " tweak stable-temp [disable]\n" + " Fixes performance bug 6012 by squashing jitter in temperature updates.\n" + " tweak fast-heat <max-ticks>\n" + " Further improves temperature updates by ensuring that 1 degree of\n" + " item temperature is crossed in no more than specified number of frames\n" + " when updating from the environment temperature. Use 0 to disable.\n" + " tweak fix-dimensions [disable]\n" + " Fixes subtracting small amount of thread/cloth/liquid from a stack\n" + " by splitting the stack and subtracting from the remaining single item.\n" + " tweak advmode-contained [disable]\n" + " Fixes custom reactions with container inputs in advmode. The issue is\n" + " that the screen tries to force you to select the contents separately\n" + " from the container. This forcefully skips child reagents.\n" + " tweak fast-trade [disable]\n" + " Makes Shift-Enter in the Move Goods to Depot and Trade screens select\n" + " the current item (fully, in case of a stack), and scroll down one line.\n" + " tweak military-stable-assign [disable]\n" + " Preserve list order and cursor position when assigning to squad,\n" + " i.e. stop the rightmost list of the Positions page of the military\n" + " screen from constantly jumping to the top.\n" + " tweak military-color-assigned [disable]\n" + " Color squad candidates already assigned to other squads in brown/green\n" + " to make them stand out more in the list.\n" )); return CR_OK; } @@ -76,9 +132,6 @@ DFhackCExport command_result plugin_shutdown (color_ostream &out) return CR_OK; } -static command_result lair(color_ostream &out, std::vector<std::string> & params); - - // to be called by tweak-fixmigrant // units forced into the fort by removing the flags do not own their clothes // which has the result that they drop all their clothes and become unhappy because they are naked @@ -136,6 +189,478 @@ command_result fix_clothing_ownership(color_ostream &out, df::unit* unit) return CR_OK; } +/* + * Save or restore cursor position on change to/from main dwarfmode menu. + */ + +static df::coord last_view, last_cursor; + +struct stable_cursor_hook : df::viewscreen_dwarfmodest +{ + typedef df::viewscreen_dwarfmodest interpose_base; + + DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input)) + { + bool was_default = (ui->main.mode == df::ui_sidebar_mode::Default); + df::coord view = Gui::getViewportPos(); + df::coord cursor = Gui::getCursorPos(); + + INTERPOSE_NEXT(feed)(input); + + bool is_default = (ui->main.mode == df::ui_sidebar_mode::Default); + df::coord cur_cursor = Gui::getCursorPos(); + + if (is_default && !was_default) + { + last_view = view; last_cursor = cursor; + } + else if (!is_default && was_default && + Gui::getViewportPos() == last_view && + last_cursor.isValid() && cur_cursor.isValid()) + { + Gui::setCursorCoords(last_cursor.x, last_cursor.y, last_cursor.z); + + // Force update of ui state + set<df::interface_key> tmp; + tmp.insert(interface_key::CURSOR_DOWN_Z); + INTERPOSE_NEXT(feed)(&tmp); + tmp.clear(); + tmp.insert(interface_key::CURSOR_UP_Z); + INTERPOSE_NEXT(feed)(&tmp); + } + else if (cur_cursor.isValid()) + { + last_cursor = df::coord(); + } + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(stable_cursor_hook, feed); + +struct patrol_duty_hook : df::squad_order_trainst +{ + typedef df::squad_order_trainst interpose_base; + + DEFINE_VMETHOD_INTERPOSE(bool, isPatrol, ()) + { + return false; + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(patrol_duty_hook, isPatrol); + +struct readable_build_plate_hook : df::viewscreen_dwarfmodest +{ + typedef df::viewscreen_dwarfmodest interpose_base; + + DEFINE_VMETHOD_INTERPOSE(void, render, ()) + { + INTERPOSE_NEXT(render)(); + + if (ui->main.mode == ui_sidebar_mode::Build && + ui_build_selector->stage == 1 && + ui_build_selector->building_type == building_type::Trap && + ui_build_selector->building_subtype == trap_type::PressurePlate && + ui_build_selector->plate_info.flags.bits.units) + { + auto dims = Gui::getDwarfmodeViewDims(); + int x = dims.menu_x1; + + Screen::Pen pen(' ',COLOR_WHITE); + + int minv = ui_build_selector->plate_info.unit_min; + if ((minv % 1000) == 0) + Screen::paintString(pen, x+11, 14, stl_sprintf("%3dK ", minv/1000)); + + int maxv = ui_build_selector->plate_info.unit_max; + if (maxv < 200000 && (maxv % 1000) == 0) + Screen::paintString(pen, x+24, 14, stl_sprintf("%3dK ", maxv/1000)); + } + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(readable_build_plate_hook, render); + +struct stable_temp_hook : df::item_actual { + typedef df::item_actual interpose_base; + + DEFINE_VMETHOD_INTERPOSE(bool, adjustTemperature, (uint16_t temp, int32_t rate_mult)) + { + if (temperature != temp) + { + // Bug 6012 is caused by fixed-point precision mismatch jitter + // when an item is being pushed by two sources at N and N+1. + // This check suppresses it altogether. + if (temp == temperature+1 || + (temp == temperature-1 && temperature_fraction == 0)) + temp = temperature; + // When SPEC_HEAT is NONE, the original function seems to not + // change the temperature, yet return true, which is silly. + else if (getSpecHeat() == 60001) + temp = temperature; + } + + return INTERPOSE_NEXT(adjustTemperature)(temp, rate_mult); + } + + DEFINE_VMETHOD_INTERPOSE(bool, updateContaminants, ()) + { + if (contaminants) + { + // Force 1-degree difference in contaminant temperature to 0 + for (size_t i = 0; i < contaminants->size(); i++) + { + auto obj = (*contaminants)[i]; + + if (abs(obj->temperature - temperature) == 1) + { + obj->temperature = temperature; + obj->temperature_fraction = temperature_fraction; + } + } + } + + return INTERPOSE_NEXT(updateContaminants)(); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(stable_temp_hook, adjustTemperature); +IMPLEMENT_VMETHOD_INTERPOSE(stable_temp_hook, updateContaminants); + +static int map_temp_mult = -1; +static int max_heat_ticks = 0; + +struct fast_heat_hook : df::item_actual { + typedef df::item_actual interpose_base; + + DEFINE_VMETHOD_INTERPOSE( + bool, updateTempFromMap, + (bool local, bool contained, bool adjust, int32_t rate_mult) + ) { + int cmult = map_temp_mult; + map_temp_mult = rate_mult; + + bool rv = INTERPOSE_NEXT(updateTempFromMap)(local, contained, adjust, rate_mult); + map_temp_mult = cmult; + return rv; + } + + DEFINE_VMETHOD_INTERPOSE( + bool, updateTemperature, + (uint16_t temp, bool local, bool contained, bool adjust, int32_t rate_mult) + ) { + // Some items take ages to cross the last degree, so speed them up + if (map_temp_mult > 0 && temp != temperature && max_heat_ticks > 0) + { + int spec = getSpecHeat(); + if (spec != 60001) + rate_mult = std::max(map_temp_mult, spec/max_heat_ticks/abs(temp - temperature)); + } + + return INTERPOSE_NEXT(updateTemperature)(temp, local, contained, adjust, rate_mult); + } + + DEFINE_VMETHOD_INTERPOSE(bool, adjustTemperature, (uint16_t temp, int32_t rate_mult)) + { + if (map_temp_mult > 0) + rate_mult = map_temp_mult; + + return INTERPOSE_NEXT(adjustTemperature)(temp, rate_mult); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(fast_heat_hook, updateTempFromMap); +IMPLEMENT_VMETHOD_INTERPOSE(fast_heat_hook, updateTemperature); +IMPLEMENT_VMETHOD_INTERPOSE(fast_heat_hook, adjustTemperature); + +static void correct_dimension(df::item_actual *self, int32_t &delta, int32_t dim) +{ + // Zero dimension or remainder? + if (dim <= 0 || self->stack_size <= 1) return; + int rem = delta % dim; + if (rem == 0) return; + // If destroys, pass through + int intv = delta / dim; + if (intv >= self->stack_size) return; + // Subtract int part + delta = rem; + self->stack_size -= intv; + if (self->stack_size <= 1) return; + + // If kills the item or cannot split, round up. + if (!self->flags.bits.in_inventory || !Items::getContainer(self)) + { + delta = dim; + return; + } + + // Otherwise split the stack + color_ostream_proxy out(Core::getInstance().getConsole()); + out.print("fix-dimensions: splitting stack #%d for delta %d.\n", self->id, delta); + + auto copy = self->splitStack(self->stack_size-1, true); + if (copy) copy->categorize(true); +} + +struct dimension_lqp_hook : df::item_liquipowder { + typedef df::item_liquipowder interpose_base; + + DEFINE_VMETHOD_INTERPOSE(bool, subtractDimension, (int32_t delta)) + { + correct_dimension(this, delta, dimension); + return INTERPOSE_NEXT(subtractDimension)(delta); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(dimension_lqp_hook, subtractDimension); + +struct dimension_bar_hook : df::item_barst { + typedef df::item_barst interpose_base; + + DEFINE_VMETHOD_INTERPOSE(bool, subtractDimension, (int32_t delta)) + { + correct_dimension(this, delta, dimension); + return INTERPOSE_NEXT(subtractDimension)(delta); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(dimension_bar_hook, subtractDimension); + +struct dimension_thread_hook : df::item_threadst { + typedef df::item_threadst interpose_base; + + DEFINE_VMETHOD_INTERPOSE(bool, subtractDimension, (int32_t delta)) + { + correct_dimension(this, delta, dimension); + return INTERPOSE_NEXT(subtractDimension)(delta); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(dimension_thread_hook, subtractDimension); + +struct dimension_cloth_hook : df::item_clothst { + typedef df::item_clothst interpose_base; + + DEFINE_VMETHOD_INTERPOSE(bool, subtractDimension, (int32_t delta)) + { + correct_dimension(this, delta, dimension); + return INTERPOSE_NEXT(subtractDimension)(delta); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(dimension_cloth_hook, subtractDimension); + +struct advmode_contained_hook : df::viewscreen_layer_unit_actionst { + typedef df::viewscreen_layer_unit_actionst interpose_base; + + DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input)) + { + auto old_reaction = cur_reaction; + auto old_reagent = reagent; + + INTERPOSE_NEXT(feed)(input); + + if (cur_reaction && (cur_reaction != old_reaction || reagent != old_reagent)) + { + old_reagent = reagent; + + // Skip reagents already contained by others + while (reagent < (int)cur_reaction->reagents.size()-1) + { + if (!cur_reaction->reagents[reagent]->flags.bits.IN_CONTAINER) + break; + reagent++; + } + + if (old_reagent != reagent) + { + // Reproduces a tiny part of the orginal screen code + choice_items.clear(); + + auto preagent = cur_reaction->reagents[reagent]; + reagent_amnt_left = preagent->quantity; + + for (int i = held_items.size()-1; i >= 0; i--) + { + if (!preagent->matchesRoot(held_items[i], cur_reaction->index)) + continue; + if (linear_index(sel_items, held_items[i]) >= 0) + continue; + choice_items.push_back(held_items[i]); + } + + layer_objects[6]->setListLength(choice_items.size()); + + if (!choice_items.empty()) + { + layer_objects[4]->active = layer_objects[5]->active = false; + layer_objects[6]->active = true; + } + else if (layer_objects[6]->active) + { + layer_objects[6]->active = false; + layer_objects[5]->active = true; + } + } + } + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(advmode_contained_hook, feed); + +struct fast_trade_assign_hook : df::viewscreen_layer_assigntradest { + typedef df::viewscreen_layer_assigntradest interpose_base; + + DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input)) + { + if (layer_objects[1]->active && input->count(interface_key::SELECT_ALL)) + { + set<df::interface_key> tmp; tmp.insert(interface_key::SELECT); + INTERPOSE_NEXT(feed)(&tmp); + tmp.clear(); tmp.insert(interface_key::STANDARDSCROLL_DOWN); + INTERPOSE_NEXT(feed)(&tmp); + } + else + INTERPOSE_NEXT(feed)(input); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(fast_trade_assign_hook, feed); + +struct fast_trade_select_hook : df::viewscreen_tradegoodsst { + typedef df::viewscreen_tradegoodsst interpose_base; + + DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input)) + { + if (!(is_unloading || !has_traders || in_edit_count) + && input->count(interface_key::SELECT_ALL)) + { + set<df::interface_key> tmp; tmp.insert(interface_key::SELECT); + INTERPOSE_NEXT(feed)(&tmp); + if (in_edit_count) + INTERPOSE_NEXT(feed)(&tmp); + tmp.clear(); tmp.insert(interface_key::STANDARDSCROLL_DOWN); + INTERPOSE_NEXT(feed)(&tmp); + } + else + INTERPOSE_NEXT(feed)(input); + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(fast_trade_select_hook, feed); + +struct military_assign_hook : df::viewscreen_layer_militaryst { + typedef df::viewscreen_layer_militaryst interpose_base; + + inline bool inPositionsMode() { + return page == Positions && !(in_create_squad || in_new_squad); + } + + DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input)) + { + if (inPositionsMode() && !layer_objects[0]->active) + { + auto pos_list = layer_objects[1]; + auto plist = layer_objects[2]; + auto &cand = positions.candidates; + + // Save the candidate list and cursors + std::vector<df::unit*> copy = cand; + int cursor = plist->getListCursor(); + int pos_cursor = pos_list->getListCursor(); + + INTERPOSE_NEXT(feed)(input); + + if (inPositionsMode() && !layer_objects[0]->active) + { + bool is_select = input->count(interface_key::SELECT); + + // Resort the candidate list and restore cursor + // on add to squad OR scroll in the position list. + if (!plist->active || is_select) + { + // Since we don't know the actual sorting order, preserve + // the ordering of the items in the list before keypress. + // This does the right thing even if the list was sorted + // with sort-units. + std::set<df::unit*> prev, next; + prev.insert(copy.begin(), copy.end()); + next.insert(cand.begin(), cand.end()); + std::vector<df::unit*> out; + + // (old-before-cursor) (new) |cursor| (old-after-cursor) + for (int i = 0; i < cursor && i < (int)copy.size(); i++) + if (next.count(copy[i])) out.push_back(copy[i]); + for (size_t i = 0; i < cand.size(); i++) + if (!prev.count(cand[i])) out.push_back(cand[i]); + int new_cursor = out.size(); + for (int i = cursor; i < (int)copy.size(); i++) + if (next.count(copy[i])) out.push_back(copy[i]); + + cand.swap(out); + plist->setListLength(cand.size()); + if (new_cursor < (int)cand.size()) + plist->setListCursor(new_cursor); + } + + // Preserve the position list index on remove from squad + if (pos_list->active && is_select) + pos_list->setListCursor(pos_cursor); + } + } + else + INTERPOSE_NEXT(feed)(input); + } + + DEFINE_VMETHOD_INTERPOSE(void, render, ()) + { + INTERPOSE_NEXT(render)(); + + if (inPositionsMode()) + { + auto plist = layer_objects[2]; + int x1 = plist->getX1(), y1 = plist->getY1(); + int x2 = plist->getX2(), y2 = plist->getY2(); + int i1 = plist->getFirstVisible(), i2 = plist->getLastVisible(); + int si = plist->getListCursor(); + + for (int y = y1, i = i1; i <= i2; i++, y++) + { + auto unit = vector_get(positions.candidates, i); + if (!unit || unit->military.squad_index < 0) + continue; + + for (int x = x1; x <= x2; x++) + { + Pen cur_tile = Screen::readTile(x, y); + if (!cur_tile.valid()) continue; + cur_tile.fg = (i == si) ? COLOR_BROWN : COLOR_GREEN; + Screen::paintTile(cur_tile, x, y); + } + } + } + } +}; + +IMPLEMENT_VMETHOD_INTERPOSE(military_assign_hook, feed); +IMPLEMENT_VMETHOD_INTERPOSE(military_assign_hook, render); + +static void enable_hook(color_ostream &out, VMethodInterposeLinkBase &hook, vector <string> ¶meters) +{ + if (vector_get(parameters, 1) == "disable") + { + hook.remove(); + out.print("Disabled tweak %s\n", parameters[0].c_str()); + } + else + { + if (hook.apply()) + out.print("Enabled tweak %s\n", parameters[0].c_str()); + else + out.printerr("Could not activate tweak %s\n", parameters[0].c_str()); + } +} + static command_result tweak(color_ostream &out, vector <string> ¶meters) { CoreSuspender suspend; @@ -234,6 +759,64 @@ static command_result tweak(color_ostream &out, vector <string> ¶meters) unit->profession2 = df::profession::TRADER; return fix_clothing_ownership(out, unit); } + else if (cmd == "stable-cursor") + { + enable_hook(out, INTERPOSE_HOOK(stable_cursor_hook, feed), parameters); + } + else if (cmd == "patrol-duty") + { + enable_hook(out, INTERPOSE_HOOK(patrol_duty_hook, isPatrol), parameters); + } + else if (cmd == "readable-build-plate") + { + if (!ui_build_selector || !ui_menu_width || !ui_area_map_width) + { + out.printerr("Necessary globals not known.\n"); + return CR_FAILURE; + } + + enable_hook(out, INTERPOSE_HOOK(readable_build_plate_hook, render), parameters); + } + else if (cmd == "stable-temp") + { + enable_hook(out, INTERPOSE_HOOK(stable_temp_hook, adjustTemperature), parameters); + enable_hook(out, INTERPOSE_HOOK(stable_temp_hook, updateContaminants), parameters); + } + else if (cmd == "fast-heat") + { + if (parameters.size() < 2) + return CR_WRONG_USAGE; + max_heat_ticks = atoi(parameters[1].c_str()); + if (max_heat_ticks <= 0) + parameters[1] = "disable"; + enable_hook(out, INTERPOSE_HOOK(fast_heat_hook, updateTempFromMap), parameters); + enable_hook(out, INTERPOSE_HOOK(fast_heat_hook, updateTemperature), parameters); + enable_hook(out, INTERPOSE_HOOK(fast_heat_hook, adjustTemperature), parameters); + } + else if (cmd == "fix-dimensions") + { + enable_hook(out, INTERPOSE_HOOK(dimension_lqp_hook, subtractDimension), parameters); + enable_hook(out, INTERPOSE_HOOK(dimension_bar_hook, subtractDimension), parameters); + enable_hook(out, INTERPOSE_HOOK(dimension_thread_hook, subtractDimension), parameters); + enable_hook(out, INTERPOSE_HOOK(dimension_cloth_hook, subtractDimension), parameters); + } + else if (cmd == "advmode-contained") + { + enable_hook(out, INTERPOSE_HOOK(advmode_contained_hook, feed), parameters); + } + else if (cmd == "fast-trade") + { + enable_hook(out, INTERPOSE_HOOK(fast_trade_assign_hook, feed), parameters); + enable_hook(out, INTERPOSE_HOOK(fast_trade_select_hook, feed), parameters); + } + else if (cmd == "military-stable-assign") + { + enable_hook(out, INTERPOSE_HOOK(military_assign_hook, feed), parameters); + } + else if (cmd == "military-color-assigned") + { + enable_hook(out, INTERPOSE_HOOK(military_assign_hook, render), parameters); + } else return CR_WRONG_USAGE; diff --git a/plugins/workflow.cpp b/plugins/workflow.cpp index 16205124..98258682 100644 --- a/plugins/workflow.cpp +++ b/plugins/workflow.cpp @@ -828,7 +828,7 @@ static void compute_custom_job(ProtectedJob *pj, df::job *job) using namespace df::enums::reaction_product_item_flags; VIRTUAL_CAST_VAR(prod, df::reaction_product_itemst, r->products[i]); - if (!prod || (prod->item_type < 0 && !prod->flags.is_set(CRAFTS))) + if (!prod || (prod->item_type < (df::item_type)0 && !prod->flags.is_set(CRAFTS))) continue; MaterialInfo mat(prod); @@ -1380,15 +1380,15 @@ static void print_constraint(color_ostream &out, ItemConstraint *cv, bool no_job { Console::color_value color; if (cv->request_resume) - color = Console::COLOR_GREEN; + color = COLOR_GREEN; else if (cv->request_suspend) - color = Console::COLOR_CYAN; + color = COLOR_CYAN; else - color = Console::COLOR_DARKGREY; + color = COLOR_DARKGREY; out.color(color); out << prefix << "Constraint " << flush; - out.color(Console::COLOR_GREY); + out.color(COLOR_GREY); out << cv->config.val() << " " << flush; out.color(color); out << (cv->goalByCount() ? "count " : "amount ") @@ -1437,18 +1437,18 @@ static void print_constraint(color_ostream &out, ItemConstraint *cv, bool no_job { if (pj->want_resumed) { - out.color(Console::COLOR_YELLOW); + out.color(COLOR_YELLOW); out << start << " (delayed)" << endl; } else { - out.color(Console::COLOR_BLUE); + out.color(COLOR_BLUE); out << start << " (suspended)" << endl; } } else { - out.color(Console::COLOR_GREEN); + out.color(COLOR_GREEN); out << start << endl; } @@ -1472,11 +1472,11 @@ static void print_job(color_ostream &out, ProtectedJob *pj) isOptionEnabled(CF_AUTOMELT)) { if (meltable_count <= 0) - out.color(Console::COLOR_CYAN); + out.color(COLOR_CYAN); else if (pj->want_resumed && !pj->isActuallyResumed()) - out.color(Console::COLOR_YELLOW); + out.color(COLOR_YELLOW); else - out.color(Console::COLOR_GREEN); + out.color(COLOR_GREEN); out << " Meltable: " << meltable_count << " objects." << endl; out.reset_color(); } diff --git a/plugins/zone.cpp b/plugins/zone.cpp index fc89fecc..c496f49b 100644 --- a/plugins/zone.cpp +++ b/plugins/zone.cpp @@ -792,7 +792,7 @@ void unitInfo(color_ostream & out, df::unit* unit, bool verbose = false) bool isActivityZone(df::building * building) { if( building->getType() == building_type::Civzone - && building->getSubtype() == civzone_type::ActivityZone) + && building->getSubtype() == (short)civzone_type::ActivityZone) return true; else return false; @@ -1603,7 +1603,7 @@ void zoneInfo(color_ostream & out, df::building* building, bool verbose) if(building->getType()!= building_type::Civzone) return; - if(building->getSubtype() != civzone_type::ActivityZone) + if(building->getSubtype() != (short)civzone_type::ActivityZone) return; string name; diff --git a/scripts/deathcause.rb b/scripts/deathcause.rb new file mode 100644 index 00000000..178ebbc8 --- /dev/null +++ b/scripts/deathcause.rb @@ -0,0 +1,37 @@ +# show death cause of a creature + +def display_event(e) + p e if $DEBUG + + str = "#{e.victim_tg.name} died in year #{e.year}" + str << " of #{e.death_cause}" if false + str << " killed by the #{e.slayer_race_tg.name[0]} #{e.slayer_tg.name}" if e.slayer != -1 + str << " using a #{df.world.raws.itemdefs.weapons[e.weapon.item_subtype].name}" if e.weapon.item_type == :WEAPON + str << ", shot by a #{df.world.raws.itemdefs.weapons[e.weapon.bow_item_subtype].name}" if e.weapon.bow_item_type == :WEAPON + + puts str + '.' +end + +item = df.item_find(:selected) + +if !item or !item.kind_of?(DFHack::ItemBodyComponent) + item = df.world.items.other[:ANY_CORPSE].find { |i| df.at_cursor?(i) } +end + +if !item or !item.kind_of?(DFHack::ItemBodyComponent) + puts "Please select a corpse in the loo'k' menu" +else + hfig = item.hist_figure_id + if hfig == -1 + puts "Not a historical figure, cannot find info" + else + events = df.world.history.events + (0...events.length).reverse_each { |i| + if events[i].kind_of?(DFHack::HistoryEventHistFigureDiedst) and events[i].victim == hfig + display_event(events[i]) + break + end + } + end +end + diff --git a/scripts/devel/find-offsets.lua b/scripts/devel/find-offsets.lua index 6fc12735..07a05847 100644 --- a/scripts/devel/find-offsets.lua +++ b/scripts/devel/find-offsets.lua @@ -803,6 +803,19 @@ end -- cur_year_tick -- +function stop_autosave() + if is_known 'd_init' then + local f = df.global.d_init.flags4 + if f.AUTOSAVE_SEASONAL or f.AUTOSAVE_YEARLY then + f.AUTOSAVE_SEASONAL = false + f.AUTOSAVE_YEARLY = false + print('Disabled seasonal and yearly autosave.') + end + else + dfhack.printerr('Could not disable autosave!') + end +end + local function find_cur_year_tick() local zone if os_type == 'windows' then @@ -815,6 +828,8 @@ local function find_cur_year_tick() return end + stop_autosave() + local addr = zone:find_counter([[ Searching for cur_year_tick. Please exit to main dwarfmode menu, then do as instructed below:]], @@ -825,6 +840,79 @@ menu, then do as instructed below:]], end -- +-- cur_season_tick +-- + +function step_n_frames(cnt) + local world = df.global.world + local ctick = world.frame_counter + local more = '' + while world.frame_counter-ctick < cnt do + print(" Please step the game "..(cnt-world.frame_counter+ctick)..more.." frames.") + more = ' more' + if not utils.prompt_yes_no(' Done?', true) then + return nil + end + end + return world.frame_counter-ctick +end + +local function find_cur_season_tick() + if not (is_known 'cur_year_tick') then + dfhack.printerr('Cannot search for cur_season_tick - prerequisites missing.') + return + end + + stop_autosave() + + local addr = searcher:find_interactive([[ +Searching for cur_season_tick. Please exit to main dwarfmode +menu, then do as instructed below:]], + 'int32_t', + function(ccursor) + if ccursor > 0 then + if not step_n_frames(10) then + return false + end + end + return true, math.floor(((df.global.cur_year_tick+10)%100800)/10) + end + ) + ms.found_offset('cur_season_tick', addr) +end + +-- +-- cur_season +-- + +local function find_cur_season() + if not (is_known 'cur_year_tick' and is_known 'cur_season_tick') then + dfhack.printerr('Cannot search for cur_season - prerequisites missing.') + return + end + + stop_autosave() + + local addr = searcher:find_interactive([[ +Searching for cur_season. Please exit to main dwarfmode +menu, then do as instructed below:]], + 'int8_t', + function(ccursor) + if ccursor > 0 then + local cst = df.global.cur_season_tick + df.global.cur_season_tick = 10079 + df.global.cur_year_tick = df.global.cur_year_tick + (10079-cst)*10 + if not step_n_frames(10) then + return false + end + end + return true, math.floor((df.global.cur_year_tick+10)/100800)%4 + end + ) + ms.found_offset('cur_season', addr) +end + +-- -- process_jobs -- @@ -839,6 +927,8 @@ end local function find_process_jobs() local zone = get_process_zone() or searcher + stop_autosave() + local addr = zone:find_menu_cursor([[ Searching for process_jobs. Please do as instructed below:]], 'int8_t', @@ -856,6 +946,8 @@ end local function find_process_dig() local zone = get_process_zone() or searcher + stop_autosave() + local addr = zone:find_menu_cursor([[ Searching for process_dig. Please do as instructed below:]], 'int8_t', @@ -879,6 +971,8 @@ local function find_pause_state() end zone = zone or searcher + stop_autosave() + local addr = zone:find_menu_cursor([[ Searching for pause_state. Please do as instructed below:]], 'int8_t', @@ -930,6 +1024,8 @@ print('\nUnpausing globals:\n') exec_finder(find_cur_year, 'cur_year') exec_finder(find_cur_year_tick, 'cur_year_tick') +exec_finder(find_cur_season_tick, 'cur_season_tick') +exec_finder(find_cur_season, 'cur_season') exec_finder(find_process_jobs, 'process_jobs') exec_finder(find_process_dig, 'process_dig') exec_finder(find_pause_state, 'pause_state') diff --git a/scripts/devel/inject-raws.lua b/scripts/devel/inject-raws.lua new file mode 100644 index 00000000..a4ebeec1 --- /dev/null +++ b/scripts/devel/inject-raws.lua @@ -0,0 +1,178 @@ +-- Injects new reaction, item and building defs into the world. + +-- The savegame contains a list of the relevant definition tokens in +-- the right order, but all details are read from raws every time. +-- This allows just adding stub definitions, and simply saving and +-- reloading the game. + +local utils = require 'utils' + +local raws = df.global.world.raws + +print[[ +WARNING: THIS SCRIPT CAN PERMANENLY DAMAGE YOUR SAVE. + +This script attempts to inject new raw objects into your +world. If the injected references do not match the actual +edited raws, your save will refuse to load, or load but crash. +]] + +if not utils.prompt_yes_no('Did you make a backup?') then + qerror('Not backed up.') +end + +df.global.pause_state = true + +local changed = false + +function inject_reaction(name) + for _,v in ipairs(raws.reactions) do + if v.code == name then + print('Reaction '..name..' already exists.') + return + end + end + + print('Injecting reaction '..name) + changed = true + + raws.reactions:insert('#', { + new = true, + code = name, + name = 'Dummy reaction '..name, + index = #raws.reactions, + }) +end + +local building_types = { + workshop = { df.building_def_workshopst, raws.buildings.workshops }, + furnace = { df.building_def_furnacest, raws.buildings.furnaces }, +} + +function inject_building(btype, name) + for _,v in ipairs(raws.buildings.all) do + if v.code == name then + print('Building '..name..' already exists.') + return + end + end + + print('Injecting building '..name) + changed = true + + local typeinfo = building_types[btype] + + local id = raws.buildings.next_id + raws.buildings.next_id = id+1 + + raws.buildings.all:insert('#', { + new = typeinfo[1], + code = name, + name = 'Dummy '..btype..' '..name, + id = id, + }) + + typeinfo[2]:insert('#', raws.buildings.all[#raws.buildings.all-1]) +end + +local itemdefs = raws.itemdefs +local item_types = { + weapon = { df.itemdef_weaponst, itemdefs.weapons, 'weapon_type' }, + trainweapon = { df.itemdef_weaponst, itemdefs.weapons, 'training_weapon_type' }, + pick = { df.itemdef_weaponst, itemdefs.weapons, 'digger_type' }, + trapcomp = { df.itemdef_trapcompst, itemdefs.trapcomps, 'trapcomp_type' }, + toy = { df.itemdef_toyst, itemdefs.toys, 'toy_type' }, + tool = { df.itemdef_toolst, itemdefs.tools, 'tool_type' }, + instrument = { df.itemdef_instrumentst, itemdefs.instruments, 'instrument_type' }, + armor = { df.itemdef_armorst, itemdefs.armor, 'armor_type' }, + ammo = { df.itemdef_ammost, itemdefs.ammo, 'ammo_type' }, + siegeammo = { df.itemdef_siegeammost, itemdefs.siege_ammo, 'siegeammo_type' }, + gloves = { df.itemdef_glovest, itemdefs.gloves, 'gloves_type' }, + shoes = { df.itemdef_shoest, itemdefs.shoes, 'shoes_type' }, + shield = { df.itemdef_shieldst, itemdefs.shields, 'shield_type' }, + helm = { df.itemdef_helmst, itemdefs.helms, 'helm_type' }, + pants = { df.itemdef_pantsst, itemdefs.pants, 'pants_type' }, + food = { df.itemdef_foodst, itemdefs.food }, +} + +function add_to_civ(entity, bvec, id) + for _,v in ipairs(entity.resources[bvec]) do + if v == id then + return + end + end + + entity.resources[bvec]:insert('#', id) +end + +function add_to_dwarf_civs(btype, id) + local typeinfo = item_types[btype] + if not typeinfo[3] then + print('Not adding to civs.') + end + + for _,entity in ipairs(df.global.world.entities.all) do + if entity.race == df.global.ui.race_id then + add_to_civ(entity, typeinfo[3], id) + end + end +end + +function inject_item(btype, name) + for _,v in ipairs(itemdefs.all) do + if v.id == name then + print('Itemdef '..name..' already exists.') + return + end + end + + print('Injecting item '..name) + changed = true + + local typeinfo = item_types[btype] + local vec = typeinfo[2] + local id = #vec + + vec:insert('#', { + new = typeinfo[1], + id = name, + subtype = id, + name = name, + name_plural = name, + }) + + itemdefs.all:insert('#', vec[id]) + + add_to_dwarf_civs(btype, id) +end + +local args = {...} +local mode = nil +local ops = {} + +for _,kv in ipairs(args) do + if mode and string.match(kv, '^[%u_]+$') then + table.insert(ops, curry(mode, kv)) + elseif kv == 'reaction' then + mode = inject_reaction + elseif building_types[kv] then + mode = curry(inject_building, kv) + elseif item_types[kv] then + mode = curry(inject_item, kv) + else + qerror('Invalid option: '..kv) + end +end + +if #ops > 0 then + print('') + for _,v in ipairs(ops) do + v() + end +end + +if changed then + print('\nNow without unpausing save and reload the game to re-read raws.') +else + print('\nNo changes made.') +end diff --git a/scripts/devel/lsmem.lua b/scripts/devel/lsmem.lua new file mode 100644 index 00000000..75586324 --- /dev/null +++ b/scripts/devel/lsmem.lua @@ -0,0 +1,14 @@ +-- Prints memory ranges of the process. + +for _,v in ipairs(dfhack.internal.getMemRanges()) do + local access = { '-', '-', '-', 'p' } + if v.read then access[1] = 'r' end + if v.write then access[2] = 'w' end + if v.execute then access[3] = 'x' end + if not v.valid then + access[4] = '?' + elseif v.shared then + access[4] = 's' + end + print(string.format('%08x-%08x %s %s', v.start_addr, v.end_addr, table.concat(access), v.name)) +end diff --git a/scripts/devel/migrants-now.lua b/scripts/devel/migrants-now.lua new file mode 100644 index 00000000..8eb4b0c8 --- /dev/null +++ b/scripts/devel/migrants-now.lua @@ -0,0 +1,9 @@ +-- Force a migrants event in next 10 ticks. + +df.global.timed_events:insert('#',{ + new = true, + type = df.timed_event_type.Migrants, + season = df.global.cur_season, + season_ticks = df.global.cur_season_tick+1, + entity = df.historical_entity.find(df.global.ui.civ_id) +}) diff --git a/scripts/devel/pop-screen.lua b/scripts/devel/pop-screen.lua new file mode 100644 index 00000000..f1ee072c --- /dev/null +++ b/scripts/devel/pop-screen.lua @@ -0,0 +1,3 @@ +-- For killing bugged out gui script screens. + +dfhack.screen.dismiss(dfhack.gui.getCurViewscreen()) diff --git a/scripts/digfort.rb b/scripts/digfort.rb new file mode 100644 index 00000000..6d609f9a --- /dev/null +++ b/scripts/digfort.rb @@ -0,0 +1,38 @@ +# designate an area for digging according to a plan in csv format + +raise "usage: digfort <plan filename>" if not $script_args[0] +planfile = File.read($script_args[0]) + +if df.cursor.x == -30000 + raise "place the game cursor to the top-left corner of the design" +end + +tiles = planfile.lines.map { |l| + l.sub(/#.*/, '').split(';').map { |t| t.strip } +} + +x = x0 = df.cursor.x +y = df.cursor.y +z = df.cursor.z + +tiles.each { |line| + next if line.empty? or line == [''] + line.each { |tile| + t = df.map_tile_at(x, y, z) + s = t.shape_basic + case tile + when 'd'; t.dig(:Default) if s == :Wall + when 'u'; t.dig(:UpStair) if s == :Wall + when 'j'; t.dig(:DownStair) if s == :Wall or s == :Floor + when 'i'; t.dig(:UpDownStair) if s == :Wall + when 'h'; t.dig(:Channel) if s == :Wall or s == :Floor + when 'r'; t.dig(:Ramp) if s == :Wall + when 'x'; t.dig(:No) + end + x += 1 + } + x = x0 + y += 1 +} + +puts 'done' diff --git a/scripts/drainaquifer.rb b/scripts/drainaquifer.rb new file mode 100644 index 00000000..4e2ae4ff --- /dev/null +++ b/scripts/drainaquifer.rb @@ -0,0 +1,11 @@ +# remove all aquifers from the map + +count = 0 +df.each_map_block { |b| + if b.designation[0][0].water_table or b.designation[15][15].water_table + count += 1 + b.designation.each { |dx| dx.each { |dy| dy.water_table = false } } + end +} + +puts "cleared #{count} map blocks" diff --git a/scripts/fix/population-cap.lua b/scripts/fix/population-cap.lua new file mode 100644 index 00000000..a34098c5 --- /dev/null +++ b/scripts/fix/population-cap.lua @@ -0,0 +1,40 @@ +-- Communicates current population to mountainhomes to avoid cap overshooting. + +-- 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. + +local args = {...} + +local ui = df.global.ui +local ui_stats = ui.tasks +local civ = df.historical_entity.find(ui.civ_id) + +if not civ then + qerror('No active fortress.') +end + +local civ_stats = civ.activity_stats + +if not civ_stats then + if args[1] ~= 'force' then + qerror('No caravan report object; use "fix/population-cap force" to create one') + end + print('Creating an empty statistics structure...') + civ.activity_stats = { + new = true, + created_weapons = { resize = #ui_stats.created_weapons }, + known_creatures1 = { resize = #ui_stats.known_creatures1 }, + known_creatures = { resize = #ui_stats.known_creatures }, + known_plants1 = { resize = #ui_stats.known_plants1 }, + known_plants = { resize = #ui_stats.known_plants }, + } + civ_stats = civ.activity_stats +end + +-- Use max to keep at least some of the original caravan communication idea +civ_stats.population = math.max(civ_stats.population, ui_stats.population) + +print('Home civ notified about current population.') diff --git a/scripts/fix/stable-temp.lua b/scripts/fix/stable-temp.lua index d06d0fcc..27a88ef7 100644 --- a/scripts/fix/stable-temp.lua +++ b/scripts/fix/stable-temp.lua @@ -1,5 +1,9 @@ -- Reset item temperature to the value of their tile. +local args = {...} + +local apply = (args[1] == 'apply') + local count = 0 local types = {} @@ -9,13 +13,16 @@ local function update_temp(item,btemp) local tid = item:getType() types[tid] = (types[tid] or 0) + 1 end - item.temperature = btemp - item.temperature_fraction = 0 - if item.contaminants then - for _,c in ipairs(item.contaminants) do - c.temperature = btemp - c.temperature_fraction = 0 + if apply then + item.temperature = btemp + item.temperature_fraction = 0 + + if item.contaminants then + for _,c in ipairs(item.contaminants) do + c.temperature = btemp + c.temperature_fraction = 0 + end end end @@ -23,7 +30,9 @@ local function update_temp(item,btemp) update_temp(sub,btemp) end - item:checkTemperatureDamage() + if apply then + item:checkTemperatureDamage() + end end local last_frame = df.global.world.frame_counter-1 @@ -39,7 +48,11 @@ for _,item in ipairs(df.global.world.items.all) do end end -print('Items updated: '..count) +if apply then + print('Items updated: '..count) +else + print('Items not in equilibrium: '..count) +end local tlist = {} for k,_ in pairs(types) do tlist[#tlist+1] = k end @@ -47,3 +60,7 @@ table.sort(tlist, function(a,b) return types[a] > types[b] end) for _,k in ipairs(tlist) do print(' '..df.item_type[k]..':', types[k]) end + +if not apply then + print("Use 'fix/stable-temp apply' to force-change temperature.") +end diff --git a/scripts/gui/hello-world.lua b/scripts/gui/hello-world.lua new file mode 100644 index 00000000..c8cd3bd0 --- /dev/null +++ b/scripts/gui/hello-world.lua @@ -0,0 +1,24 @@ +-- Test lua viewscreens. + +local gui = require 'gui' + +local text = 'Woohoo, lua viewscreen :)' + +local screen = gui.FramedScreen{ + frame_style = gui.GREY_LINE_FRAME, + frame_title = 'Hello World', + frame_width = #text+6, + frame_height = 3, +} + +function screen:onRenderBody(dc) + dc:seek(3,1):string(text, COLOR_LIGHTGREEN) +end + +function screen:onInput(keys) + if keys.LEAVESCREEN or keys.SELECT then + self:dismiss() + end +end + +screen:show() diff --git a/scripts/gui/liquids.lua b/scripts/gui/liquids.lua new file mode 100644 index 00000000..cddb9f01 --- /dev/null +++ b/scripts/gui/liquids.lua @@ -0,0 +1,295 @@ +-- Interface front-end for liquids plugin. + +local utils = require 'utils' +local gui = require 'gui' +local guidm = require 'gui.dwarfmode' +local dlg = require 'gui.dialogs' + +local liquids = require('plugins.liquids') + +local sel_rect = df.global.selection_rect + +local brushes = { + { tag = 'range', caption = 'Rectangle', range = true }, + { tag = 'block', caption = '16x16 block' }, + { tag = 'column', caption = 'Column' }, + { tag = 'flood', caption = 'Flood' }, +} + +local paints = { + { tag = 'water', caption = 'Water', liquid = true, flow = true, key = 'w' }, + { tag = 'magma', caption = 'Magma', liquid = true, flow = true, key = 'l' }, + { tag = 'obsidian', caption = 'Obsidian Wall' }, + { tag = 'obsidian_floor', caption = 'Obsidian Floor' }, + { tag = 'riversource', caption = 'River Source' }, + { tag = 'flowbits', caption = 'Flow Updates', flow = true }, + { tag = 'wclean', caption = 'Clean Salt/Stagnant' }, +} + +local flowbits = { + { tag = '+', caption = 'Enable Updates' }, + { tag = '-', caption = 'Disable Updates' }, + { tag = '.', caption = 'Keep Updates' }, +} + +local setmode = { + { tag = '.', caption = 'Set Exactly' }, + { tag = '+', caption = 'Only Increase' }, + { tag = '-', caption = 'Only Decrease' }, +} + +local permaflows = { + { tag = '.', caption = "Keep Permaflow" }, + { tag = '-', caption = 'Remove Permaflow' }, + { tag = 'N', caption = 'Set Permaflow N' }, + { tag = 'S', caption = 'Set Permaflow S' }, + { tag = 'E', caption = 'Set Permaflow E' }, + { tag = 'W', caption = 'Set Permaflow W' }, + { tag = 'NE', caption = 'Set Permaflow NE' }, + { tag = 'NW', caption = 'Set Permaflow NW' }, + { tag = 'SE', caption = 'Set Permaflow SE' }, + { tag = 'SW', caption = 'Set Permaflow SW' }, +} + +Toggle = defclass(Toggle) + +Toggle.ATTRS{ items = {}, selected = 1 } + +function Toggle:get() + return self.items[self.selected] +end + +function Toggle:render(dc) + local item = self:get() + if item then + dc:string(item.caption) + if item.key then + dc:string(" ("):string(item.key, COLOR_LIGHTGREEN):string(")") + end + else + dc:string('NONE', COLOR_RED) + end +end + +function Toggle:step(delta) + if #self.items > 1 then + delta = delta or 1 + self.selected = 1 + (self.selected + delta - 1) % #self.items + end +end + +LiquidsUI = defclass(LiquidsUI, guidm.MenuOverlay) + +LiquidsUI.focus_path = 'liquids' + +function LiquidsUI:init() + self:assign{ + brush = Toggle{ items = brushes }, + paint = Toggle{ items = paints }, + flow = Toggle{ items = flowbits }, + set = Toggle{ items = setmode }, + permaflow = Toggle{ items = permaflows }, + amount = 7, + } +end + +function LiquidsUI:onDestroy() + guidm.clearSelection() +end + +function render_liquid(dc, block, x, y) + local dsgn = block.designation[x%16][y%16] + + if dsgn.flow_size > 0 then + if dsgn.liquid_type == df.tile_liquid.Magma then + dc:pen(COLOR_RED):string("Magma") + else + dc:pen(COLOR_BLUE) + if dsgn.water_stagnant then dc:string("Stagnant ") end + if dsgn.water_salt then dc:string("Salty ") end + dc:string("Water") + end + dc:string(" ["..dsgn.flow_size.."/7]") + else + dc:string('No Liquid') + end +end + +local permaflow_abbr = { + north = 'N', south = 'S', east = 'E', west = 'W', + northeast = 'NE', northwest = 'NW', southeast = 'SE', southwest = 'SW' +} + +function render_flow_state(dc, block, x, y) + local flow = block.liquid_flow[x%16][y%16] + + if block.flags.update_liquid then + dc:string("Updating", COLOR_GREEN) + else + dc:string("Static") + end + dc:string(", ") + if flow.perm_flow_dir ~= 0 then + local tag = df.tile_liquid_flow_dir[flow.perm_flow_dir] + dc:string("Permaflow "..(permaflow_abbr[tag] or tag), COLOR_CYAN) + elseif flow.temp_flow_timer > 0 then + dc:string("Flowing "..flow.temp_flow_timer, COLOR_GREEN) + else + dc:string("No Flow") + end +end + +function LiquidsUI:onRenderBody(dc) + dc:clear():seek(1,1):string("Paint Liquids Cheat", COLOR_WHITE) + + local cursor = guidm.getCursorPos() + local block = dfhack.maps.getTileBlock(cursor) + + if block then + local x, y = pos2xyz(cursor) + local tile = block.tiletype[x%16][y%16] + + dc:seek(2,3):string(df.tiletype.attrs[tile].caption, COLOR_CYAN) + dc:newline(2):pen(COLOR_DARKGREY) + render_liquid(dc, block, x, y) + dc:newline(2):pen(COLOR_DARKGREY) + render_flow_state(dc, block, x, y) + else + dc:seek(2,3):string("No map data", COLOR_RED):advance(0,2) + end + + dc:newline():pen(COLOR_GREY) + + dc:newline(1):string("b", COLOR_LIGHTGREEN):string(": ") + self.brush:render(dc) + dc:newline(1):string("p", COLOR_LIGHTGREEN):string(": ") + self.paint:render(dc) + + local paint = self.paint:get() + + dc:newline() + if paint.liquid then + dc:newline(1):string("Amount: "..self.amount) + dc:advance(1):string("("):string("-+", COLOR_LIGHTGREEN):string(")") + dc:newline(3):string("s", COLOR_LIGHTGREEN):string(": ") + self.set:render(dc) + else + dc:advance(0,2) + end + + dc:newline() + if paint.flow then + dc:newline(1):string("f", COLOR_LIGHTGREEN):string(": ") + self.flow:render(dc) + dc:newline(1):string("r", COLOR_LIGHTGREEN):string(": ") + self.permaflow:render(dc) + else + dc:advance(0,2) + end + + dc:newline():newline(1):pen(COLOR_WHITE) + dc:string("Esc", COLOR_LIGHTGREEN):string(": Back, ") + dc:string("Enter", COLOR_LIGHTGREEN):string(": Paint") +end + +function ensure_blocks(cursor, size, cb) + size = size or xyz2pos(1,1,1) + local cx,cy,cz = pos2xyz(cursor) + local all = true + for x=1,size.x or 1,16 do + for y=1,size.y or 1,16 do + for z=1,size.z do + if not dfhack.maps.getTileBlock(cx+x-1, cy+y-1, cz+z-1) then + all = false + end + end + end + end + if all then + cb() + return + end + dlg.showYesNoPrompt( + 'Instantiate Blocks', + 'Not all map blocks are allocated - instantiate?\n\nWarning: new untested feature.', + COLOR_YELLOW, + function() + for x=1,size.x or 1,16 do + for y=1,size.y or 1,16 do + for z=1,size.z do + dfhack.maps.ensureTileBlock(cx+x-1, cy+y-1, cz+z-1) + end + end + end + cb() + end, + function() + cb() + end + ) +end + +function LiquidsUI:onInput(keys) + local paint = self.paint:get() + local liquid = paint.liquid + if keys.CUSTOM_B then + self.brush:step() + elseif keys.CUSTOM_P then + self.paint:step() + elseif liquid and keys.SECONDSCROLL_UP then + self.amount = math.max(0, self.amount-1) + elseif liquid and keys.SECONDSCROLL_DOWN then + self.amount = math.min(7, self.amount+1) + elseif liquid and keys.CUSTOM_S then + self.set:step() + elseif paint.flow and keys.CUSTOM_F then + self.flow:step() + elseif paint.flow and keys.CUSTOM_R then + self.permaflow:step() + elseif keys.LEAVESCREEN then + if guidm.getSelection() then + guidm.clearSelection() + return + end + self:dismiss() + self:sendInputToParent('CURSOR_DOWN_Z') + self:sendInputToParent('CURSOR_UP_Z') + elseif keys.SELECT then + local cursor = guidm.getCursorPos() + local sp = guidm.getSelection() + local size = nil + if self.brush:get().range then + if not sp then + guidm.setSelectionStart(cursor) + return + else + guidm.clearSelection() + cursor, size = guidm.getSelectionRange(cursor, sp) + end + else + guidm.clearSelection() + end + local cb = curry( + liquids.paint, + cursor, + self.brush:get().tag, self.paint:get().tag, + self.amount, size, + self.set:get().tag, self.flow:get().tag, + self.permaflow:get().tag + ) + ensure_blocks(cursor, size, cb) + elseif self:propagateMoveKeys(keys) then + return + elseif keys.D_LOOK_ARENA_WATER then + self.paint.selected = 1 + elseif keys.D_LOOK_ARENA_MAGMA then + self.paint.selected = 2 + end +end + +if not string.match(dfhack.gui.getCurFocus(), '^dwarfmode/LookAround') then + qerror("This script requires the main dwarfmode view in 'k' mode") +end + +local list = LiquidsUI() +list:show() diff --git a/scripts/gui/mechanisms.lua b/scripts/gui/mechanisms.lua new file mode 100644 index 00000000..d1e8ec80 --- /dev/null +++ b/scripts/gui/mechanisms.lua @@ -0,0 +1,129 @@ +-- Shows mechanisms linked to the current building. + +local utils = require 'utils' +local gui = require 'gui' +local guidm = require 'gui.dwarfmode' + +function listMechanismLinks(building) + local lst = {} + local function push(item, mode) + if item then + lst[#lst+1] = { + obj = item, mode = mode, + name = utils.getBuildingName(item) + } + end + end + + push(building, 'self') + + if not df.building_actual:is_instance(building) then + return lst + end + + local item, tref, tgt + for _,v in ipairs(building.contained_items) do + item = v.item + if df.item_trappartsst:is_instance(item) then + tref = dfhack.items.getGeneralRef(item, df.general_ref_type.BUILDING_TRIGGER) + if tref then + push(tref:getBuilding(), 'trigger') + end + tref = dfhack.items.getGeneralRef(item, df.general_ref_type.BUILDING_TRIGGERTARGET) + if tref then + push(tref:getBuilding(), 'target') + end + end + end + + return lst +end + +MechanismList = defclass(MechanismList, guidm.MenuOverlay) + +MechanismList.focus_path = 'mechanisms' + +function MechanismList:init(info) + self:assign{ + links = {}, selected = 1 + } + self:fillList(info.building) +end + +function MechanismList:fillList(building) + local links = listMechanismLinks(building) + + self.old_viewport = self:getViewport() + self.old_cursor = guidm.getCursorPos() + + if #links <= 1 then + links[1].mode = 'none' + end + + self.links = links + self.selected = 1 +end + +local colors = { + self = COLOR_CYAN, none = COLOR_CYAN, + trigger = COLOR_GREEN, target = COLOR_GREEN +} +local icons = { + self = 128, none = 63, trigger = 27, target = 26 +} + +function MechanismList:onRenderBody(dc) + dc:clear() + dc:seek(1,1):string("Mechanism Links", COLOR_WHITE):newline() + + for i,v in ipairs(self.links) do + local pen = { fg=colors[v.mode], bold = (i == self.selected) } + dc:newline(1):pen(pen):char(icons[v.mode]) + dc:advance(1):string(v.name) + end + + local nlinks = #self.links + + if nlinks <= 1 then + dc:newline():newline(1):string("This building has no links", COLOR_LIGHTRED) + end + + dc:newline():newline(1):pen(COLOR_WHITE) + dc:string("Esc", COLOR_LIGHTGREEN):string(": Back, ") + dc:string("Enter", COLOR_LIGHTGREEN):string(": Switch") +end + +function MechanismList:changeSelected(delta) + if #self.links <= 1 then return end + self.selected = 1 + (self.selected + delta - 1) % #self.links + self:selectBuilding(self.links[self.selected].obj) +end + +function MechanismList:onInput(keys) + if keys.SECONDSCROLL_UP then + self:changeSelected(-1) + elseif keys.SECONDSCROLL_DOWN then + self:changeSelected(1) + elseif keys.LEAVESCREEN then + self:dismiss() + if self.selected ~= 1 then + self:selectBuilding(self.links[1].obj, self.old_cursor, self.old_view) + end + elseif keys.SELECT_ALL then + if self.selected > 1 then + self:fillList(self.links[self.selected].obj) + end + elseif keys.SELECT then + self:dismiss() + elseif self:simulateViewScroll(keys) then + return + end +end + +if not string.match(dfhack.gui.getCurFocus(), '^dwarfmode/QueryBuilding/Some') then + qerror("This script requires the main dwarfmode view in 'q' mode") +end + +local list = MechanismList{ building = df.global.world.selected_building } +list:show() +list:changeSelected(1) diff --git a/scripts/gui/power-meter.lua b/scripts/gui/power-meter.lua new file mode 100644 index 00000000..6c2f699a --- /dev/null +++ b/scripts/gui/power-meter.lua @@ -0,0 +1,114 @@ +-- Interface front-end for power-meter plugin. + +local utils = require 'utils' +local gui = require 'gui' +local guidm = require 'gui.dwarfmode' +local dlg = require 'gui.dialogs' + +local plugin = require('plugins.power-meter') +local bselector = df.global.ui_build_selector + +PowerMeter = defclass(PowerMeter, guidm.MenuOverlay) + +PowerMeter.focus_path = 'power-meter' + +function PowerMeter:init() + self:assign{ + min_power = 0, max_power = -1, invert = false, + } +end + +function PowerMeter:onShow() + PowerMeter.super.onShow(self) + + -- Send an event to update the errors + bselector.plate_info.flags.whole = 0 + self:sendInputToParent('BUILDING_TRIGGER_ENABLE_WATER') +end + +function PowerMeter:onRenderBody(dc) + dc:fill(0,0,dc.width-1,13,gui.CLEAR_PEN) + dc:seek(1,1):pen(COLOR_WHITE) + dc:string("Power Meter"):newline():newline(1) + dc:string("Placement"):newline():newline(1) + + dc:string("Excess power range:") + + dc:newline(3):string("as", COLOR_LIGHTGREEN) + dc:string(": Min ") + if self.min_power <= 0 then + dc:string("(any)") + else + dc:string(''..self.min_power) + end + + dc:newline(3):string("zx", COLOR_LIGHTGREEN) + dc:string(": Max ") + if self.max_power < 0 then + dc:string("(any)") + else + dc:string(''..self.max_power) + end + dc:newline():newline(1) + + dc:string("i",COLOR_LIGHTGREEN):string(": ") + if self.invert then + dc:string("Inverted") + else + dc:string("Not inverted") + end +end + +function PowerMeter:onInput(keys) + if keys.CUSTOM_I then + self.invert = not self.invert + elseif keys.BUILDING_TRIGGER_MIN_WATER_UP then + self.min_power = self.min_power + 10 + elseif keys.BUILDING_TRIGGER_MIN_WATER_DOWN then + self.min_power = math.max(0, self.min_power - 10) + elseif keys.BUILDING_TRIGGER_MAX_WATER_UP then + if self.max_power < 0 then + self.max_power = 0 + else + self.max_power = self.max_power + 10 + end + elseif keys.BUILDING_TRIGGER_MAX_WATER_DOWN then + self.max_power = math.max(-1, self.max_power - 10) + elseif keys.LEAVESCREEN then + self:dismiss() + self:sendInputToParent('LEAVESCREEN') + elseif keys.SELECT then + if #bselector.errors == 0 then + if not plugin.makePowerMeter( + bselector.plate_info, + self.min_power, self.max_power, self.invert + ) + then + dlg.showMessage( + 'Power Meter', + 'Could not initialize.', COLOR_LIGHTRED + ) + + self:dismiss() + self:sendInputToParent('LEAVESCREEN') + return + end + + self:sendInputToParent('SELECT') + if bselector.stage ~= 1 then + self:dismiss() + end + end + elseif self:propagateMoveKeys(keys) then + return + end +end + +if dfhack.gui.getCurFocus() ~= 'dwarfmode/Build/Position/Trap' +or bselector.building_subtype ~= df.trap_type.PressurePlate +then + qerror("This script requires the main dwarfmode view in build pressure plate mode") +end + +local list = PowerMeter() +list:show() diff --git a/scripts/gui/rename.lua b/scripts/gui/rename.lua new file mode 100644 index 00000000..70a09b2f --- /dev/null +++ b/scripts/gui/rename.lua @@ -0,0 +1,63 @@ +-- Rename various objects via gui. + +local gui = require 'gui' +local dlg = require 'gui.dialogs' +local plugin = require 'plugins.rename' + +local mode = ... +local focus = dfhack.gui.getCurFocus() + +local function verify_mode(expected) + if mode ~= nil and mode ~= expected then + qerror('Invalid UI state for mode '..mode) + end +end + +local unit = dfhack.gui.getSelectedUnit(true) +local building = dfhack.gui.getSelectedBuilding(true) + +if building and (not unit or mode == 'building') then + verify_mode('building') + + if plugin.canRenameBuilding(building) then + dlg.showInputPrompt( + 'Rename Building', + 'Enter a new name for the building:', COLOR_GREEN, + building.name, + curry(plugin.renameBuilding, building) + ) + else + dlg.showMessage( + 'Rename Building', + 'Cannot rename this type of building.', COLOR_LIGHTRED + ) + end +elseif unit then + if mode == 'unit-profession' then + dlg.showInputPrompt( + 'Rename Unit', + 'Enter a new profession for the unit:', COLOR_GREEN, + unit.custom_profession, + function(newval) + unit.custom_profession = newval + end + ) + else + verify_mode('unit') + + local vname = dfhack.units.getVisibleName(unit) + local vnick = '' + if vname and vname.has_name then + vnick = vname.nickname + end + + dlg.showInputPrompt( + 'Rename Unit', + 'Enter a new nickname for the unit:', COLOR_GREEN, + vnick, + curry(dfhack.units.setNickname, unit) + ) + end +elseif mode then + verify_mode(nil) +end diff --git a/scripts/gui/room-list.lua b/scripts/gui/room-list.lua new file mode 100644 index 00000000..0de82db5 --- /dev/null +++ b/scripts/gui/room-list.lua @@ -0,0 +1,247 @@ +-- Browses rooms owned by a unit. + +local utils = require 'utils' +local gui = require 'gui' +local guidm = require 'gui.dwarfmode' + +local room_type_table = { + [df.building_bedst] = { token = 'bed', qidx = 2, tile = 233 }, + [df.building_tablest] = { token = 'table', qidx = 3, tile = 209 }, + [df.building_chairst] = { token = 'chair', qidx = 4, tile = 210 }, + [df.building_coffinst] = { token = 'coffin', qidx = 5, tile = 48 }, +} + +local room_quality_table = { + { 1, 'Meager Quarters', 'Meager Dining Room', 'Meager Office', 'Grave' }, + { 100, 'Modest Quarters', 'Modest Dining Room', 'Modest Office', "Servant's Burial Chamber" }, + { 250, 'Quarters', 'Dining Room', 'Office', 'Burial Chamber' }, + { 500, 'Decent Quarters', 'Decent Dining Room', 'Decent Office', 'Tomb' }, + { 1000, 'Fine Quarters', 'Fine Dining Room', 'Splendid Office', 'Fine Tomb' }, + { 1500, 'Great Bedroom', 'Great Dining Room', 'Throne Room', 'Mausoleum' }, + { 2500, 'Grand Bedroom', 'Grand Dining Room', 'Opulent Throne Room', 'Grand Mausoleum' }, + { 10000, 'Royal Bedroom', 'Royal Dining Room', 'Royal Throne Room', 'Royal Mausoleum' } +} + +function getRoomName(building, unit) + local info = room_type_table[building._type] + if not info or not building.is_room then + return utils.getBuildingName(building) + end + + local quality = building:getRoomValue(unit) + local row = room_quality_table[1] + for _,v in ipairs(room_quality_table) do + if v[1] <= quality then + row = v + else + break + end + end + return row[info.qidx] +end + +function makeRoomEntry(bld, unit, is_spouse) + local info = room_type_table[bld._type] or {} + + return { + obj = bld, + token = info.token or '?', + tile = info.tile or '?', + caption = getRoomName(bld, unit), + can_use = (not is_spouse or bld:canUseSpouseRoom()), + owner = unit + } +end + +function listRooms(unit, spouse) + local rv = {} + for _,v in pairs(unit.owned_buildings) do + if v.owner == unit then + rv[#rv+1] = makeRoomEntry(v, unit, spouse) + end + end + return rv +end + +function concat_lists(...) + local rv = {} + for i = 1,select('#',...) do + local v = select(i,...) + if v then + for _,x in ipairs(v) do rv[#rv+1] = x end + end + end + return rv +end + +RoomList = defclass(RoomList, guidm.MenuOverlay) + +RoomList.focus_path = 'room-list' + +RoomList.ATTRS{ unit = DEFAULT_NIL } + +function RoomList:init(info) + local unit = info.unit + local base_bld = df.global.world.selected_building + + self:assign{ + base_building = base_bld, + items = {}, selected = 1, + own_rooms = {}, spouse_rooms = {} + } + + self.old_viewport = self:getViewport() + self.old_cursor = guidm.getCursorPos() + + if unit then + self.own_rooms = listRooms(unit) + self.spouse = df.unit.find(unit.relations.spouse_id) + if self.spouse then + self.spouse_rooms = listRooms(self.spouse, unit) + end + self.items = concat_lists(self.own_rooms, self.spouse_rooms) + end + + if base_bld then + for i,v in ipairs(self.items) do + if v.obj == base_bld then + self.selected = i + v.tile = 26 + goto found + end + end + self.base_item = makeRoomEntry(base_bld, unit) + self.base_item.owner = unit + self.base_item.old_owner = base_bld.owner + self.base_item.tile = 26 + self.items = concat_lists({self.base_item}, self.items) + ::found:: + end +end + +local sex_char = { [0] = 12, [1] = 11 } + +function drawUnitName(dc, unit) + dc:pen(COLOR_GREY) + if unit then + local color = dfhack.units.getProfessionColor(unit) + dc:char(sex_char[unit.sex] or '?'):advance(1):pen(color) + + local vname = dfhack.units.getVisibleName(unit) + if vname and vname.has_name then + dc:string(dfhack.TranslateName(vname)..', ') + end + dc:string(dfhack.units.getProfessionName(unit)) + else + dc:string("No Owner Assigned") + end +end + +function drawRoomEntry(dc, entry, selected) + local color = COLOR_GREEN + if not entry.can_use then + color = COLOR_RED + elseif entry.obj.owner ~= entry.owner or not entry.owner then + color = COLOR_CYAN + end + dc:pen{fg = color, bold = (selected == entry)} + dc:char(entry.tile):advance(1):string(entry.caption) +end + +function can_modify(sel_item) + return sel_item and sel_item.owner + and sel_item.can_use and not sel_item.owner.flags1.dead +end + +function RoomList:onRenderBody(dc) + local sel_item = self.items[self.selected] + + dc:clear():seek(1,1) + drawUnitName(dc, self.unit) + + if self.base_item then + dc:newline():newline(2) + drawRoomEntry(dc, self.base_item, sel_item) + end + if #self.own_rooms > 0 then + dc:newline() + for _,v in ipairs(self.own_rooms) do + dc:newline(2) + drawRoomEntry(dc, v, sel_item) + end + end + if #self.spouse_rooms > 0 then + dc:newline():newline(1) + drawUnitName(dc, self.spouse) + + dc:newline() + for _,v in ipairs(self.spouse_rooms) do + dc:newline(2) + drawRoomEntry(dc, v, sel_item) + end + end + if self.unit and #self.own_rooms == 0 and #self.spouse_rooms == 0 then + dc:newline():newline(2):string("No already assigned rooms.", COLOR_LIGHTRED) + end + + dc:newline():newline(1):pen(COLOR_WHITE) + dc:string("Esc", COLOR_LIGHTGREEN):string(": Back") + + if can_modify(sel_item) then + dc:string(", "):string("Enter", COLOR_LIGHTGREEN) + if sel_item.obj.owner == sel_item.owner then + dc:string(": Unassign") + else + dc:string(": Assign") + end + end +end + +function RoomList:changeSelected(delta) + if #self.items <= 1 then return end + self.selected = 1 + (self.selected + delta - 1) % #self.items + self:selectBuilding(self.items[self.selected].obj) +end + +function RoomList:onInput(keys) + local sel_item = self.items[self.selected] + + if keys.SECONDSCROLL_UP then + self:changeSelected(-1) + elseif keys.SECONDSCROLL_DOWN then + self:changeSelected(1) + elseif keys.LEAVESCREEN then + self:dismiss() + + if self.base_building then + if not sel_item or self.base_building ~= sel_item.obj then + self:selectBuilding(self.base_building, self.old_cursor, self.old_view) + end + if self.unit and self.base_building.owner == self.unit then + df.global.ui_building_in_assign = false + end + end + elseif keys.SELECT then + if can_modify(sel_item) then + local owner = sel_item.owner + if sel_item.obj.owner == owner then + owner = sel_item.old_owner + end + dfhack.buildings.setOwner(sel_item.obj, owner) + end + elseif self:simulateViewScroll(keys) then + return + end +end + +local focus = dfhack.gui.getCurFocus() + +if focus == 'dwarfmode/QueryBuilding/Some/Assign/Unit' then + local unit = df.global.ui_building_assign_units[df.global.ui_building_item_cursor] + RoomList{ unit = unit }:show() +elseif string.match(dfhack.gui.getCurFocus(), '^dwarfmode/QueryBuilding/Some') then + local base = df.global.world.selected_building + RoomList{ unit = base.owner }:show() +else + qerror("This script requires the main dwarfmode view in 'q' mode") +end diff --git a/scripts/gui/siege-engine.lua b/scripts/gui/siege-engine.lua new file mode 100644 index 00000000..f460bb21 --- /dev/null +++ b/scripts/gui/siege-engine.lua @@ -0,0 +1,494 @@ +-- Front-end for the siege engine plugin. + +local utils = require 'utils' +local gui = require 'gui' +local guidm = require 'gui.dwarfmode' +local dlg = require 'gui.dialogs' + +local plugin = require 'plugins.siege-engine' +local wmap = df.global.world.map + +local LEGENDARY = df.skill_rating.Legendary + +-- Globals kept between script calls +last_target_min = last_target_min or nil +last_target_max = last_target_max or nil + +local item_choices = { + { caption = 'boulders (default)', item_type = df.item_type.BOULDER }, + { caption = 'blocks', item_type = df.item_type.BLOCKS }, + { caption = 'weapons', item_type = df.item_type.WEAPON }, + { caption = 'trap components', item_type = df.item_type.TRAPCOMP }, + { caption = 'bins', item_type = df.item_type.BIN }, + { caption = 'barrels', item_type = df.item_type.BARREL }, + { caption = 'cages', item_type = df.item_type.CAGE }, + { caption = 'anything', item_type = -1 }, +} + +local item_choice_idx = {} +for i,v in ipairs(item_choices) do + item_choice_idx[v.item_type] = i +end + +SiegeEngine = defclass(SiegeEngine, guidm.MenuOverlay) + +SiegeEngine.focus_path = 'siege-engine' + +SiegeEngine.ATTRS{ building = DEFAULT_NIL } + +function SiegeEngine:init() + self:assign{ + center = utils.getBuildingCenter(self.building), + selected_pile = 1, + mode_main = { + render = self:callback 'onRenderBody_main', + input = self:callback 'onInput_main', + }, + mode_aim = { + render = self:callback 'onRenderBody_aim', + input = self:callback 'onInput_aim', + }, + mode_pile = { + render = self:callback 'onRenderBody_pile', + input = self:callback 'onInput_pile', + } + } +end + +function SiegeEngine:onShow() + SiegeEngine.super.onShow(self) + + self.old_cursor = guidm.getCursorPos() + self.old_viewport = self:getViewport() + + self.mode = self.mode_main + self:showCursor(false) +end + +function SiegeEngine:onDestroy() + if self.save_profile then + plugin.saveWorkshopProfile(self.building) + end + if not self.no_select_building then + self:selectBuilding(self.building, self.old_cursor, self.old_viewport, 10) + end +end + +function SiegeEngine:onGetSelectedBuilding() + return df.global.world.selected_building +end + +function SiegeEngine:showCursor(enable) + local cursor = guidm.getCursorPos() + if cursor and not enable then + self.cursor = cursor + self.target_select_first = nil + guidm.clearCursorPos() + elseif not cursor and enable then + local view = self:getViewport() + cursor = self.cursor + if not cursor or not view:isVisible(cursor) then + cursor = view:getCenter() + end + self.cursor = nil + guidm.setCursorPos(cursor) + end +end + +function SiegeEngine:centerViewOn(pos) + local cursor = guidm.getCursorPos() + if cursor then + guidm.setCursorPos(pos) + else + self.cursor = pos + end + self:getViewport():centerOn(pos):set() +end + +function SiegeEngine:zoomToTarget() + local target_min, target_max = plugin.getTargetArea(self.building) + if target_min then + local cx = math.floor((target_min.x + target_max.x)/2) + local cy = math.floor((target_min.y + target_max.y)/2) + local cz = math.floor((target_min.z + target_max.z)/2) + local pos = plugin.adjustToTarget(self.building, xyz2pos(cx,cy,cz)) + self:centerViewOn(pos) + end +end + +function paint_target_grid(dc, view, origin, p1, p2) + local r1, sz, r2 = guidm.getSelectionRange(p1, p2) + + if view.z < r1.z or view.z > r2.z then + return + end + + local p1 = view:tileToScreen(r1) + local p2 = view:tileToScreen(r2) + local org = view:tileToScreen(origin) + dc:pen{ fg = COLOR_CYAN, bg = COLOR_CYAN, ch = '+', bold = true } + + -- Frame + dc:fill(p1.x,p1.y,p1.x,p2.y) + dc:fill(p1.x,p1.y,p2.x,p1.y) + dc:fill(p2.x,p1.y,p2.x,p2.y) + dc:fill(p1.x,p2.y,p2.x,p2.y) + + -- Grid + local gxmin = org.x+10*math.ceil((p1.x-org.x)/10) + local gxmax = org.x+10*math.floor((p2.x-org.x)/10) + local gymin = org.y+10*math.ceil((p1.y-org.y)/10) + local gymax = org.y+10*math.floor((p2.y-org.y)/10) + for x = gxmin,gxmax,10 do + for y = gymin,gymax,10 do + dc:fill(p1.x,y,p2.x,y) + dc:fill(x,p1.y,x,p2.y) + end + end +end + +function SiegeEngine:renderTargetView(target_min, target_max) + local view = self:getViewport() + local map = self.df_layout.map + local map_dc = gui.Painter.new(map) + + plugin.paintAimScreen( + self.building, view:getPos(), + xy2pos(map.x1, map.y1), view:getSize() + ) + + if target_min and math.floor(dfhack.getTickCount()/500) % 2 == 0 then + paint_target_grid(map_dc, view, self.center, target_min, target_max) + end + + local cursor = guidm.getCursorPos() + if cursor then + local cx, cy, cz = pos2xyz(view:tileToScreen(cursor)) + if cz == 0 then + map_dc:seek(cx,cy):char('X', COLOR_YELLOW) + end + end +end + +function SiegeEngine:scrollPiles(delta) + local links = plugin.getStockpileLinks(self.building) + if links then + self.selected_pile = 1+(self.selected_pile+delta-1) % #links + return links[self.selected_pile] + end +end + +function SiegeEngine:renderStockpiles(dc, links, nlines) + local idx = (self.selected_pile-1) % #links + local page = math.floor(idx/nlines) + for i = page*nlines,math.min(#links,(page+1)*nlines)-1 do + local color = COLOR_BROWN + if i == idx then + color = COLOR_YELLOW + end + dc:newline(2):string(utils.getBuildingName(links[i+1]), color) + end +end + +function SiegeEngine:onRenderBody_main(dc) + dc:newline(1):pen(COLOR_WHITE):string("Target: ") + + local target_min, target_max = plugin.getTargetArea(self.building) + if target_min then + dc:string( + (target_max.x-target_min.x+1).."x".. + (target_max.y-target_min.y+1).."x".. + (target_max.z-target_min.z+1).." Rect" + ) + else + dc:string("None (default)") + end + + dc:newline(3):string("r",COLOR_LIGHTGREEN):string(": Rectangle") + if last_target_min then + dc:string(", "):string("p",COLOR_LIGHTGREEN):string(": Paste") + end + dc:newline(3) + if target_min then + dc:string("x",COLOR_LIGHTGREEN):string(": Clear, ") + dc:string("z",COLOR_LIGHTGREEN):string(": Zoom") + end + + dc:newline():newline(1) + if self.building.type == df.siegeengine_type.Ballista then + dc:string("Uses ballista arrows") + else + local item = plugin.getAmmoItem(self.building) + dc:string("u",COLOR_LIGHTGREEN):string(": Use ") + if item_choice_idx[item] then + dc:string(item_choices[item_choice_idx[item]].caption) + else + dc:string(df.item_type[item]) + end + end + + dc:newline():newline(1) + dc:string("t",COLOR_LIGHTGREEN):string(": Take from stockpile"):newline(3) + local links = plugin.getStockpileLinks(self.building) + local bottom = dc.height - 5 + if links then + dc:string("d",COLOR_LIGHTGREEN):string(": Delete, ") + dc:string("o",COLOR_LIGHTGREEN):string(": Zoom"):newline() + self:renderStockpiles(dc, links, bottom-2-dc:localY()) + dc:newline():newline() + end + + local prof = self.building:getWorkshopProfile() or {} + dc:seek(1,math.max(dc:localY(),19)):string('ghjk',COLOR_LIGHTGREEN)dc:string(': ') + dc:string(df.skill_rating.attrs[prof.min_level or 0].caption):string('-') + dc:string(df.skill_rating.attrs[math.min(LEGENDARY,prof.max_level or 3000)].caption) + dc:newline():newline() + + if self.target_select_first then + self:renderTargetView(self.target_select_first, guidm.getCursorPos()) + else + self:renderTargetView(target_min, target_max) + end +end + +function SiegeEngine:setTargetArea(p1, p2) + self.target_select_first = nil + + if not plugin.setTargetArea(self.building, p1, p2) then + dlg.showMessage( + 'Set Target Area', + 'Could not set the target area', COLOR_LIGHTRED + ) + else + last_target_min = p1 + last_target_max = p2 + end +end + +function SiegeEngine:setAmmoItem(choice) + if self.building.type == df.siegeengine_type.Ballista then + return + end + + if not plugin.setAmmoItem(self.building, choice.item_type) then + dlg.showMessage( + 'Set Ammo Item', + 'Could not set the ammo item', COLOR_LIGHTRED + ) + end +end + +function SiegeEngine:onInput_main(keys) + if keys.CUSTOM_R then + self:showCursor(true) + self.target_select_first = nil + self.mode = self.mode_aim + elseif keys.CUSTOM_P and last_target_min then + self:setTargetArea(last_target_min, last_target_max) + elseif keys.CUSTOM_U then + local item = plugin.getAmmoItem(self.building) + local idx = 1 + (item_choice_idx[item] or 0) % #item_choices + self:setAmmoItem(item_choices[idx]) + elseif keys.CUSTOM_Z then + self:zoomToTarget() + elseif keys.CUSTOM_X then + plugin.clearTargetArea(self.building) + elseif keys.SECONDSCROLL_UP then + self:scrollPiles(-1) + elseif keys.SECONDSCROLL_DOWN then + self:scrollPiles(1) + elseif keys.CUSTOM_D then + local pile = self:scrollPiles(0) + if pile then + plugin.removeStockpileLink(self.building, pile) + end + elseif keys.CUSTOM_O then + local pile = self:scrollPiles(0) + if pile then + self:centerViewOn(utils.getBuildingCenter(pile)) + end + elseif keys.CUSTOM_T then + self:showCursor(true) + self.mode = self.mode_pile + self:sendInputToParent('CURSOR_DOWN_Z') + self:sendInputToParent('CURSOR_UP_Z') + elseif keys.CUSTOM_G then + local prof = plugin.saveWorkshopProfile(self.building) + prof.min_level = math.max(0, prof.min_level-1) + plugin.saveWorkshopProfile(self.building) + elseif keys.CUSTOM_H then + local prof = plugin.saveWorkshopProfile(self.building) + prof.min_level = math.min(LEGENDARY, prof.min_level+1) + plugin.saveWorkshopProfile(self.building) + elseif keys.CUSTOM_J then + local prof = plugin.saveWorkshopProfile(self.building) + prof.max_level = math.max(0, math.min(LEGENDARY,prof.max_level)-1) + plugin.saveWorkshopProfile(self.building) + elseif keys.CUSTOM_K then + local prof = plugin.saveWorkshopProfile(self.building) + prof.max_level = math.min(LEGENDARY, prof.max_level+1) + if prof.max_level >= LEGENDARY then prof.max_level = 3000 end + plugin.saveWorkshopProfile(self.building) + elseif self:simulateViewScroll(keys) then + self.cursor = nil + else + return false + end + return true +end + +local status_table = { + ok = { pen = COLOR_GREEN, msg = "Target accessible" }, + out_of_range = { pen = COLOR_CYAN, msg = "Target out of range" }, + blocked = { pen = COLOR_RED, msg = "Target obstructed" }, + semi_blocked = { pen = COLOR_BROWN, msg = "Partially obstructed" }, +} + +function SiegeEngine:onRenderBody_aim(dc) + local cursor = guidm.getCursorPos() + local first = self.target_select_first + + dc:newline(1):string('Select target rectangle'):newline() + + local info = status_table[plugin.getTileStatus(self.building, cursor)] + if info then + dc:newline(2):string(info.msg, info.pen) + else + dc:newline(2):string('ERROR', COLOR_RED) + end + + dc:newline():newline(1):string("Enter",COLOR_LIGHTGREEN) + if first then + dc:string(": Finish rectangle") + else + dc:string(": Start rectangle") + end + dc:newline() + + local target_min, target_max = plugin.getTargetArea(self.building) + if target_min then + dc:newline(1):string("z",COLOR_LIGHTGREEN):string(": Zoom to current target") + end + + if first then + self:renderTargetView(first, cursor) + else + local target_min, target_max = plugin.getTargetArea(self.building) + self:renderTargetView(target_min, target_max) + end +end + +function SiegeEngine:onInput_aim(keys) + if keys.SELECT then + local cursor = guidm.getCursorPos() + if self.target_select_first then + self:setTargetArea(self.target_select_first, cursor) + + self.mode = self.mode_main + self:showCursor(false) + else + self.target_select_first = cursor + end + elseif keys.CUSTOM_Z then + self:zoomToTarget() + elseif keys.LEAVESCREEN then + self.mode = self.mode_main + self:showCursor(false) + elseif self:simulateCursorMovement(keys) then + self.cursor = nil + else + return false + end + return true +end + +function SiegeEngine:onRenderBody_pile(dc) + dc:newline(1):string('Select pile to take from'):newline():newline(2) + + local sel = df.global.world.selected_building + + if df.building_stockpilest:is_instance(sel) then + dc:string(utils.getBuildingName(sel), COLOR_GREEN):newline():newline(1) + + if plugin.isLinkedToPile(self.building, sel) then + dc:string("Already taking from here"):newline():newline(2) + dc:string("d", COLOR_LIGHTGREEN):string(": Delete link") + else + dc:string("Enter",COLOR_LIGHTGREEN):string(": Take from this pile") + end + elseif sel then + dc:string(utils.getBuildingName(sel), COLOR_DARKGREY) + dc:newline():newline(1) + dc:string("Not a stockpile",COLOR_LIGHTRED) + else + dc:string("No building selected", COLOR_DARKGREY) + end +end + +function SiegeEngine:onInput_pile(keys) + if keys.SELECT then + local sel = df.global.world.selected_building + if df.building_stockpilest:is_instance(sel) + and not plugin.isLinkedToPile(self.building, sel) then + plugin.addStockpileLink(self.building, sel) + + df.global.world.selected_building = self.building + self.mode = self.mode_main + self:showCursor(false) + end + elseif keys.CUSTOM_D then + local sel = df.global.world.selected_building + if df.building_stockpilest:is_instance(sel) then + plugin.removeStockpileLink(self.building, sel) + end + elseif keys.LEAVESCREEN then + df.global.world.selected_building = self.building + self.mode = self.mode_main + self:showCursor(false) + elseif self:propagateMoveKeys(keys) then + -- + else + return false + end + return true +end + +function SiegeEngine:onRenderBody(dc) + dc:clear() + dc:seek(1,1):pen(COLOR_WHITE):string(utils.getBuildingName(self.building)):newline() + + self.mode.render(dc) + + dc:seek(1, math.max(dc:localY(), 21)):pen(COLOR_WHITE) + dc:string("ESC", COLOR_LIGHTGREEN):string(": Back, ") + dc:string("c", COLOR_LIGHTGREEN):string(": Recenter") +end + +function SiegeEngine:onInput(keys) + if self.mode.input(keys) then + -- + elseif keys.CUSTOM_C then + self:centerViewOn(self.center) + elseif keys.LEAVESCREEN then + self:dismiss() + elseif keys.LEAVESCREEN_ALL then + self:dismiss() + self.no_select_building = true + guidm.clearCursorPos() + df.global.ui.main.mode = df.ui_sidebar_mode.Default + df.global.world.selected_building = nil + end +end + +if not string.match(dfhack.gui.getCurFocus(), '^dwarfmode/QueryBuilding/Some/SiegeEngine') then + qerror("This script requires a siege engine selected in 'q' mode") +end + +local building = df.global.world.selected_building + +if not df.building_siegeenginest:is_instance(building) then + qerror("A siege engine must be selected") +end + +local list = SiegeEngine{ building = building } +list:show() diff --git a/scripts/setfps.lua b/scripts/setfps.lua new file mode 100644 index 00000000..690f8270 --- /dev/null +++ b/scripts/setfps.lua @@ -0,0 +1,10 @@ +-- Set the FPS cap at runtime. + +local cap = ... +local capnum = tonumber(cap) + +if not capnum or capnum < 1 then + qerror('Invalid FPS cap value: '..cap) +end + +df.global.enabler.fps = capnum diff --git a/scripts/siren.lua b/scripts/siren.lua new file mode 100644 index 00000000..30d3aa07 --- /dev/null +++ b/scripts/siren.lua @@ -0,0 +1,122 @@ +-- Wakes up the sleeping, breaks up parties and stops breaks. + +local utils = require 'utils' + +local args = {...} +local burrows = {} +local bnames = {} + +if not dfhack.isMapLoaded() then + qerror('Map is not loaded.') +end + +for _,v in ipairs(args) do + local b = dfhack.burrows.findByName(v) + if not b then + qerror('Unknown burrow: '..v) + end + table.insert(bnames, v) + table.insert(burrows, b) +end + +local in_siege = false + +function is_in_burrows(pos) + if #burrows == 0 then + return true + end + for _,v in ipairs(burrows) do + if dfhack.burrows.isAssignedTile(v, pos) then + return true + end + end +end + +function add_thought(unit, code) + for _,v in ipairs(unit.status.recent_events) do + if v.type == code then + v.age = 0 + return + end + end + + unit.status.recent_events:insert('#', { new = true, type = code }) +end + +function wake_unit(unit) + local job = unit.job.current_job + if not job or job.job_type ~= df.job_type.Sleep then + return + end + + if job.completion_timer > 0 then + unit.counters.unconscious = 0 + add_thought(unit, df.unit_thought_type.SleepNoiseWake) + elseif job.completion_timer < 0 then + add_thought(unit, df.unit_thought_type.Tired) + end + + job.pos:assign(unit.pos) + + job.completion_timer = 0 + + unit.path.dest:assign(unit.pos) + unit.path.path.x:resize(0) + unit.path.path.y:resize(0) + unit.path.path.z:resize(0) + + unit.counters.job_counter = 0 +end + +function stop_break(unit) + local counter = dfhack.units.getMiscTrait(unit, df.misc_trait_type.OnBreak) + if counter then + counter.id = df.misc_trait_type.TimeSinceBreak + counter.value = 100800 - 30*1200 + add_thought(unit, df.unit_thought_type.Tired) + end +end + +-- Check siege for thought purpose +for _,v in ipairs(df.global.ui.invasions.list) do + if v.flags.siege and v.flags.active then + in_siege = true + break + end +end + +-- Stop rest +for _,v in ipairs(df.global.world.units.active) do + local x,y,z = dfhack.units.getPosition(v) + if x and dfhack.units.isCitizen(v) and is_in_burrows(xyz2pos(x,y,z)) then + if not in_siege and v.military.squad_index < 0 then + add_thought(v, df.unit_thought_type.LackProtection) + end + wake_unit(v) + stop_break(v) + end +end + +-- Stop parties +for _,v in ipairs(df.global.ui.parties) do + local pos = utils.getBuildingCenter(v.location) + if is_in_burrows(pos) then + v.timer = 0 + for _, u in ipairs(v.units) do + add_thought(unit, df.unit_thought_type.Tired) + end + end +end + +local place = 'the halls and tunnels' +if #bnames > 0 then + if #bnames == 1 then + place = bnames[1] + else + place = table.concat(bnames,', ',1,#bnames-1)..' and '..bnames[#bnames] + end +end +dfhack.gui.showAnnouncement( + 'A loud siren sounds throughout '..place..', waking the sleeping and startling the awake.', + COLOR_BROWN, true +) diff --git a/scripts/superdwarf.rb b/scripts/superdwarf.rb new file mode 100644 index 00000000..7f5296b7 --- /dev/null +++ b/scripts/superdwarf.rb @@ -0,0 +1,61 @@ +# give super-dwarven speed to an unit + +$superdwarf_onupdate ||= nil +$superdwarf_ids ||= [] + +case $script_args[0] +when 'add' + if u = df.unit_find + $superdwarf_ids |= [u.id] + + $superdwarf_onupdate ||= df.onupdate_register(1) { + if $superdwarf_ids.empty? + df.onupdate_unregister($superdwarf_onupdate) + $superdwarf_onupdate = nil + else + $superdwarf_ids.each { |id| + if u = df.unit_find(id) and not u.flags1.dead + # faster walk/work + if u.counters.job_counter > 0 + u.counters.job_counter = 0 + end + + # no sleep + if u.counters2.sleepiness_timer > 10000 + u.counters2.sleepiness_timer = 1 + end + + # no break + if b = u.status.misc_traits.find { |t| t.id == :OnBreak } + b.value = 500_000 + end + else + $superdwarf_ids.delete id + end + } + end + } + else + puts "Select a creature using 'v'" + end + +when 'del' + if u = df.unit_find + $superdwarf_ids.delete u.id + else + puts "Select a creature using 'v'" + end + +when 'clear' + $superdwarf_ids.clear + +when 'list' + puts "current superdwarves:", $superdwarf_ids.map { |id| df.unit_find(id).name } + +else + puts "Usage:", + " - superdwarf add: give superspeed to currently selected creature", + " - superdwarf del: remove superspeed to current creature", + " - superdwarf clear: remove all superpowers", + " - superdwarf list: list super-dwarves" +end |
