Lua Api
Lua Api
==================================
Introduction
------------
Mods are contained and ran solely on the server side. Definitions and media
files are automatically transferred to the client.
If you see a deficiency in the API, feel free to attempt to add the
functionality in the engine and API, and to document it here.
Programming in Lua
------------------
Startup
-------
Mods are loaded during server startup from the mod load paths by running
the `init.lua` scripts in a shared environment.
Paths
-----
Minetest keeps and looks for files mostly in two paths. `path_share` or
`path_user`.
`path_share` contains possibly read-only content for the engine (incl. games and
mods).
`path_user` contains mods or games installed by the user but also the users
worlds or settings.
Games
=====
* `$path_share/games/<gameid>/`
* `$path_user/games/<gameid>/`
Where `<gameid>` is unique to each game.
Menu images
-----------
Games can provide custom main menu images. They are put inside a `menu`
directory inside the game directory.
Menu music
-----------
Games can provide custom main menu music. They are put inside a `menu`
directory inside the game directory.
Mods
====
Paths are relative to the directories listed in the [Paths] section above.
* `games/<gameid>/mods/`
* `mods/`
* `worlds/<worldname>/worldmods/`
World-specific games
--------------------
This is useful for e.g. adventure worlds and happens if the `<worldname>/game/`
directory exists.
Modpacks
--------
* `name`: The modpack name. Allows Minetest to determine the modpack name even
if the folder is wrongly named.
* `description`: Description of mod to be shown in the Mods tab of the main
menu.
* `author`: The author of the modpack. It only appears when downloaded from
ContentDB.
* `release`: Ignore this: Should only ever be set by ContentDB, as it is an
internal ID used to track versions.
* `title`: A human-readable title to address the modpack.
mods
├── modname
│ ├── mod.conf
│ ├── screenshot.png
│ ├── settingtypes.txt
│ ├── init.lua
│ ├── models
│ ├── textures
│ │ ├── modname_stuff.png
│ │ ├── modname_stuff_normal.png
│ │ ├── modname_something_else.png
│ │ ├── subfolder_foo
│ │ │ ├── modname_more_stuff.png
│ │ │ └── another_subfolder
│ │ └── bar_subfolder
│ ├── sounds
│ ├── media
│ ├── locale
│ └── <custom data>
└── another
### modname
### mod.conf
* `name`: The mod name. Allows Minetest to determine the mod name even if the
folder is wrongly named.
* `description`: Description of mod to be shown in the Mods tab of the main
menu.
* `depends`: A comma separated list of dependencies. These are mods that must be
loaded before this mod.
* `optional_depends`: A comma separated list of optional dependencies.
Like a dependency, but no error if the mod doesn't exist.
* `author`: The author of the mod. It only appears when downloaded from
ContentDB.
* `release`: Ignore this: Should only ever be set by ContentDB, as it is an
internal ID used to track versions.
* `title`: A human-readable title to address the mod.
### `screenshot.png`
A screenshot shown in the mod manager within the main menu. It should
have an aspect ratio of 3:2 and a minimum size of 300×200 pixels.
### `depends.txt`
### `description.txt`
A file containing a description to be shown in the Mods tab of the main menu.
### `settingtypes.txt`
### `init.lua`
The main Lua script. Running this script should register everything it
wants to register. Subsequent execution depends on minetest calling the
registered callbacks.
It is suggested to use the folders for the purpose they are thought for,
eg. put textures into `textures`, translation files into `locale`,
models for entities or meshnodes into `models` et cetera.
Although it is discouraged, a mod can overwrite a media file of any mod that it
depends on by supplying a file with an equal name.
Naming conventions
------------------
modname:<whatever>
a-zA-Z0-9_
Registered names can be overridden by prefixing the name with `:`. This can
be used for overriding the registrations of some other mod.
The `:` prefix can also be used for maintaining backwards compatibility.
### Example
:experimental:tnt
when registering it. For this to work correctly, that mod must have
`experimental` as a dependency.
Aliases
=======
This can also set quick access names for things, e.g. if
you have an item called `epiclylongmodname:stuff`, you could do
minetest.register_alias("stuff", "epiclylongmodname:stuff")
Mapgen aliases
--------------
In a game, a certain number of these must be set to tell core mapgens which
of the game's nodes are to be used for core mapgen generation. For example:
minetest.register_alias("mapgen_stone", "default:stone")
* `mapgen_stone`
* `mapgen_water_source`
* `mapgen_river_water_source`
`mapgen_river_water_source` is required for mapgens with sloping rivers where
it is necessary to have a river liquid node with a short `liquid_range` and
`liquid_renewable = false` to avoid flooding.
* `mapgen_lava_source`
Fallback lava node used if cave liquids are not defined in biome definitions.
Deprecated, define cave liquids in biome definitions instead.
* `mapgen_cobble`
Fallback node used if dungeon nodes are not defined in biome definitions.
Deprecated, define dungeon nodes in biome definitions instead.
#### Essential
* `mapgen_stone`
* `mapgen_water_source`
* `mapgen_lava_source`
* `mapgen_dirt`
* `mapgen_dirt_with_grass`
* `mapgen_sand`
* `mapgen_tree`
* `mapgen_leaves`
* `mapgen_apple`
* `mapgen_cobble`
#### Optional
By default the world is filled with air nodes. To set a different node use e.g.:
minetest.register_alias("mapgen_singlenode", "default:stone")
Textures
========
Mods should generally prefix their textures with `modname_`, e.g. given
the mod name `foomod`, a texture could be called:
foomod_foothing.png
* e.g. `foomod_foothing.png`
* e.g. `foomod_foothing`
Supported texture formats are PNG (`.png`), JPEG (`.jpg`), Bitmap (`.bmp`)
and Targa (`.tga`).
Since better alternatives exist, the latter two may be removed in the future.
Texture modifiers
-----------------
Example:
default_dirt.png^default_grass_side.png
Example: `cobble.png^(thing1.png^thing2.png)`
### Escaping
Modifiers that accept texture names (e.g. `[combine`) accept escaping to allow
passing complex texture names as arguments. Escaping is done with backslash and
is required for `^`, `:` and `\`.
Example: `cobble.png^[lowpart:50:color.png\^[mask\:trans.png`
Or as a Lua string: `"cobble.png^[lowpart:50:color.png\\^[mask\\:trans.png"`
The lower 50 percent of `color.png^[mask:trans.png` are overlaid
on top of `cobble.png`.
#### Crack
* `[crack:<n>:<p>`
* `[cracko:<n>:<p>`
* `[crack:<t>:<n>:<p>`
* `[cracko:<t>:<n>:<p>`
Parameters:
Example:
default_cobble.png^[crack:10:1
#### `[combine:<w>x<h>:<x1>,<y1>=<file1>:<x2>,<y2>=<file2>:...`
* `<w>`: width
* `<h>`: height
* `<x>`: x position
* `<y>`: y position
* `<file>`: texture to combine
Creates a texture of size `<w>` times `<h>` and blits the listed files to their
specified coordinates.
Example:
[combine:16x32:0,0=default_cobble.png:0,16=default_wood.png
#### `[resize:<w>x<h>`
Example:
default_sandstone.png^[resize:16x16
#### `[opacity:<r>`
Example:
default_sandstone.png^[opacity:127
#### `[invert:<mode>`
Example:
default_apple.png^[invert:rgb
#### `[brighten`
Example:
tnt_tnt_side.png^[brighten
#### `[noalpha`
Example:
default_leaves.png^[noalpha
#### `[makealpha:<r>,<g>,<b>`
Example:
default_cobble.png^[makealpha:128,128,128
#### `[transform<t>`
0 I identity
1 R90 rotate by 90 degrees
2 R180 rotate by 180 degrees
3 R270 rotate by 270 degrees
4 FX flip X
5 FXR90 flip X then rotate by 90 degrees
6 FY flip Y
7 FYR90 flip Y then rotate by 90 degrees
Example:
default_stone.png^[transformFXR90
#### `[inventorycube{<top>{<left>{<right>`
Escaping does not apply here and `^` is replaced by `&` in texture names
instead.
Example:
[inventorycube{grass.png{dirt.png&grass_side.png{dirt.png&grass_side.png
#### `[lowpart:<percent>:<file>`
Example:
base.png^[lowpart:25:overlay.png
#### `[verticalframe:<t>:<n>`
Example:
default_torch_animated.png^[verticalframe:16:8
#### `[mask:<file>`
#### `[sheet:<w>x<h>:<x>,<y>`
#### `[colorize:<color>:<ratio>`
#### `[multiply:<color>`
#### `[png:<base64>`
Hardware coloring
-----------------
When you register an item or node, set its `color` field (which accepts a
`ColorSpec`) to the desired color.
Each tile may have an individual static color, which overwrites every
other coloring method. To disable the coloring of a face,
set its color to white (because multiplying with white does nothing).
You can set the `color` property of the tiles in the node's definition
if the tile is in table format.
### Palettes
For nodes and items which can have many colors, a palette is more
suitable. A palette is a texture, which can contain up to 256 pixels.
Each pixel is one possible color for the node/item.
You can register one node/item, which can have up to 256 colors.
Examples:
* `paramtype2 = "color"` for nodes which use their full `param2` for
palette indexing. These nodes can have 256 different colors.
The palette should contain 256 pixels.
* `paramtype2 = "colorwallmounted"` for nodes which use the first
five bits (most significant) of `param2` for palette indexing.
The remaining three bits are describing rotation, as in `wallmounted`
paramtype2. Division by 8 yields the palette index (without stretching the
palette). These nodes can have 32 different colors, and the palette
should contain 32 pixels.
Examples:
* `param2 = 17` is 2 * 8 + 1, so the rotation is 1 and the third (= 2 + 1)
pixel will be picked from the palette.
* `param2 = 35` is 4 * 8 + 3, so the rotation is 3 and the fifth (= 4 + 1)
pixel will be picked from the palette.
* `paramtype2 = "colorfacedir"` for nodes which use the first
three bits of `param2` for palette indexing. The remaining
five bits are describing rotation, as in `facedir` paramtype2.
Division by 32 yields the palette index (without stretching the
palette). These nodes can have 8 different colors, and the
palette should contain 8 pixels.
Examples:
* `param2 = 17` is 0 * 32 + 17, so the rotation is 17 and the
first (= 0 + 1) pixel will be picked from the palette.
* `param2 = 35` is 1 * 32 + 3, so the rotation is 3 and the
second (= 1 + 1) pixel will be picked from the palette.
* `paramtype2 = "color4dir"` for nodes which use the first
six bits of `param2` for palette indexing. The remaining
two bits are describing rotation, as in `4dir` paramtype2.
Division by 4 yields the palette index (without stretching the
palette). These nodes can have 64 different colors, and the
palette should contain 64 pixels.
Examples:
* `param2 = 17` is 4 * 4 + 1, so the rotation is 1 and the
fifth (= 4 + 1) pixel will be picked from the palette.
* `param2 = 35` is 8 * 4 + 3, so the rotation is 3 and the
ninth (= 8 + 1) pixel will be picked from the palette.
Example:
minetest.register_node("mod:stone", {
description = "Stone",
tiles = {"default_stone.png"},
paramtype2 = "color",
palette = "palette.png",
drop = {
items = {
-- assume that mod:cobblestone also has the same palette
{items = {"mod:cobblestone"}, inherit_color = true },
}
}
})
Craft recipes only support item strings, but fortunately item strings
can also contain metadata. Example craft recipe registration:
minetest.register_craft({
output = minetest.itemstring_with_palette("wool:block", 3),
type = "shapeless",
recipe = {
"wool:block",
"dye:red",
},
})
Metadata field filtering in the `recipe` field are not supported yet,
so the craft output is independent of the color of the ingredients.
These overlays are 'soft', because unlike texture modifiers, the layers
are not merged in the memory, but they are simply drawn on top of each
other. This allows different hardware coloring, but also means that
tiles with overlays are drawn slower. Using too much overlays might
cause FPS loss.
For inventory and wield images you can specify overlays which
hardware coloring does not modify. You have to set `inventory_overlay`
and `wield_overlay` fields to an image name.
To define a node overlay, simply set the `overlay_tiles` field of the node
definition. These tiles are defined in the same way as plain tiles:
they can have a texture name, color etc.
To skip one face, set that overlay tile to an empty string.
minetest.register_node("default:dirt_with_grass", {
description = "Dirt with Grass",
-- Regular tiles, as usual
-- The dirt tile disables palette coloring
tiles = {{name = "default_grass.png"},
{name = "default_dirt.png", color = "white"}},
-- Overlay tiles: define them in the same style
-- The top and bottom tile does not have overlay
overlay_tiles = {"", "",
{name = "default_grass_side.png"}},
-- Global color, used in inventory
color = "green",
-- Palette in the world
paramtype2 = "color",
palette = "default_foilage.png",
})
Sounds
======
Mods should generally prefix their sounds with `modname_`, e.g. given
the mod name "`foomod`", a sound could be called:
foomod_foosound.ogg
Sounds are referred to by their name with a dot, a single digit and the
file extension stripped out. When a sound is played, the actual sound file
is chosen randomly from the matching sounds.
* `foomod_foosound.ogg`
* `foomod_foosound.0.ogg`
* `foomod_foosound.1.ogg`
* (...)
* `foomod_foosound.9.ogg`
`SimpleSoundSpec`
-----------------
Examples:
* `""`: No sound
* `{}`: No sound
* `"default_place_node"`: Play e.g. `default_place_node.ogg`
* `{name = "default_place_node"}`: Same as above
* `{name = "default_place_node", gain = 0.5}`: 50% volume
* `{name = "default_place_node", gain = 0.9, pitch = 1.1}`: 90% volume, 110% pitch
* `player_damage`: Played when the local player takes damage (gain = 0.5)
* `player_falling_damage`: Played when the local player takes
damage by falling (gain = 0.5)
* `player_jump`: Played when the local player jumps
* `default_dig_<groupname>`: Default node digging sound (gain = 0.5)
(see node sound definition for details)
Registered definitions
======================
Anything added using certain [Registration functions] gets added to one or more
of the global [Registered definition tables].
Note that in some cases you will stumble upon things that are not contained
in these tables (e.g. when a mod has been removed). Always check for
existence before trying to access the fields.
Example:
If you want to check the drawtype of a node, you could do it like this:
Nodes
=====
Nodes are the bulk data of the world: cubes and other things that take the
space of a cube. Huge amounts of them are handled efficiently, but they
are quite static.
minetest.registered_nodes[node.name]
`param1` and `param2` are 8-bit integers ranging from 0 to 255. The engine uses
them for certain automated functions. If you don't use these functions, you can
use them to store arbitrary values.
Node paramtypes
---------------
The functions of `param1` and `param2` are determined by certain fields in the
node definition.
* `paramtype = "light"`
* The value stores light with and without sun in its lower and upper 4 bits
respectively.
* Required by a light source node to enable spreading its light.
* Required by the following drawtypes as they determine their visual
brightness from their internal light value:
* torchlike
* signlike
* firelike
* fencelike
* raillike
* nodebox
* mesh
* plantlike
* plantlike_rooted
* `paramtype = "none"`
* `param1` will not be used by the engine and can be used to store
an arbitrary value
* `paramtype2 = "flowingliquid"`
* Used by `drawtype = "flowingliquid"` and `liquidtype = "flowing"`
* The liquid level and a flag of the liquid are stored in `param2`
* Bits 0-2: Liquid level (0-7). The higher, the more liquid is in this node;
see `minetest.get_node_level`, `minetest.set_node_level` and
`minetest.add_node_level`
to access/manipulate the content of this field
* Bit 3: If set, liquid is flowing downwards (no graphical effect)
* `paramtype2 = "wallmounted"`
* Supported drawtypes: "torchlike", "signlike", "plantlike",
"plantlike_rooted", "normal", "nodebox", "mesh"
* The rotation of the node is stored in `param2`
* Node is 'mounted'/facing towards one of 6 directions
* You can make this value by using `minetest.dir_to_wallmounted()`
* Values range 0 - 5
* The value denotes at which direction the node is "mounted":
0 = y+, 1 = y-, 2 = x+, 3 = x-, 4 = z+, 5 = z-
* By default, on placement the param2 is automatically set to the
appropriate rotation, depending on which side was pointed at
* `paramtype2 = "facedir"`
* Supported drawtypes: "normal", "nodebox", "mesh"
* The rotation of the node is stored in `param2`.
* Node is rotated around face and axis; 24 rotations in total.
* Can be made by using `minetest.dir_to_facedir()`.
* Chests and furnaces can be rotated that way, and also 'flipped'
* Values range 0 - 23
* facedir / 4 = axis direction:
0 = y+, 1 = z+, 2 = z-, 3 = x+, 4 = x-, 5 = y-
* The node is rotated 90 degrees around the X or Z axis so that its top face
points in the desired direction. For the y- direction, it's rotated 180
degrees around the Z axis.
* facedir modulo 4 = left-handed rotation around the specified axis, in 90°
steps.
* By default, on placement the param2 is automatically set to the
horizontal direction the player was looking at (values 0-3)
* Special case: If the node is a connected nodebox, the nodebox
will NOT rotate, only the textures will.
* `paramtype2 = "4dir"`
* Supported drawtypes: "normal", "nodebox", "mesh"
* The rotation of the node is stored in `param2`.
* Allows node to be rotated horizontally, 4 rotations in total
* Can be made by using `minetest.dir_to_fourdir()`.
* Chests and furnaces can be rotated that way, but not flipped
* Values range 0 - 3
* 4dir modulo 4 = rotation
* Otherwise, behavior is identical to facedir
* `paramtype2 = "leveled"`
* Only valid for "nodebox" with 'type = "leveled"', and "plantlike_rooted".
* Leveled nodebox:
* The level of the top face of the nodebox is stored in `param2`.
* The other faces are defined by 'fixed = {}' like 'type = "fixed"'
nodeboxes.
* The nodebox height is (`param2` / 64) nodes.
* The maximum accepted value of `param2` is 127.
* Rooted plantlike:
* The height of the 'plantlike' section is stored in `param2`.
* The height is (`param2` / 16) nodes.
* `paramtype2 = "degrotate"`
* Valid for `plantlike` and `mesh` drawtypes. The rotation of the node is
stored in `param2`.
* Values range 0–239. The value stored in `param2` is multiplied by 1.5 to
get the actual rotation in degrees of the node.
* `paramtype2 = "meshoptions"`
* Only valid for "plantlike" drawtype. `param2` encodes the shape and
optional modifiers of the "plant". `param2` is a bitfield.
* Bits 0 to 2 select the shape.
Use only one of the values below:
* 0 = an "x" shaped plant (ordinary plant)
* 1 = a "+" shaped plant (just rotated 45 degrees)
* 2 = a "*" shaped plant with 3 faces instead of 2
* 3 = a "#" shaped plant with 4 faces instead of 2
* 4 = a "#" shaped plant with 4 faces that lean outwards
* 5-7 are unused and reserved for future meshes.
* Bits 3 to 7 are used to enable any number of optional modifiers.
Just add the corresponding value(s) below to `param2`:
* 8 - Makes the plant slightly vary placement horizontally
* 16 - Makes the plant mesh 1.4x larger
* 32 - Moves each face randomly a small bit down (1/8 max)
* values 64 and 128 (bits 6-7) are reserved for future use.
* Example: `param2 = 0` selects a normal "x" shaped plant
* Example: `param2 = 17` selects a "+" shaped plant, 1.4x larger (1+16)
* `paramtype2 = "color"`
* `param2` tells which color is picked from the palette.
The palette should have 256 pixels.
* `paramtype2 = "colorfacedir"`
* Same as `facedir`, but with colors.
* The first three bits of `param2` tells which color is picked from the
palette. The palette should have 8 pixels.
* `paramtype2 = "color4dir"`
* Same as `facedir`, but with colors.
* The first six bits of `param2` tells which color is picked from the
palette. The palette should have 64 pixels.
* `paramtype2 = "colorwallmounted"`
* Same as `wallmounted`, but with colors.
* The first five bits of `param2` tells which color is picked from the
palette. The palette should have 32 pixels.
* `paramtype2 = "glasslikeliquidlevel"`
* Only valid for "glasslike_framed" or "glasslike_framed_optional"
drawtypes. "glasslike_framed_optional" nodes are only affected if the
"Connected Glass" setting is enabled.
* Bits 0-5 define 64 levels of internal liquid, 0 being empty and 63 being
full.
* Bits 6 and 7 modify the appearance of the frame and node faces. One or
both of these values may be added to `param2`:
* 64 - Makes the node not connect with neighbors above or below it.
* 128 - Makes the node not connect with neighbors to its sides.
* Liquid texture is defined using `special_tiles = {"modname_tilename.png"}`
* `paramtype2 = "colordegrotate"`
* Same as `degrotate`, but with colors.
* The first (most-significant) three bits of `param2` tells which color
is picked from the palette. The palette should have 8 pixels.
* Remaining 5 bits store rotation in range 0–23 (i.e. in 15° steps)
* `paramtype2 = "none"`
* `param2` will not be used by the engine and can be used to store
an arbitrary value
Node drawtypes
--------------
* `normal`
* A node-sized cube.
* `airlike`
* Invisible, uses no texture.
* `liquid`
* The cubic source node for a liquid.
* Faces bordering to the same node are never rendered.
* Connects to node specified in `liquid_alternative_flowing`.
* You *must* set `liquid_alternative_source` to the node's own name.
* Use `backface_culling = false` for the tiles you want to make
visible when inside the node.
* `flowingliquid`
* The flowing version of a liquid, appears with various heights and slopes.
* Faces bordering to the same node are never rendered.
* Connects to node specified in `liquid_alternative_source`.
* You *must* set `liquid_alternative_flowing` to the node's own name.
* Node textures are defined with `special_tiles` where the first tile
is for the top and bottom faces and the second tile is for the side
faces.
* `tiles` is used for the item/inventory/wield image rendering.
* Use `backface_culling = false` for the special tiles you want to make
visible when inside the node
* `glasslike`
* Often used for partially-transparent nodes.
* Only external sides of textures are visible.
* `glasslike_framed`
* All face-connected nodes are drawn as one volume within a surrounding
frame.
* The frame appearance is generated from the edges of the first texture
specified in `tiles`. The width of the edges used are 1/16th of texture
size: 1 pixel for 16x16, 2 pixels for 32x32 etc.
* The glass 'shine' (or other desired detail) on each node face is supplied
by the second texture specified in `tiles`.
* `glasslike_framed_optional`
* This switches between the above 2 drawtypes according to the menu setting
'Connected Glass'.
* `allfaces`
* Often used for partially-transparent nodes.
* External and internal sides of textures are visible.
* `allfaces_optional`
* Often used for leaves nodes.
* This switches between `normal`, `glasslike` and `allfaces` according to
the menu setting: Opaque Leaves / Simple Leaves / Fancy Leaves.
* With 'Simple Leaves' selected, the texture specified in `special_tiles`
is used instead, if present. This allows a visually thicker texture to be
used to compensate for how `glasslike` reduces visual thickness.
* `torchlike`
* A single vertical texture.
* If `paramtype2="[color]wallmounted"`:
* If placed on top of a node, uses the first texture specified in `tiles`.
* If placed against the underside of a node, uses the second texture
specified in `tiles`.
* If placed on the side of a node, uses the third texture specified in
`tiles` and is perpendicular to that node.
* If `paramtype2="none"`:
* Will be rendered as if placed on top of a node (see
above) and only the first texture is used.
* `signlike`
* A single texture parallel to, and mounted against, the top, underside or
side of a node.
* If `paramtype2="[color]wallmounted"`, it rotates according to `param2`
* If `paramtype2="none"`, it will always be on the floor.
* `plantlike`
* Two vertical and diagonal textures at right-angles to each other.
* See `paramtype2 = "meshoptions"` above for other options.
* `firelike`
* When above a flat surface, appears as 6 textures, the central 2 as
`plantlike` plus 4 more surrounding those.
* If not above a surface the central 2 do not appear, but the texture
appears against the faces of surrounding nodes if they are present.
* `fencelike`
* A 3D model suitable for a wooden fence.
* One placed node appears as a single vertical post.
* Adjacently-placed nodes cause horizontal bars to appear between them.
* `raillike`
* Often used for tracks for mining carts.
* Requires 4 textures to be specified in `tiles`, in order: Straight,
curved, t-junction, crossing.
* Each placed node automatically switches to a suitable rotated texture
determined by the adjacent `raillike` nodes, in order to create a
continuous track network.
* Becomes a sloping node if placed against stepped nodes.
* `nodebox`
* Often used for stairs and slabs.
* Allows defining nodes consisting of an arbitrary number of boxes.
* See [Node boxes] below for more information.
* `mesh`
* Uses models for nodes.
* Tiles should hold model materials textures.
* Only static meshes are implemented.
* For supported model formats see Irrlicht engine documentation.
* `plantlike_rooted`
* Enables underwater `plantlike` without air bubbles around the nodes.
* Consists of a base cube at the co-ordinates of the node plus a
`plantlike` extension above
* If `paramtype2="leveled", the `plantlike` extension has a height
of `param2 / 16` nodes, otherwise it's the height of 1 node
* If `paramtype2="wallmounted"`, the `plantlike` extension
will be at one of the corresponding 6 sides of the base cube.
Also, the base cube rotates like a `normal` cube would
* The `plantlike` extension visually passes through any nodes above the
base cube without affecting them.
* The base cube texture tiles are defined as normal, the `plantlike`
extension uses the defined special tile, for example:
`special_tiles = {{name = "default_papyrus.png"}},`
Node boxes
----------
{
-- A normal cube; the default in most things
type = "regular"
}
{
-- A fixed box (or boxes) (facedir param2 is used, if applicable)
type = "fixed",
fixed = box OR {box1, box2, ...}
}
{
-- A variable height box (or boxes) with the top face position defined
-- by the node parameter 'leveled = ', or if 'paramtype2 == "leveled"'
-- by param2.
-- Other faces are defined by 'fixed = {}' as with 'type = "fixed"'.
type = "leveled",
fixed = box OR {box1, box2, ...}
}
{
-- A box like the selection box for torches
-- (wallmounted param2 is used, if applicable)
type = "wallmounted",
wall_top = box,
wall_bottom = box,
wall_side = box
}
{
-- A node that has optional boxes depending on neighboring nodes'
-- presence and type. See also `connects_to`.
type = "connected",
fixed = box OR {box1, box2, ...}
connect_top = box OR {box1, box2, ...}
connect_bottom = box OR {box1, box2, ...}
connect_front = box OR {box1, box2, ...}
connect_left = box OR {box1, box2, ...}
connect_back = box OR {box1, box2, ...}
connect_right = box OR {box1, box2, ...}
-- The following `disconnected_*` boxes are the opposites of the
-- `connect_*` ones above, i.e. when a node has no suitable neighbor
-- on the respective side, the corresponding disconnected box is drawn.
disconnected_top = box OR {box1, box2, ...}
disconnected_bottom = box OR {box1, box2, ...}
disconnected_front = box OR {box1, box2, ...}
disconnected_left = box OR {box1, box2, ...}
disconnected_back = box OR {box1, box2, ...}
disconnected_right = box OR {box1, box2, ...}
disconnected = box OR {box1, box2, ...} -- when there is *no* neighbor
disconnected_sides = box OR {box1, box2, ...} -- when there are *no*
-- neighbors to the sides
}
To avoid collision issues, keep each value within the range of +/- 1.45.
This also applies to leveled nodeboxes, where the final height shall not
exceed this soft limit.
Coordinates
-----------
Occasionally the API uses 'blockpos' which refers to mapblock coordinates that
specify a particular mapblock.
For example blockpos (0,0,0) specifies the mapblock that extends from
node position (0,0,0) to node position (15,15,15).
To calculate the blockpos of the mapblock that contains the node at 'nodepos',
for each axis:
* blockpos = math.floor(nodepos / 16)
* Minimum:
nodepos = blockpos * 16
* Maximum:
nodepos = blockpos * 16 + 15
HUD
===
The `name` field is not yet used, but should contain a description of what the
HUD element represents.
The `alignment` field specifies how the item will be aligned. It is a table
where `x` and `y` range from `-1` to `1`, with `0` being central. `-1` is
moved to the left/up, and `1` is to the right/down. Fractional values can be
used.
The `offset` field specifies a pixel offset from the position. Contrary to
position, the offset is not scaled to screen size. This allows for some
precisely positioned items in the HUD.
**Note**: `offset` _will_ adapt to screen DPI as well as user defined scaling
factor!
The `z_index` field specifies the order of HUD elements from back to front.
Lower z-index elements are displayed behind higher z-index elements. Elements
with same z-index are displayed in an arbitrary order. Default 0.
Supports negative values. By convention, the following values are recommended:
Below are the specific uses for fields in each type; fields not listed for that
type are ignored.
### `image`
* `scale`: The scale of the image, with 1 being the original texture size.
Only the X coordinate scale is used (positive values).
Negative values represent that percentage of the screen it
should take; e.g. `x=-100` means 100% (width).
* `text`: The name of the texture that is displayed.
* `alignment`: The alignment of the image.
* `offset`: offset in pixels from position.
### `text`
### `statbar`
### `inventory`
### `image_waypoint`
Same as `image`, but does not accept a `position`; the position is instead
determined by `world_pos`, the world position of the waypoint.
* `scale`: The scale of the image, with 1 being the original texture size.
Only the X coordinate scale is used (positive values).
Negative values represent that percentage of the screen it
should take; e.g. `x=-100` means 100% (width).
* `text`: The name of the texture that is displayed.
* `alignment`: The alignment of the image.
* `world_pos`: World position of the waypoint.
* `offset`: offset in pixels from position.
### `compass`
### `minimap`
vector.new(x, y, z)
`pointed_thing`
---------------
* `{type="nothing"}`
* `{type="node", under=pos, above=pos}`
* Indicates a pointed node selection box.
* `under` refers to the node position behind the pointed face.
* `above` refers to the node position in front of the pointed face.
* `{type="object", ref=ObjectRef}`
Flags using the standardized flag specifier format can be specified in either
of two ways, by string or table.
In addition to the standard string flag format, the schematic flags field can
also be a table of flag names to boolean values representing whether or not the
flag is set. Additionally, if a field with the flag name prefixed with `"no"`
is present, mapped to a boolean of any value, the specified flag is unset.
which is equivalent to
or even
"place_center_x, place_center_z"
Items
=====
Items are things that can be held by players, dropped in the map and
stored in inventories.
Items come in the form of item stacks, which are collections of equal
items that occupy a single inventory slot.
Item types
----------
Item formats
------------
Items and item stacks can exist in three formats: Serializes, table format
and `ItemStack`.
### Serialized
Syntax:
Examples:
* `"default:apple"`: 1 apple
* `"default:dirt 5"`: 5 dirt
* `"default:pick_stone"`: a new stone pickaxe
* `"default:pick_wood 1 21323"`: a wooden pickaxe, ca. 1/3 worn out
* `[[default:pick_wood 1 21323 "\u0001description\u0002My worn out pick\u0003"]]`:
* a wooden pickaxe from the `default` mod,
* amount must be 1 (pickaxe is a tool), ca. 1/3 worn out (it's a tool),
* with the `description` field set to `"My worn out pick"` in its metadata
* `[[default:dirt 5 0 "\u0001description\u0002Special dirt\u0003"]]`:
* analogous to the above example
* note how the wear is set to `0` as dirt is not a tool
You should ideally use the `ItemStack` format to build complex item strings
(especially if they use item metadata)
without relying on the serialization format. Example:
5 dirt nodes:
An apple:
### `ItemStack`
A native C++ format with many helper methods. Useful for converting
between formats. See the [Class reference] section for details.
Groups
======
Usage
-----
Groups are stored in a table, having the group names with keys and the
group ratings as values. Group ratings are integer values within the
range [-32767, 32767]. For example:
-- Default dirt
groups = {crumbly=3, soil=1}
When not defined, the rating of a group defaults to `0`. Thus when you
read groups, you must interpret `nil` and `0` as the same value, `0`.
You can read the rating of a group for an item or a node by using
minetest.get_item_group(itemname, groupname)
Groups of items
---------------
Groups of nodes
---------------
In addition to the general item things, groups are used to define whether
a node is destroyable and how long it takes to destroy by a tool.
Groups of entities
------------------
For entities, groups are, as of now, used only for calculating damage.
The rating is the percentage of damage caused by items with this damage group.
See [Entity damage mechanism].
Groups in tool capabilities define which groups of nodes and entities they
are effective towards.
"group:<group_name>"
For example, `"group:meat"` will accept any item in the `meat` group.
"group:<group_name_1>,<group_name_2>,(...),<group_name_n>"
An example recipe: Craft a raw meat soup from any meat, any water and any bowl:
{
output = "food:meat_soup_raw",
recipe = {
{"group:meat"},
{"group:water"},
{"group:bowl"},
},
}
Another example: Craft red wool from white wool and red dye
(here, "red dye" is defined as any item which is member of
*both* the groups `dye` and `basecolor_red`).
{
type = "shapeless",
output = "wool:red",
recipe = {"wool:white", "group:dye,basecolor_red"},
}
Special groups
--------------
The asterisk `(*)` after a group name describes that there is no engine
functionality bound to it, and implementation is left up as a suggestion
to games.
* `immortal`: Skips all damage and breath handling for an object. This group
will also hide the integrated HUD status bars for players. It is
automatically set to all players when damage is disabled on the server and
cannot be reset (subject to change).
* `fall_damage_add_percent`: Modifies the fall damage suffered by players
when they hit the ground. It is analog to the node group with the same
name. See the node group above for the exact calculation.
* `punch_operable`: For entities; disables the regular damage mechanism for
players punching it by hand or a non-tool item, so that it can do something
else than take damage.
Item groups are often used for defining, well, _groups of items_.
* `meat`: any meat-kind of a thing (rating might define the size or healing
ability or be irrelevant -- it is not defined as of yet)
* `eatable`: anything that can be eaten. Rating might define HP gain in half
hearts.
* `flammable`: can be set on fire. Rating might define the intensity of the
fire, affecting e.g. the speed of the spreading of an open fire.
* `wool`: any wool (any origin, any color)
* `metal`: any metal
* `weapon`: any weapon
* `heavy`: anything considerably heavy
The `level` group is used to limit the toughness of nodes an item capable
of digging can dig and to scale the digging times / damage to a greater extent.
**Please do understand this**, otherwise you cannot use the system to it's
full potential.
Tool Capabilities
=================
Tool capabilities are available for all items, not just tools.
But only tools can receive wear from digging and punching.
When used as a weapon, the item will do full damage if this time is spent
between punches. If e.g. half the time is spent, the item will do half
damage.
Suggests the maximum level of node, when dug with the item, that will drop
its useful item. (e.g. iron ore to drop a lump of iron).
This value is not used in the engine; it is the responsibility of the game/mod
code to implement this.
### Uses `uses` (tools only)
Determines how many uses the tool has when it is used for digging a node,
of this group, of the maximum level. The maximum supported number of
uses is 65535. The special number 0 is used for infinite uses.
For lower leveled nodes, the use count is multiplied by `3^leveldiff`.
`leveldiff` is the difference of the tool's `maxlevel` `groupcaps` and the
node's `level` group. The node cannot be dug if `leveldiff` is less than zero.
Tells what is the maximum level of a node of this group that the item will
be able to dig.
List of digging times for different ratings of the group, for nodes of the
maximum level.
Determines how many uses (before breaking) the tool has when dealing damage
to an object, when the full punch interval (see above) was always
waited out fully.
tool_capabilities = {
groupcaps={
crumbly={maxlevel=2, uses=20, times={[1]=1.60, [2]=1.20, [3]=0.80}}
},
}
This makes the item capable of digging nodes that fulfill both of these:
level diff: 2 1 0 -1 -2
-> 0 - - - - -
1 180 60 20 - -
2 180 60 20 - -
3 180 60 20 - -
**Notes**:
Damage calculation:
damage = 0
foreach group in cap.damage_groups:
damage += cap.damage_groups[group]
* limit(actual_interval / cap.full_punch_interval, 0.0, 1.0)
* (object.armor_groups[group] / 100.0)
-- Where object.armor_groups[group] is 0 for inexistent values
return damage
This should never be called directly, because damage is usually not handled by
the entity itself.
* `puncher` is the object performing the punch. Can be `nil`. Should never be
accessed unless absolutely required, to encourage interoperability.
* `time_from_last_punch` is time from last punch (by `puncher`) or `nil`.
* `tool_capabilities` can be `nil`.
* `direction` is a unit vector, pointing from the source of the punch to
the punched object.
* `damage` damage that will be done to entity
Return value of this function will determine if damage is done by this function
(retval true) or shall be done by engine (retval false)
Metadata
========
Node Metadata
-------------
The instance of a node in the world normally only contains the three values
mentioned in [Nodes]. However, it is possible to insert extra data into a node.
It is called "node metadata"; See `NodeMetaRef`.
* A key-value store
* An inventory
Example:
Item Metadata
-------------
Example:
stack:get_meta():set_string("short_description", "Short")
print(stack:get_description()) --> Custom description\nAnother line
print(stack:get_short_description()) --> Short
print(ItemStack("mod:item_with_no_desc"):get_description()) -->
mod:item_with_no_desc
Formspec
========
Spaces and newlines can be inserted between the blocks, as is used in the
examples.
Position and size units are inventory slots unless the new coordinate system
is enabled. `X` and `Y` position the formspec element relative to the top left
of the menu or container. `W` and `H` are its width and height values.
If the new system is enabled, all elements have unified coordinates for all
elements with no padding or spacing in between. This is highly recommended
for new forms. See `real_coordinates[<bool>]` and `Migrating to Real
Coordinates`.
When displaying text which can contain formspec code, e.g. text set by a player,
use `minetest.formspec_escape`.
For colored text you can use `minetest.colorize`.
Since formspec version 3, elements drawn in the order they are defined. All
background elements are drawn before all other elements.
**WARNING**: do _not_ use an element name starting with `key_`; those names are
reserved to pass key press events to formspec!
**WARNING**: Minetest allows you to add elements to every single formspec instance
using `player:set_formspec_prepend()`, which may be the reason backgrounds are
appearing when you don't expect them to, or why things are styled differently
to normal. See [`no_prepend[]`] and [Styling Formspecs].
Examples
--------
### Chest
size[8,9]
list[context;main;0,0;8,4;]
list[current_player;main;0,5;8,4;]
### Furnace
size[8,9]
list[context;fuel;2,3;1,1;]
list[context;src;2,1;1,1;]
list[context;dst;5,1;2,2;]
list[current_player;main;0,5;8,4;]
size[8,7.5]
image[1,0.6;1,2;player.png]
list[current_player;main;0,3.5;8,4;]
list[current_player;craft;3,0;3,3;]
list[current_player;craftpreview;7,1;1,1;]
Version History
---------------
Elements
--------
### `formspec_version[<version>]`
### `size[<W>,<H>,<fixed_size>]`
### `position[<X>,<Y>]`
### `anchor[<X>,<Y>]`
* Must be used after both `size` and `position` (if present) elements.
* Defines the location of the anchor point within the formspec.
* For X and Y, 0.0 and 1.0 represent opposite edges of the formspec,
for example:
* [0.0, 1.0] sets the anchor to the bottom left corner of the formspec.
* [1.0, 0.0] sets the anchor to the top right of the formspec.
* Defaults to the center of the formspec [0.5, 0.5].
### `padding[<X>,<Y>]`
* Must be used after the `size`, `position`, and `anchor` elements (if present).
* Defines how much space is padded around the formspec if the formspec tries to
increase past the size of the screen and coordinates have to be shrunk.
* For X and Y, 0.0 represents no padding (the formspec can touch the edge of the
screen), and 0.5 represents half the screen (which forces the coordinate size
to 0). If negative, the formspec can extend off the edge of the screen.
* Defaults to [0.05, 0.05].
### `no_prepend[]`
* Must be used after the `size`, `position`, `anchor`, and `padding` elements
(if present).
* Disables player:set_formspec_prepend() from applying to this formspec.
### `real_coordinates[<bool>]`
### `container[<X>,<Y>]`
### `container_end[]`
### `scroll_container_end[]`
### `listring[]`
### `listcolors[<slot_bg_normal>;<slot_bg_hover>]`
### `listcolors[<slot_bg_normal>;<slot_bg_hover>;<slot_border>]`
###
`listcolors[<slot_bg_normal>;<slot_bg_hover>;<slot_border>;<tooltip_bgcolor>;<toolt
ip_fontcolor>]`
### `tooltip[<gui_element_name>;<tooltip_text>;<bgcolor>;<fontcolor>]`
### `tooltip[<X>,<Y>;<W>,<H>;<tooltip_text>;<bgcolor>;<fontcolor>]`
* Adds tooltip for an area. Other tooltips will take priority when present.
* `bgcolor` tooltip background color as `ColorString` (optional)
* `fontcolor` tooltip font color as `ColorString` (optional)
* Show an image.
* `middle` (optional): Makes the image render in 9-sliced mode and defines the
middle rect.
* Requires formspec version >= 6.
* See `background9[]` documentation for more information.
### `model[<X>,<Y>;<W>,<H>;<name>;<mesh>;<textures>;<rotation
X,Y>;<continuous>;<mouse control>;<frame loop range>;<animation speed>]`
### `bgcolor[<bgcolor>;<fullscreen>;<fbgcolor>]`
### `pwdfield[<X>,<Y>;<W>,<H>;<name>;<label>]`
* Textual password style field; will be sent to server when a button is clicked
* When enter is pressed in field, fields.key_enter_field will be sent with the
name of this field.
* With the old coordinate system, fields are a set height, but will be vertically
centered on `H`. With the new coordinate system, `H` will modify the height.
* `name` is the name of the field as returned in fields to `on_receive_fields`
* `label`, if not blank, will be text printed on the top left above the field
* See `field_close_on_enter` to stop enter closing the formspec
### `field[<X>,<Y>;<W>,<H>;<name>;<label>;<default>]`
### `field[<name>;<label>;<default>]`
### `field_close_on_enter[<name>;<close_on_enter>]`
### `textarea[<X>,<Y>;<W>,<H>;<name>;<label>;<default>]`
### `label[<X>,<Y>;<label>]`
### `hypertext[<X>,<Y>;<W>,<H>;<name>;<text>]`
* Displays a static formatted text with hyperlinks.
* **Note**: This element is currently unstable and subject to change.
* `x`, `y`, `w` and `h` work as per field
* `name` is the name of the field as returned in fields to `on_receive_fields` in
case of action in text.
* `text` is the formatted text using `Markup Language` described below.
### `vertlabel[<X>,<Y>;<label>]`
* Textual label drawn vertically
* `label` is the text on the label
* **Note**: If the new coordinate system is enabled, vertlabels are
positioned from the center of the text, not the left.
### `button[<X>,<Y>;<W>,<H>;<name>;<label>]`
### `image_button[<X>,<Y>;<W>,<H>;<texture
name>;<name>;<label>;<noclip>;<drawborder>;<pressed texture name>]`
### `button_exit[<X>,<Y>;<W>,<H>;<name>;<label>]`
* When clicked, fields will be sent and the form will quit.
* Same as `button` in all other respects.
* When clicked, fields will be sent and the form will quit.
* Same as `image_button` in all other respects.
### `box[<X>,<Y>;<W>,<H>;<color>]`
### `checkbox[<X>,<Y>;<name>;<label>;<selected>]`
* Show a checkbox
* `name` fieldname data is transferred to Lua
* `label` to be shown left of checkbox
* `selected` (optional): `true`/`false`
* **Note**: If the new coordinate system is enabled, checkboxes are
positioned from the center of the checkbox, not the top.
### `scrollbar[<X>,<Y>;<W>,<H>;<orientation>;<name>;<value>]`
### `scrollbaroptions[opt1;opt2;...]`
* Sets options for all following `scrollbar[]` elements
* `min=<int>`
* Sets scrollbar minimum value, defaults to `0`.
* `max=<int>`
* Sets scrollbar maximum value, defaults to `1000`.
If the max is equal to the min, the scrollbar will be disabled.
* `smallstep=<int>`
* Sets scrollbar step value when the arrows are clicked or the mouse wheel is
scrolled.
* If this is set to a negative number, the value will be reset to `10`.
* `largestep=<int>`
* Sets scrollbar step value used by page up and page down.
* If this is set to a negative number, the value will be reset to `100`.
* `thumbsize=<int>`
* Sets size of the thumb on the scrollbar. Size is calculated in the number of
units the thumb spans out of the range of the scrollbar values.
* Example: If a scrollbar has a `min` of 1 and a `max` of 100, a thumbsize of
10
would span a tenth of the scrollbar space.
* If this is set to zero or less, the value will be reset to `1`.
* `arrows=<show/hide/default>`
* Whether to show the arrow buttons on the scrollbar. `default` hides the
arrows
when the scrollbar gets too small, but shows them otherwise.
### `set_focus[<name>;<force>]`
* Sets the focus to the element with the same `name` parameter.
* **Note**: This element must be placed before the element it focuses.
* `force` (optional, default `false`): By default, focus is not applied for
re-sent formspecs with the same name so that player-set focus is kept.
`true` sets the focus to the specified element for every sent formspec.
* The following elements have the ability to be focused:
* checkbox
* button
* button_exit
* image_button
* image_button_exit
* item_image_button
* table
* textlist
* dropdown
* field
* pwdfield
* textarea
* scrollbar
In the old system, positions included padding and spacing. Padding is a gap between
the formspec window edges and content, and spacing is the gaps between items. For
example, two `1x1` elements at `0,0` and `1,1` would have a spacing of `5/4`
between them,
and a padding of `3/8` from the formspec edge. It may be easiest to recreate old
layouts
in the new coordinate system from scratch.
To recreate an old layout with padding, you'll need to pass the positions and sizes
through the following formula to re-introduce padding:
```
pos = (oldpos + 1)*spacing + padding
where
padding = 3/8
spacing = 5/4
```
```
size = (oldsize-1)*spacing + padding*2 + 1
```
A few elements had random offsets in the old system. Here is a table which shows
these
offsets when migrating:
Styling Formspecs
-----------------
property_name=property_value
For example:
style_type[button;bgcolor=#006699]
style[world_delete;bgcolor=red;textcolor=yellow]
button[4,3.95;2.6,1;world_delete;Delete]
world_delete,world_create,world_configure
button,image_button
world_delete:hovered+pressed
button:pressed
States allow you to apply styles in response to changes in the element, instead of
applying at all times.
Setting a property to nothing will reset it to the default value. For example:
style_type[button;bgimg=button.png;bgimg_pressed=button_pressed.png;border=false]
style[btn_exit;bgimg=;bgimg_pressed=;border=;bgcolor=red]
* animated_image
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* box
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* Defaults to false in formspec_version version 3 or higher
* **Note**: `colors`, `bordercolors`, and `borderwidths` accept multiple input
types:
* Single value (e.g. `#FF0`): All corners/borders.
* Two values (e.g. `red,#FFAAFF`): top-left and bottom-right,top-right and
bottom-left/
top and bottom,left and right.
* Four values (e.g. `blue,#A0F,green,#FFFA`): top-left/top and rotates
clockwise.
* These work similarly to CSS borders.
* colors - `ColorString`. Sets the color(s) of the box corners. Default
`black`.
* bordercolors - `ColorString`. Sets the color(s) of the borders. Default
`black`.
* borderwidths - Integer. Sets the width(s) of the borders in pixels. If the
width is
negative, the border will extend inside the box, whereas positive extends
outside
the box. A width of zero results in no border; this is default.
* button, button_exit, image_button, item_image_button
* alpha - boolean, whether to draw alpha in bgimg. Default true.
* bgcolor - color, sets button tint.
* bgcolor_hovered - color when hovered. Defaults to a lighter bgcolor when not
provided.
* This is deprecated, use states instead.
* bgcolor_pressed - color when pressed. Defaults to a darker bgcolor when not
provided.
* This is deprecated, use states instead.
* bgimg - standard background image. Defaults to none.
* bgimg_hovered - background image when hovered. Defaults to bgimg when not
provided.
* This is deprecated, use states instead.
* bgimg_middle - Makes the bgimg textures render in 9-sliced mode and defines
the middle rect.
See background9[] documentation for more details. This
property also pads the
button's content when set.
* bgimg_pressed - background image when pressed. Defaults to bgimg when not
provided.
* This is deprecated, use states instead.
* font - Sets font type. This is a comma separated list of options. Valid
options:
* Main font type options. These cannot be combined with each other:
* `normal`: Default font
* `mono`: Monospaced font
* Font modification options. If used without a main font type, `normal` is
used:
* `bold`: Makes font bold.
* `italic`: Makes font italic.
Default `normal`.
* font_size - Sets font size. Default is user-set. Can have multiple values:
* `<number>`: Sets absolute font size to `number`.
* `+<number>`/`-<number>`: Offsets default font size by `number` points.
* `*<number>`: Multiplies default font size by `number`, similar to CSS `em`.
* border - boolean, draw border. Set to false to hide the bevelled button pane.
Default true.
* content_offset - 2d vector, shifts the position of the button's content
without resizing it.
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* padding - rect, adds space between the edges of the button and the content.
This value is
relative to bgimg_middle.
* sound - a sound to be played when triggered.
* textcolor - color, default white.
* checkbox
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* sound - a sound to be played when triggered.
* dropdown
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* sound - a sound to be played when the entry is changed.
* field, pwdfield, textarea
* border - set to false to hide the textbox background and border. Default
true.
* font - Sets font type. See button `font` property for more information.
* font_size - Sets font size. See button `font_size` property for more
information.
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* textcolor - color. Default white.
* model
* bgcolor - color, sets background color.
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* Default to false in formspec_version version 3 or higher
* image
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* Default to false in formspec_version version 3 or higher
* item_image
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
Default to false.
* label, vertlabel
* font - Sets font type. See button `font` property for more information.
* font_size - Sets font size. See button `font_size` property for more
information.
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* list
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* size - 2d vector, sets the size of inventory slots in coordinates.
* spacing - 2d vector, sets the space between inventory slots in coordinates.
* image_button (additional properties)
* fgimg - standard image. Defaults to none.
* fgimg_hovered - image when hovered. Defaults to fgimg when not provided.
* This is deprecated, use states instead.
* fgimg_pressed - image when pressed. Defaults to fgimg when not provided.
* This is deprecated, use states instead.
* fgimg_middle - Makes the fgimg textures render in 9-sliced mode and defines
the middle rect.
See background9[] documentation for more details.
* NOTE: The parameters of any given image_button will take precedence over
fgimg/fgimg_pressed
* sound - a sound to be played when triggered.
* scrollbar
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* tabheader
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* sound - a sound to be played when a different tab is selected.
* textcolor - color. Default white.
* table, textlist
* font - Sets font type. See button `font` property for more information.
* font_size - Sets font size. See button `font_size` property for more
information.
* noclip - boolean, set to true to allow the element to exceed formspec bounds.
* *all elements*
* default - Equivalent to providing no states
* button, button_exit, image_button, item_image_button
* hovered - Active when the mouse is hovering over the element
* pressed - Active when the button is pressed
Markup Language
---------------
Markup language used in `hypertext[]` elements uses tags that look like HTML tags.
The markup language is currently unstable and subject to change. Use with caution.
Some tags can enclose text, they open with `<tagname>` and close with `</tagname>`.
Tags can have attributes, in that case, attributes are in the opening tag in
form of a key/value separated with equal signs. Attribute values should not be
quoted.
If you want to insert a literal greater-than sign or a backslash into the text,
you must escape it by preceding it with a backslash.
These are the technically basic tags but see below for usual tags. Base tags are:
This tag needs to be placed only once as it changes the global settings of the
text. Anyway, if several tags are placed, each changed will be made in the order
tags appear.
Defines or redefines tag style. This can be used to define new tags.
* `name`: Name of the tag to define or change.
* `color`: Text color. Given color is a `colorspec`.
* `hovercolor`: Text color when element hovered (only for `action` tags). Given
color is a `colorspec`.
* `size`: Text size.
* `font`: Text font (`mono` or `normal`).
Following tags are the usual tags for text layout. They are defined by default.
Other tags can be added using `<tag ...>` tag.
`<action name=...>...</action>`
When clicked, the formspec is send to the server. The value of the text field
sent to `on_player_receive_fields` will be "action:" concatenated to the action
name.
Inventory
=========
Inventory locations
-------------------
Colors
======
`ColorString`
-------------
`ColorSpec`
-----------
* table form: Each element ranging from 0..255 (a, if absent, defaults to 255):
* `colorspec = {a=255, r=0, g=255, b=0}`
* numerical form: The raw integer value of an ARGB8 quad:
* `colorspec = 0xFF00FF00`
* string form: A ColorString (defined above):
* `colorspec = "green"`
Escape sequences
================
Most text can contain escape sequences, that can for example color the text.
There are a few exceptions: tab headers, dropdowns and vertical labels can't.
The following functions provide escape sequences:
* `minetest.get_color_escape_sequence(color)`:
* `color` is a ColorString
* The escape sequence sets the text color to `color`
* `minetest.colorize(color, message)`:
* Equivalent to:
`minetest.get_color_escape_sequence(color) ..
message ..
minetest.get_color_escape_sequence("#ffffff")`
* `minetest.get_background_escape_sequence(color)`
* `color` is a ColorString
* The escape sequence sets the background of the whole text element to
`color`. Only defined for item descriptions and tooltips.
* `minetest.strip_foreground_colors(str)`
* Removes foreground colors added by `get_color_escape_sequence`.
* `minetest.strip_background_colors(str)`
* Removes background colors added by `get_background_escape_sequence`.
* `minetest.strip_colors(str)`
* Removes all color escape sequences.
Spatial Vectors
===============
Spatial vectors are used for various things, including, but not limited to:
* `(x, y, z)` (Used rarely, and only if it's clear that it's a vector.)
* `vector.new(x, y, z)`
* `{x=num, y=num, z=num}` (Even here you are still supposed to use `vector.new`.)
Compatibility notes
-------------------
Vectors used to be defined as tables of the form `{x = num, y = num, z = num}`.
Since Minetest 5.5.0, vectors additionally have a metatable to enable easier use.
Note: Those old-style vectors can still be found in old mod code. Hence, mod and
engine APIs still need to be able to cope with them in many places.
Manually constructed tables are deprecated and highly discouraged. This interface
should be used to ensure seamless compatibility between mods and the Minetest API.
This is especially important to callback function parameters and functions
overwritten
by mods.
Also, though not likely, the internal implementation of a vector might change in
the future.
In your own code, or if you define your own API, you can, of course, still use
other representations of vectors.
Vectors provided by API functions will provide an instance of this class if not
stated otherwise. Mods should adapt this for convenience reasons.
Vectors can be indexed with numbers and allow method and operator syntax.
Where `v` is a vector and `foo` stands for any function name, `v:foo(...)` does
the same as `vector.foo(v, ...)`, apart from deprecated functionality.
The metatable that is used for vectors can be accessed via `vector.metatable`.
Do not modify it!
* `vector.new([a[, b, c]])`:
* Returns a new vector `(a, b, c)`.
* Deprecated: `vector.new()` does the same as `vector.zero()` and
`vector.new(v)` does the same as `vector.copy(v)`
* `vector.zero()`:
* Returns a new vector `(0, 0, 0)`.
* `vector.copy(v)`:
* Returns a copy of the vector `v`.
* `vector.from_string(s[, init])`:
* Returns `v, np`, where `v` is a vector read from the given string `s` and
`np` is the next position in the string after the vector.
* Returns `nil` on failure.
* `s`: Has to begin with a substring of the form `"(x, y, z)"`. Additional
spaces, leaving away commas and adding an additional comma to the end
is allowed.
* `init`: If given starts looking for the vector at this string index.
* `vector.to_string(v)`:
* Returns a string of the form `"(x, y, z)"`.
* `tostring(v)` does the same.
* `vector.direction(p1, p2)`:
* Returns a vector of length 1 with direction `p1` to `p2`.
* If `p1` and `p2` are identical, returns `(0, 0, 0)`.
* `vector.distance(p1, p2)`:
* Returns zero or a positive number, the distance between `p1` and `p2`.
* `vector.length(v)`:
* Returns zero or a positive number, the length of vector `v`.
* `vector.normalize(v)`:
* Returns a vector of length 1 with direction of vector `v`.
* If `v` has zero length, returns `(0, 0, 0)`.
* `vector.floor(v)`:
* Returns a vector, each dimension rounded down.
* `vector.round(v)`:
* Returns a vector, each dimension rounded to nearest integer.
* At a multiple of 0.5, rounds away from zero.
* `vector.apply(v, func)`:
* Returns a vector where the function `func` has been applied to each
component.
* `vector.combine(v, w, func)`:
* Returns a vector where the function `func` has combined both components of
`v` and `w`
for each component
* `vector.equals(v1, v2)`:
* Returns a boolean, `true` if the vectors are identical.
* `vector.sort(v1, v2)`:
* Returns in order minp, maxp vectors of the cuboid defined by `v1`, `v2`.
* `vector.angle(v1, v2)`:
* Returns the angle between `v1` and `v2` in radians.
* `vector.dot(v1, v2)`:
* Returns the dot product of `v1` and `v2`.
* `vector.cross(v1, v2)`:
* Returns the cross product of `v1` and `v2`.
* `vector.offset(v, x, y, z)`:
* Returns the sum of the vectors `v` and `(x, y, z)`.
* `vector.check(v)`:
* Returns a boolean value indicating whether `v` is a real vector, eg. created
by a `vector.*` function.
* Returns `false` for anything else, including tables like `{x=3,y=1,z=4}`.
* `vector.add(v, x)`:
* Returns a vector.
* If `x` is a vector: Returns the sum of `v` and `x`.
* If `x` is a number: Adds `x` to each component of `v`.
* `vector.subtract(v, x)`:
* Returns a vector.
* If `x` is a vector: Returns the difference of `v` subtracted by `x`.
* If `x` is a number: Subtracts `x` from each component of `v`.
* `vector.multiply(v, s)`:
* Returns a scaled vector.
* Deprecated: If `s` is a vector: Returns the Schur product.
* `vector.divide(v, s)`:
* Returns a scaled vector.
* Deprecated: If `s` is a vector: Returns the Schur quotient.
Operators
---------
Rotation-related functions
--------------------------
For the following functions `a` is an angle in radians and `r` is a rotation
vector (`{x = <pitch>, y = <yaw>, z = <roll>}`) where pitch, yaw and roll are
angles in radians.
* `vector.rotate(v, r)`:
* Applies the rotation `r` to `v` and returns the result.
* `vector.rotate(vector.new(0, 0, 1), r)` and
`vector.rotate(vector.new(0, 1, 0), r)` return vectors pointing
forward and up relative to an entity's rotation `r`.
* `vector.rotate_around_axis(v1, v2, a)`:
* Returns `v1` rotated around axis `v2` by `a` radians according to
the right hand rule.
* `vector.dir_to_rotation(direction[, up])`:
* Returns a rotation vector for `direction` pointing forward using `up`
as the up vector.
* If `up` is omitted, the roll of the returned vector defaults to zero.
* Otherwise `direction` and `up` need to be vectors in a 90 degree angle to
each other.
Further helpers
---------------
There are more helper functions involving vectors, but they are listed elsewhere
because they only work on specific sorts of vectors or involve things that are not
vectors.
For example:
Helper functions
================
Translations
============
local S = minetest.get_translator(textdomain)
S(str, ...)
For instance, suppose we want to translate "@1 Wool" with "@1" being replaced
by the translation of "Red". We can do the following:
local S = minetest.get_translator()
S("@1 Wool", S("Red"))
This will be displayed as "Red Wool" on old clients and on clients that do
not have localization enabled. However, if we have for instance a translation
file named `wool.fr.tr` containing the following:
@1 Wool=Laine @1
Red=Rouge
Escapes
-------
Strings that need to be translated can contain several escapes, preceded by `@`.
On some specific cases, server translation could be useful. For example, filter
a list on labels and send results to client. A method is supplied to achieve
that:
IMPORTANT: This functionality should only be used for sorting, filtering or similar
purposes.
You do not need to use this to get translated strings to show up on the client.
Perlin noise
============
This combination results in noise varying very roughly between -2.0 and 2.0 and
with an average value of 0.0, so `scale` and `offset` are then used to multiply
and offset the noise variation.
Noise Parameters
----------------
### `offset`
After the multiplication by `scale` this is added to the result and is the final
step in creating the noise value.
Can be positive or negative.
### `scale`
Once all octaves have been combined, the result is multiplied by this.
Can be positive or negative.
### `spread`
For octave1, this is roughly the change of input value needed for a very large
variation in the noise value generated by octave1. It is almost like a
'wavelength' for the wavy noise variation.
Each additional octave has a 'wavelength' that is smaller than the previous
octave, to create finer detail. `spread` will therefore roughly be the typical
size of the largest structures in the final noise variation.
### `seed`
This is a whole number that determines the entire pattern of the noise
variation. Altering it enables different noise patterns to be created.
With other parameters equal, different seeds produce different noise patterns
and identical seeds produce identical noise patterns.
For this parameter you can randomly choose any whole number. Usually it is
preferable for this to be different from other seeds, but sometimes it is useful
to be able to create identical noise patterns.
In some noise APIs the world seed is added to the seed specified in noise
parameters. This is done to make the resulting noise pattern vary in different
worlds, and be 'world-specific'.
### `octaves`
Choose the number of octaves according to the `spread` and `lacunarity`, and the
size of the finest detail you require. For example:
if `spread` is 512 nodes, `lacunarity` is 2.0 and finest detail required is 16
nodes, octaves will be 6 because the 'wavelengths' of the octaves will be
512, 256, 128, 64, 32, 16 nodes.
Warning: If the 'wavelength' of any octave falls below 1 an error will occur.
### `persistence`
Each additional octave has an amplitude that is the amplitude of the previous
octave multiplied by `persistence`, to reduce the amplitude of finer details,
as is often helpful and natural to do so.
Since this controls the balance of fine detail to large-scale detail
`persistence` can be thought of as the 'roughness' of the noise.
### `lacunarity`
### `flags`
#### `defaults`
#### `eased`
#### `absvalue`
The absolute value of each octave's noise variation is used when combining the
octaves. The final perlin noise variation is created as follows:
np_terrain = {
offset = 0,
scale = 1,
spread = {x = 500, y = 500, z = 500},
seed = 571347,
octaves = 5,
persistence = 0.63,
lacunarity = 2.0,
flags = "defaults, absvalue",
}
Ores
====
Ore types
---------
### `scatter`
### `sheet`
Creates a sheet of ore in a blob shape according to the 2D perlin noise
described by `noise_params` and `noise_threshold`. This is essentially an
improved version of the so-called "stratus" ore seen in some unofficial mods.
The ore parameters `clust_scarcity` and `clust_num_ores` are ignored for this
ore type.
### `puff`
As with the `sheet` ore type, the size and shape of puffs are described by
`noise_params` and `noise_threshold` and are placed at random vertical
positions within the currently generated chunk.
The vertical top and bottom displacement of each puff are determined by the
noise parameters `np_puff_top` and `np_puff_bottom`, respectively.
### `blob`
### `vein`
noise_params = {
offset = 0,
scale = 3,
spread = {x=200, y=200, z=200},
seed = 5390,
octaves = 4,
persistence = 0.5,
lacunarity = 2.0,
flags = "eased",
},
noise_threshold = 1.6
**WARNING**: Use this ore type *very* sparingly since it is ~200x more
computationally expensive than any other ore.
### `stratum`
If the noise parameter `noise_params` is omitted the ore will occur from y_min
to y_max in a simple horizontal stratum.
Leaving out one or both noise parameters makes the ore generation less
intensive, useful when adding multiple strata.
`y_min` and `y_max` define the limits of the ore generation and for performance
reasons should be set as close together as possible but without clipping the
stratum's Y variation.
Ore attributes
--------------
### `puff_cliffs`
If set, puff ore generation will not taper down large differences in
displacement when approaching the edge of a puff. This flag has no effect for
ore types other than `puff`.
### `puff_additive_composition`
Decoration types
================
`simple`
--------
Creates a 1 times `H` times 1 column of a specified node (or a random node from
a list, if a decoration list is specified). Can specify a certain node it must
spawn next to, such as water or lava, for example. Can also generate a
decoration of random height between a specified lower and upper bound.
This type of decoration is intended for placement of grass, flowers, cacti,
papyri, waterlilies and so on.
`schematic`
-----------
Copies a box of `MapNodes` from a specified schematic file (or raw description).
Can specify a probability of a node randomly appearing when placed.
This decoration type is intended to be used for multi-node sized discrete
structures, such as trees, cave spikes, rocks, and so on.
Schematics
==========
Schematic specifier
--------------------
* A probability value of `0` or `1` means that node will never appear
(0% chance).
* A probability value of `254` or `255` means the node will always appear
(100% chance).
* If the probability value `p` is greater than `1`, then there is a
`(p / 256 * 100)` percent chance that node will appear when the schematic is
placed on the map.
Schematic attributes
--------------------
About VoxelManip
----------------
It is important to note that VoxelManip is designed for speed, and *not* ease
of use or flexibility. If your mod requires a map manipulation facility that
will handle 100% of all edge cases, or the use of high level node placement
features, perhaps `minetest.set_node()` is better suited for the job.
In addition, VoxelManip might not be faster, or could even be slower, for your
specific use case. VoxelManip is most effective when setting large areas of map
at once - for example, if only setting a 3x3x3 node area, a
`minetest.set_node()` loop may be more optimal. Always profile code using both
methods of map manipulation to determine which is most appropriate for your
usage.
Using VoxelManip
----------------
A VoxelManip object can be created any time using either:
`VoxelManip([p1, p2])`, or `minetest.get_voxel_manip([p1, p2])`.
If the optional position parameters are present for either of these routines,
the specified region will be pre-loaded into the VoxelManip object on creation.
Otherwise, the area of map you wish to manipulate must first be loaded into the
VoxelManip object using `VoxelManip:read_from_map()`.
Now that the VoxelManip object is populated with map data, your mod can fetch a
copy of this data using either of two methods. `VoxelManip:get_node_at()`,
which retrieves an individual node in a MapNode formatted table at the position
requested is the simplest method to use, but also the slowest.
Nodes in a VoxelManip object may also be read in bulk to a flat array table
using:
It is very important to understand that the tables returned by any of the above
three functions represent a snapshot of the VoxelManip's internal state at the
time of the call. This copy of the data will not magically update itself if
another function modifies the internal VoxelManip state.
Any functions that modify a VoxelManip's contents work on the VoxelManip's
internal state unless otherwise explicitly stated.
Once the bulk data has been edited to your liking, the internal VoxelManip
state can be set using:
The parameter to each of the above three functions can use any table at all in
the same flat array format as produced by `get_data()` etc. and is not required
to be a table retrieved from `get_data()`.
Once the internal VoxelManip state has been modified to your liking, the
changes can be committed back to the map by calling `VoxelManip:write_to_map()`
Let
`Nx = p2.X - p1.X + 1`,
`Ny = p2.Y - p1.Y + 1`, and
`Nz = p2.Z - p1.Z + 1`.
Then, for a loaded region of p1..p2, this array ranges from `1` up to and
including the value of the expression `Nx * Ny * Nz`.
Positions offset from p1 are present in the array with the format of:
[
(0, 0, 0), (1, 0, 0), (2, 0, 0), ... (Nx, 0, 0),
(0, 1, 0), (1, 1, 0), (2, 1, 0), ... (Nx, 1, 0),
...
(0, Ny, 0), (1, Ny, 0), (2, Ny, 0), ... (Nx, Ny, 0),
(0, 0, 1), (1, 0, 1), (2, 0, 1), ... (Nx, 0, 1),
...
(0, Ny, 2), (1, Ny, 2), (2, Ny, 2), ... (Nx, Ny, 2),
...
(0, Ny, Nz), (1, Ny, Nz), (2, Ny, Nz), ... (Nx, Ny, Nz)
]
and the array index for a position p contained completely in p1..p2 is:
The following builtin node types have their Content IDs defined as constants:
### Notes
* Attempting to read data from a VoxelManip object before map is read will
result in a zero-length array table for `VoxelManip:get_data()`, and an
"ignore" node at any position for `VoxelManip:get_node_at()`.
* If either a region of map has not yet been generated or is out-of-bounds of
the map, that region is filled with "ignore" nodes.
* Other mods, or the core itself, could possibly modify the area of map
currently loaded into a VoxelManip object. With the exception of Mapgen
VoxelManips (see above section), the internal buffers are not updated. For
this reason, it is strongly encouraged to complete the usage of a particular
VoxelManip object in the same callback it had been created.
* If a VoxelManip object will be used often, such as in an `on_generated()`
callback, consider passing a file-scoped table as the optional parameter to
`VoxelManip:get_data()`, which serves as a static buffer the function can use
to write map data to instead of returning a new table each call. This greatly
enhances performance by avoiding unnecessary memory allocations.
Methods
-------
`VoxelArea`
-----------
A helper class for voxel areas.
It can be created via `VoxelArea(pmin, pmax)` or
`VoxelArea:new({MinEdge = pmin, MaxEdge = pmax})`.
The coordinates are *inclusive*, like most other things in Minetest.
### Methods
For a particular position in a voxel area, whose flat array index is known,
it is often useful to know the index of a neighboring or nearby position.
The table below shows the changes of index required for 1 node movements along
the axes in a voxel area:
The values of `ystride` and `zstride` can be obtained using `area.ystride` and
`area.zstride`.
Mapgen objects
==============
### `voxelmanip`
This returns three values; the `VoxelManip` object to be used, minimum and
maximum emerged position, in that order. All mapgens support this object.
### `heightmap`
### `biomemap`
Returns an array containing the biome IDs of nodes in the most recently
generated chunk by the current mapgen.
### `heatmap`
### `humiditymap`
Returns an array containing the humidity values of nodes in the most recently
generated chunk by the current mapgen.
### `gennotify`
Registered entities
===================
Callbacks:
{
touching_ground = boolean,
-- Note that touching_ground is only true if the entity was moving and
-- collided with ground.
collides = boolean,
standing_on_object = boolean,
collisions = {
{
type = string, -- "node" or "object",
axis = string, -- "x", "y" or "z"
node_pos = vector, -- if type is "node"
object = ObjectRef, -- if type is "object"
old_velocity = vector,
new_velocity = vector,
},
...
}
-- `collisions` does not contain data of unloaded mapblock collisions
-- or when the velocity changes are negligibly small
}
L-system trees
==============
Tree definition
---------------
treedef={
axiom, --string initial tree axiom
rules_a, --string rules set A
rules_b, --string rules set B
rules_c, --string rules set C
rules_d, --string rules set D
trunk, --string trunk node name
leaves, --string leaves node name
leaves2, --string secondary leaves node name
leaves2_chance,--num chance (0-100) to replace leaves with leaves2
angle, --num angle in deg
iterations, --num max # of iterations, usually 2 -5
random_level, --num factor to lower number of iterations, usually 0 -
3
trunk_type, --string single/double/crossed) type of trunk: 1 node,
-- 2x2 nodes or 3x3 in cross shape
thin_branches, --boolean true -> use thin (1 node) branches
fruit, --string fruit node name
fruit_chance, --num chance (0-100) to replace leaves with fruit node
seed, --num random seed, if no seed is provided, the engine
will create one.
}
Key for special L-System symbols used in axioms
-----------------------------------------------
Example
-------
pos = {x=230,y=20,z=4}
apple_tree={
axiom="FFFFFAFFBF",
rules_a="[&&&FFFFF&&FFFF][&&&++++FFFFF&&FFFF][&&&----FFFFF&&FFFF]",
rules_b="[&&&++FFFFF&&FFFF][&&&--FFFFF&&FFFF][&&&------FFFFF&&FFFF]",
trunk="default:tree",
leaves="default:leaves",
angle=30,
iterations=2,
random_level=0,
trunk_type="single",
thin_branches=true,
fruit_chance=10,
fruit="default:apple"
}
minetest.spawn_tree(pos,apple_tree)
Privileges
==========
For consistency and practical reasons, privileges should strictly increase the
abilities of the user.
Do not register custom privileges that e.g. restrict the player from certain in-
game actions.
Checking privileges
-------------------
Built-in privileges
-------------------
* Security-related privileges:
* `privs`: can modify privileges of the players using `/grant[me]` and
`/revoke[me]` commands.
* `basic_privs`: can grant and revoke basic privileges as defined by
the `basic_privs` setting.
* `kick`: can kick other players from the server using `/kick` command.
* `ban`: can ban other players using `/ban` command.
* `password`: can use `/setpassword` and `/clearpassword` commands
to manage players' passwords.
* `protection_bypass`: can bypass node protection. Note that the engine does
not act upon this privilege,
it is only an implementation suggestion for games.
* Administrative privileges:
* `server`: can use `/fixlight`, `/deleteblocks` and `/deleteobjects`
commands. Can clear inventory of other players using `/clearinv` command.
* `rollback`: can use `/rollback_check` and `/rollback` commands.
Related settings
----------------
Utilities
---------
{
id = string,
title = string,
author = string,
-- The root directory of the game
path = string,
}
{
address = "127.0.0.1", -- IP address of client
ip_version = 4, -- IPv4 / IPv6
connection_uptime = 200, -- seconds since client connected
protocol_version = 32, -- protocol version used by client
formspec_version = 2, -- supported formspec version
lang_code = "fr", -- Language code used for translation
-- the following keys can be missing if no stats have been collected yet
min_rtt = 0.01, -- minimum round trip time
max_rtt = 0.2, -- maximum round trip time
avg_rtt = 0.02, -- average round trip time
min_jitter = 0.01, -- minimum packet time jitter
max_jitter = 0.5, -- maximum packet time jitter
avg_jitter = 0.03, -- average packet time jitter
-- the following information is available in a debug build only!!!
-- DO NOT USE IN MODS
--ser_vers = 26, -- serialization version used by client
--major = 0, -- major version number
--minor = 4, -- minor version number
--patch = 10, -- patch version number
--vers_string = "0.4.9-git", -- full version string
--state = "Active" -- current client state
}
* `minetest.get_player_window_information(player_name)`:
-- Will only be present if the client sent this information (requires v5.7+)
--
-- Note that none of these things are constant, they are likely to change
during a client
-- connection as the player resizes the window and moves it between monitors
--
-- real_gui_scaling and real_hud_scaling can be used instead of DPI.
-- OSes don't necessarily give the physical DPI, as they may allow user
configuration.
-- real_*_scaling is just OS DPI / 96 but with another level of user
configuration.
{
-- Current size of the in-game render target (pixels).
--
-- This is usually the window size, but may be smaller in certain
situations,
-- such as side-by-side mode.
size = {
x = 1308,
y = 577,
},
-- Estimated maximum formspec size before Minetest will start shrinking
the
-- formspec to fit. For a fullscreen formspec, use a size 10-20% larger
than
-- this and `padding[-0.01,-0.01]`.
max_formspec_size = {
x = 20,
y = 11.25
},
Logging
-------
* `minetest.debug(...)`
* Equivalent to `minetest.log(table.concat({...}, "\t"))`
* `minetest.log([level,] text)`
* `level` is one of `"none"`, `"error"`, `"warning"`, `"action"`,
`"info"`, or `"verbose"`. Default is `"none"`.
Registration functions
----------------------
### Environment
### Gameplay
* `minetest.register_craft(recipe)`
* Check recipe table syntax for different types below.
* `minetest.clear_craft(recipe)`
* Will erase existing craft based either on output item or on input recipe.
* Specify either output or input only. If you specify both, input will be
ignored. For input use the same recipe table syntax as for
`minetest.register_craft(recipe)`. For output specify only the item,
without a quantity.
* Returns false if no erase candidate could be found, otherwise returns true.
* **Warning**! The type field ("shaped", "cooking" or any other) will be
ignored if the recipe contains output. Erasing is then done independently
from the crafting method.
* `minetest.register_chatcommand(cmd, chatcommand definition)`
* `minetest.override_chatcommand(name, redefinition)`
* Overrides fields of a chatcommand registered with `register_chatcommand`.
* `minetest.unregister_chatcommand(name)`
* Unregisters a chatcommands registered with `register_chatcommand`.
* `minetest.register_privilege(name, definition)`
* `definition` can be a description or a definition table (see [Privilege
definition]).
* If it is a description, the priv will be granted to singleplayer and admin
by default.
* To allow players with `basic_privs` to grant, see the `basic_privs`
minetest.conf setting.
* `minetest.register_authentication_handler(authentication handler definition)`
* Registers an auth handler that overrides the builtin one.
* This function can be called by a single mod once only.
* `minetest.register_globalstep(function(dtime))`
* Called every server step, usually interval of 0.1s
* `minetest.register_on_mods_loaded(function())`
* Called after mods have finished loading and before the media is cached or the
aliases handled.
* `minetest.register_on_shutdown(function())`
* Called before server shutdown
* **Warning**: If the server terminates abnormally (i.e. crashes), the
registered callbacks **will likely not be run**. Data should be saved at
semi-frequent intervals as well as on server shutdown.
* `minetest.register_on_placenode(function(pos, newnode, placer, oldnode,
itemstack, pointed_thing))`
* Called when a node has been placed
* If return `true` no item is taken from `itemstack`
* `placer` may be any valid ObjectRef or nil.
* **Not recommended**; use `on_construct` or `after_place_node` in node
definition whenever possible.
* `minetest.register_on_dignode(function(pos, oldnode, digger))`
* Called when a node has been dug.
* **Not recommended**; Use `on_destruct` or `after_dig_node` in node
definition whenever possible.
* `minetest.register_on_punchnode(function(pos, node, puncher, pointed_thing))`
* Called when a node is punched
* `minetest.register_on_generated(function(minp, maxp, blockseed))`
* Called after generating a piece of world. Modifying nodes inside the area
is a bit faster than usual.
* `minetest.register_on_newplayer(function(ObjectRef))`
* Called when a new player enters the world for the first time
* `minetest.register_on_punchplayer(function(player, hitter, time_from_last_punch,
tool_capabilities, dir, damage))`
* Called when a player is punched
* Note: This callback is invoked even if the punched player is dead.
* `player`: ObjectRef - Player that was punched
* `hitter`: ObjectRef - Player that hit
* `time_from_last_punch`: Meant for disallowing spamming of clicks
(can be nil).
* `tool_capabilities`: Capability table of used item (can be nil)
* `dir`: Unit vector of direction of punch. Always defined. Points from
the puncher to the punched.
* `damage`: Number that represents the damage calculated by the engine
* should return `true` to prevent the default damage mechanism
* `minetest.register_on_rightclickplayer(function(player, clicker))`
* Called when the 'place/use' key was used while pointing a player
(not necessarily an actual rightclick)
* `player`: ObjectRef - Player that is acted upon
* `clicker`: ObjectRef - Object that acted upon `player`, may or may not be a
player
* `minetest.register_on_player_hpchange(function(player, hp_change, reason),
modifier)`
* Called when the player gets damaged or healed
* `player`: ObjectRef of the player
* `hp_change`: the amount of change. Negative when it is damage.
* `reason`: a PlayerHPChangeReason table.
* The `type` field will have one of the following values:
* `set_hp`: A mod or the engine called `set_hp` without
giving a type - use this for custom damage types.
* `punch`: Was punched. `reason.object` will hold the puncher, or nil
if none.
* `fall`
* `node_damage`: `damage_per_second` from a neighboring node.
`reason.node` will hold the node name or nil.
* `drown`
* `respawn`
* Any of the above types may have additional fields from mods.
* `reason.from` will be `mod` or `engine`.
* `modifier`: when true, the function should return the actual `hp_change`.
Note: modifiers only get a temporary `hp_change` that can be modified by
later modifiers.
Modifiers can return true as a second argument to stop the execution of
further functions.
Non-modifiers receive the final HP change calculated by the modifiers.
* `minetest.register_on_dieplayer(function(ObjectRef, reason))`
* Called when a player dies
* `reason`: a PlayerHPChangeReason table, see register_on_player_hpchange
* `minetest.register_on_respawnplayer(function(ObjectRef))`
* Called when player is to be respawned
* Called _before_ repositioning of player occurs
* return true in func to disable regular player placement
* `minetest.register_on_prejoinplayer(function(name, ip))`
* Called when a client connects to the server, prior to authentication
* If it returns a string, the client is disconnected with that string as
reason.
* `minetest.register_on_joinplayer(function(ObjectRef, last_login))`
* Called when a player joins the game
* `last_login`: The timestamp of the previous login, or nil if player is new
* `minetest.register_on_leaveplayer(function(ObjectRef, timed_out))`
* Called when a player leaves the game
* `timed_out`: True for timeout, false for other reasons.
* `minetest.register_on_authplayer(function(name, ip, is_success))`
* Called when a client attempts to log into an account.
* `name`: The name of the account being authenticated.
* `ip`: The IP address of the client
* `is_success`: Whether the client was successfully authenticated
* For newly registered accounts, `is_success` will always be true
* `minetest.register_on_auth_fail(function(name, ip))`
* Deprecated: use `minetest.register_on_authplayer(name, ip, is_success)`
instead.
* `minetest.register_on_cheat(function(ObjectRef, cheat))`
* Called when a player cheats
* `cheat`: `{type=<cheat_type>}`, where `<cheat_type>` is one of:
* `moved_too_fast`
* `interacted_too_far`
* `interacted_with_self`
* `interacted_while_dead`
* `finished_unknown_dig`
* `dug_unbreakable`
* `dug_too_fast`
* `minetest.register_on_chat_message(function(name, message))`
* Called always when a player says something
* Return `true` to mark the message as handled, which means that it will
not be sent to other players.
* `minetest.register_on_chatcommand(function(name, command, params))`
* Called always when a chatcommand is triggered, before
`minetest.registered_chatcommands`
is checked to see if the command exists, but after the input is parsed.
* Return `true` to mark the command as handled, which means that the default
handlers will be prevented.
* `minetest.register_on_player_receive_fields(function(player, formname, fields))`
* Called when the server received input from `player` in a formspec with
the given `formname`. Specifically, this is called on any of the
following events:
* a button was pressed,
* Enter was pressed while the focus was on a text field
* a checkbox was toggled,
* something was selected in a dropdown list,
* a different tab was selected,
* selection was changed in a textlist or table,
* an entry was double-clicked in a textlist or table,
* a scrollbar was moved, or
* the form was actively closed by the player.
* Fields are sent for formspec elements which define a field. `fields`
is a table containing each formspecs element value (as string), with
the `name` parameter as index for each. The value depends on the
formspec element type:
* `animated_image`: Returns the index of the current frame.
* `button` and variants: If pressed, contains the user-facing button
text as value. If not pressed, is `nil`
* `field`, `textarea` and variants: Text in the field
* `dropdown`: Either the index or value, depending on the `index event`
dropdown argument.
* `tabheader`: Tab index, starting with `"1"` (only if tab changed)
* `checkbox`: `"true"` if checked, `"false"` if unchecked
* `textlist`: See `minetest.explode_textlist_event`
* `table`: See `minetest.explode_table_event`
* `scrollbar`: See `minetest.explode_scrollbar_event`
* Special case: `["quit"]="true"` is sent when the user actively
closed the form by mouse click, keypress or through a button_exit[]
element.
* Special case: `["key_enter"]="true"` is sent when the user pressed
the Enter key and the focus was either nowhere (causing the formspec
to be closed) or on a button. If the focus was on a text field,
additionally, the index `key_enter_field` contains the name of the
text field. See also: `field_close_on_enter`.
* Newest functions are called first
* If function returns `true`, remaining functions are not called
* `minetest.register_on_craft(function(itemstack, player, old_craft_grid,
craft_inv))`
* Called when `player` crafts something
* `itemstack` is the output
* `old_craft_grid` contains the recipe (Note: the one in the inventory is
cleared).
* `craft_inv` is the inventory with the crafting grid
* Return either an `ItemStack`, to replace the output, or `nil`, to not
modify it.
* `minetest.register_craft_predict(function(itemstack, player, old_craft_grid,
craft_inv))`
* The same as before, except that it is called before the player crafts, to
make craft prediction, and it should not change anything.
* `minetest.register_allow_player_inventory_action(function(player, action,
inventory, inventory_info))`
* Determines how much of a stack may be taken, put or moved to a
player inventory.
* Function arguments: see `minetest.register_on_player_inventory_action`
* Return a numeric value to limit the amount of items to be taken, put or
moved. A value of `-1` for `take` will make the source stack infinite.
* `minetest.register_on_player_inventory_action(function(player, action, inventory,
inventory_info))`
* Called after an item take, put or move event from/to/in a player inventory
* These inventory actions are recognized:
* move: Item was moved within the player inventory
* put: Item was put into player inventory from another inventory
* take: Item was taken from player inventory and put into another inventory
* `player` (type `ObjectRef`) is the player who modified the inventory
`inventory` (type `InvRef`).
* List of possible `action` (string) values and their
`inventory_info` (table) contents:
* `move`: `{from_list=string, to_list=string, from_index=number,
to_index=number, count=number}`
* `put`: `{listname=string, index=number, stack=ItemStack}`
* `take`: Same as `put`
* Does not accept or handle any return value.
* `minetest.register_on_protection_violation(function(pos, name))`
* Called by `builtin` and mods when a player violates protection at a
position (eg, digs a node or punches a protected entity).
* The registered functions can be called using
`minetest.record_protection_violation`.
* The provided function should check that the position is protected by the
mod calling this function before it prints a message, if it does, to
allow for multiple protection mods.
* `minetest.register_on_item_eat(function(hp_change, replace_with_item, itemstack,
user, pointed_thing))`
* Called when an item is eaten, by `minetest.item_eat`
* Return `itemstack` to cancel the default item eat response (i.e.: hp
increase).
* `minetest.register_on_item_pickup(function(itemstack, picker, pointed_thing,
time_from_last_punch, ...))`
* Called by `minetest.item_pickup` before an item is picked up.
* Function is added to `minetest.registered_on_item_pickups`.
* Oldest functions are called first.
* Parameters are the same as in the `on_pickup` callback.
* Return an itemstack to cancel the default item pick-up response (i.e.: adding
the item into inventory).
* `minetest.register_on_priv_grant(function(name, granter, priv))`
* Called when `granter` grants the priv `priv` to `name`.
* Note that the callback will be called twice if it's done by a player,
once with granter being the player name, and again with granter being nil.
* `minetest.register_on_priv_revoke(function(name, revoker, priv))`
* Called when `revoker` revokes the priv `priv` from `name`.
* Note that the callback will be called twice if it's done by a player,
once with revoker being the player name, and again with revoker being nil.
* `minetest.register_can_bypass_userlimit(function(name, ip))`
* Called when `name` user connects with `ip`.
* Return `true` to by pass the player limit
* `minetest.register_on_modchannel_message(function(channel_name, sender,
message))`
* Called when an incoming mod channel message is received
* You should have joined some channels to receive events.
* If message comes from a server mod, `sender` field is an empty string.
* `minetest.register_on_liquid_transformed(function(pos_list, node_list))`
* Called after liquid nodes (`liquidtype ~= "none"`) are modified by the
engine's liquid transformation process.
* `pos_list` is an array of all modified positions.
* `node_list` is an array of the old node that was previously at the position
with the corresponding index in pos_list.
* `minetest.register_on_mapblocks_changed(function(modified_blocks,
modified_block_count))`
* Called soon after any nodes or node metadata have been modified. No
modifications will be missed, but there may be false positives.
* Will never be called more than once per server step.
* `modified_blocks` is the set of modified mapblock position hashes. These
are in the same format as those produced by `minetest.hash_node_position`,
and can be converted to positions with `minetest.get_position_from_hash`.
The set is a table where the keys are hashes and the values are `true`.
* `modified_block_count` is the number of entries in the set.
* Note: callbacks must be registered at mod load time.
Setting-related
---------------
Authentication
--------------
* `minetest.string_to_privs(str[, delim])`:
* Converts string representation of privs into table form
* `delim`: String separating the privs. Defaults to `","`.
* Returns `{ priv1 = true, ... }`
* `minetest.privs_to_string(privs[, delim])`:
* Returns the string representation of `privs`
* `delim`: String to delimit privs. Defaults to `","`.
* `minetest.get_player_privs(name) -> {priv1=true,...}`
* `minetest.check_player_privs(player_or_name, ...)`:
returns `bool, missing_privs`
* A quickhand for checking privileges.
* `player_or_name`: Either a Player object or the name of a player.
* `...` is either a list of strings, e.g. `"priva", "privb"` or
a table, e.g. `{ priva = true, privb = true }`.
`minetest.set_player_password`, `minetest.set_player_privs`,
`minetest.get_player_privs` and `minetest.auth_reload` call the authentication
handler.
Chat
----
* `minetest.chat_send_all(text)`
* `minetest.chat_send_player(name, text)`
* `minetest.format_chat_message(name, message)`
* Used by the server to format a chat message, based on the setting
`chat_message_format`.
Refer to the documentation of the setting for a list of valid placeholders.
* Takes player name and message, and returns the formatted string to be sent to
players.
* Can be redefined by mods if required, for things like colored names or
messages.
* **Only** the first occurrence of each placeholder will be replaced.
Environment access
------------------
* `minetest.set_node(pos, node)`
* `minetest.add_node(pos, node)`: alias to `minetest.set_node`
* Set node at position `pos`
* `node`: table `{name=string, param1=number, param2=number}`
* If param1 or param2 is omitted, it's set to `0`.
* e.g. `minetest.set_node({x=0, y=10, z=0}, {name="default:wood"})`
* `minetest.bulk_set_node({pos1, pos2, pos3, ...}, node)`
* Set node on all positions set in the first argument.
* e.g. `minetest.bulk_set_node({{x=0, y=1, z=1}, {x=1, y=2, z=2}},
{name="default:stone"})`
* For node specification or position syntax see `minetest.set_node` call
* Faster than set_node due to single call, but still considerably slower
than Lua Voxel Manipulators (LVM) for large numbers of nodes.
Unlike LVMs, this will call node callbacks. It also allows setting nodes
in spread out positions which would cause LVMs to waste memory.
For setting a cube, this is 1.3x faster than set_node whereas LVM is 20
times faster.
* `minetest.swap_node(pos, node)`
* Set node at position, but don't remove metadata
* `minetest.remove_node(pos)`
* By default it does the same as `minetest.set_node(pos, {name="air"})`
* `minetest.get_node(pos)`
* Returns the node at the given position as table in the format
`{name="node_name", param1=0, param2=0}`,
returns `{name="ignore", param1=0, param2=0}` for unloaded areas.
* `minetest.get_node_or_nil(pos)`
* Same as `get_node` but returns `nil` for unloaded areas.
* `minetest.get_node_light(pos[, timeofday])`
* Gets the light value at the given position. Note that the light value
"inside" the node at the given position is returned, so you usually want
to get the light value of a neighbor.
* `pos`: The position where to measure the light.
* `timeofday`: `nil` for current time, `0` for night, `0.5` for day
* Returns a number between `0` and `15` or `nil`
* `nil` is returned e.g. when the map isn't loaded at `pos`
* `minetest.get_natural_light(pos[, timeofday])`
* Figures out the sunlight (or moonlight) value at pos at the given time of
day.
* `pos`: The position of the node
* `timeofday`: `nil` for current time, `0` for night, `0.5` for day
* Returns a number between `0` and `15` or `nil`
* This function tests 203 nodes in the worst case, which happens very
unlikely
* `minetest.get_artificial_light(param1)`
* Calculates the artificial light (light from e.g. torches) value from the
`param1` value.
* `param1`: The param1 value of a `paramtype = "light"` node.
* Returns a number between `0` and `15`
* Currently it's the same as `math.floor(param1 / 16)`, except that it
ensures compatibility.
* `minetest.place_node(pos, node)`
* Place node with the same effects that a player would cause
* `minetest.dig_node(pos)`
* Dig node with the same effects that a player would cause
* Returns `true` if successful, `false` on failure (e.g. protected location)
* `minetest.punch_node(pos)`
* Punch node with the same effects that a player would cause
* `minetest.spawn_falling_node(pos)`
* Change node into falling node
* Returns `true` and the ObjectRef of the spawned entity if successful, `false`
on failure
* `minetest.find_nodes_with_meta(pos1, pos2)`
* Get a table of positions of nodes that have metadata within a region
{pos1, pos2}.
* `minetest.get_meta(pos)`
* Get a `NodeMetaRef` at that position
* `minetest.get_node_timer(pos)`
* Get `NodeTimerRef`
* `minetest.add_entity(pos, name, [staticdata])`: Spawn Lua-defined entity at
position.
* Returns `ObjectRef`, or `nil` if failed
* `minetest.add_item(pos, item)`: Spawn item
* Returns `ObjectRef`, or `nil` if failed
* `minetest.get_player_by_name(name)`: Get an `ObjectRef` to a player
* `minetest.get_objects_inside_radius(pos, radius)`: returns a list of
ObjectRefs.
* `radius`: using a Euclidean metric
* `minetest.get_objects_in_area(pos1, pos2)`: returns a list of
ObjectRefs.
* `pos1` and `pos2` are the min and max positions of the area to search.
* `minetest.set_timeofday(val)`
* `val` is between `0` and `1`; `0` for midnight, `0.5` for midday
* `minetest.get_timeofday()`
* `minetest.get_gametime()`: returns the time, in seconds, since the world was
created.
* `minetest.get_day_count()`: returns number days elapsed since world was
created.
* accounts for time changes.
* `minetest.find_node_near(pos, radius, nodenames, [search_center])`: returns
pos or `nil`.
* `radius`: using a maximum metric
* `nodenames`: e.g. `{"ignore", "group:tree"}` or `"default:dirt"`
* `search_center` is an optional boolean (default: `false`)
If true `pos` is also checked for the nodes
* `minetest.find_nodes_in_area(pos1, pos2, nodenames, [grouped])`
* `pos1` and `pos2` are the min and max positions of the area to search.
* `nodenames`: e.g. `{"ignore", "group:tree"}` or `"default:dirt"`
* If `grouped` is true the return value is a table indexed by node name
which contains lists of positions.
* If `grouped` is false or absent the return values are as follows:
first value: Table with all node positions
second value: Table with the count of each node with the node name
as index
* Area volume is limited to 4,096,000 nodes
* `minetest.find_nodes_in_area_under_air(pos1, pos2, nodenames)`: returns a
list of positions.
* `nodenames`: e.g. `{"ignore", "group:tree"}` or `"default:dirt"`
* Return value: Table with all node positions with a node air above
* Area volume is limited to 4,096,000 nodes
* `minetest.get_perlin(noiseparams)`
* Return world-specific perlin noise.
* The actual seed used is the noiseparams seed plus the world seed.
* `minetest.get_perlin(seeddiff, octaves, persistence, spread)`
* Deprecated: use `minetest.get_perlin(noiseparams)` instead.
* Return world-specific perlin noise.
* `minetest.get_voxel_manip([pos1, pos2])`
* Return voxel manipulator object.
* Loads the manipulator from the map if positions are passed.
* `minetest.set_gen_notify(flags, {deco_ids})`
* Set the types of on-generate notifications that should be collected.
* `flags` is a flag field with the available flags:
* dungeon
* temple
* cave_begin
* cave_end
* large_cave_begin
* large_cave_end
* decoration
* The second parameter is a list of IDs of decorations which notification
is requested for.
* `minetest.get_gen_notify()`
* Returns a flagstring and a table with the `deco_id`s.
* `minetest.get_decoration_id(decoration_name)`
* Returns the decoration ID number for the provided decoration name string,
or `nil` on failure.
* `minetest.get_mapgen_object(objectname)`
* Return requested mapgen object if available (see [Mapgen objects])
* `minetest.get_heat(pos)`
* Returns the heat at the position, or `nil` on failure.
* `minetest.get_humidity(pos)`
* Returns the humidity at the position, or `nil` on failure.
* `minetest.get_biome_data(pos)`
* Returns a table containing:
* `biome` the biome id of the biome at that position
* `heat` the heat at the position
* `humidity` the humidity at the position
* Or returns `nil` on failure.
* `minetest.get_biome_id(biome_name)`
* Returns the biome id, as used in the biomemap Mapgen object and returned
by `minetest.get_biome_data(pos)`, for a given biome_name string.
* `minetest.get_biome_name(biome_id)`
* Returns the biome name string for the provided biome id, or `nil` on
failure.
* If no biomes have been registered, such as in mgv6, returns `default`.
* `minetest.get_mapgen_params()`
* Deprecated: use `minetest.get_mapgen_setting(name)` instead.
* Returns a table containing:
* `mgname`
* `seed`
* `chunksize`
* `water_level`
* `flags`
* `minetest.set_mapgen_params(MapgenParams)`
* Deprecated: use `minetest.set_mapgen_setting(name, value, override)`
instead.
* Set map generation parameters.
* Function cannot be called after the registration period.
* Takes a table as an argument with the fields:
* `mgname`
* `seed`
* `chunksize`
* `water_level`
* `flags`
* Leave field unset to leave that parameter unchanged.
* `flags` contains a comma-delimited string of flags to set, or if the
prefix `"no"` is attached, clears instead.
* `flags` is in the same format and has the same options as `mg_flags` in
`minetest.conf`.
* `minetest.get_mapgen_edges([mapgen_limit[, chunksize]])`
* Returns the minimum and maximum possible generated node positions
in that order.
* `mapgen_limit` is an optional number. If it is absent, its value is that
of the *active* mapgen setting `"mapgen_limit"`.
* `chunksize` is an optional number. If it is absent, its value is that
of the *active* mapgen setting `"chunksize"`.
* `minetest.get_mapgen_setting(name)`
* Gets the *active* mapgen setting (or nil if none exists) in string
format with the following order of precedence:
1) Settings loaded from map_meta.txt or overrides set during mod
execution.
2) Settings set by mods without a metafile override
3) Settings explicitly set in the user config file, minetest.conf
4) Settings set as the user config default
* `minetest.get_mapgen_setting_noiseparams(name)`
* Same as above, but returns the value as a NoiseParams table if the
setting `name` exists and is a valid NoiseParams.
* `minetest.set_mapgen_setting(name, value, [override_meta])`
* Sets a mapgen param to `value`, and will take effect if the corresponding
mapgen setting is not already present in map_meta.txt.
* `override_meta` is an optional boolean (default: `false`). If this is set
to true, the setting will become the active setting regardless of the map
metafile contents.
* Note: to set the seed, use `"seed"`, not `"fixed_map_seed"`.
* `minetest.set_mapgen_setting_noiseparams(name, value, [override_meta])`
* Same as above, except value is a NoiseParams table.
* `minetest.set_noiseparams(name, noiseparams, set_default)`
* Sets the noiseparams setting of `name` to the noiseparams table specified
in `noiseparams`.
* `set_default` is an optional boolean (default: `true`) that specifies
whether the setting should be applied to the default config or current
active config.
* `minetest.get_noiseparams(name)`
* Returns a table of the noiseparams for name.
* `minetest.generate_ores(vm, pos1, pos2)`
* Generate all registered ores within the VoxelManip `vm` and in the area
from `pos1` to `pos2`.
* `pos1` and `pos2` are optional and default to mapchunk minp and maxp.
* `minetest.generate_decorations(vm, pos1, pos2)`
* Generate all registered decorations within the VoxelManip `vm` and in the
area from `pos1` to `pos2`.
* `pos1` and `pos2` are optional and default to mapchunk minp and maxp.
* `minetest.clear_objects([options])`
* Clear all objects in the environment
* Takes an optional table as an argument with the field `mode`.
* mode = `"full"`: Load and go through every mapblock, clearing
objects (default).
* mode = `"quick"`: Clear objects immediately in loaded mapblocks,
clear objects in unloaded mapblocks only when the
mapblocks are next activated.
* `minetest.load_area(pos1[, pos2])`
* Load the mapblocks containing the area from `pos1` to `pos2`.
`pos2` defaults to `pos1` if not specified.
* This function does not trigger map generation.
* `minetest.emerge_area(pos1, pos2, [callback], [param])`
* Queue all blocks in the area from `pos1` to `pos2`, inclusive, to be
asynchronously fetched from memory, loaded from disk, or if inexistent,
generates them.
* If `callback` is a valid Lua function, this will be called for each block
emerged.
* The function signature of callback is:
`function EmergeAreaCallback(blockpos, action, calls_remaining, param)`
* `blockpos` is the *block* coordinates of the block that had been
emerged.
* `action` could be one of the following constant values:
* `minetest.EMERGE_CANCELLED`
* `minetest.EMERGE_ERRORED`
* `minetest.EMERGE_FROM_MEMORY`
* `minetest.EMERGE_FROM_DISK`
* `minetest.EMERGE_GENERATED`
* `calls_remaining` is the number of callbacks to be expected after
this one.
* `param` is the user-defined parameter passed to emerge_area (or
nil if the parameter was absent).
* `minetest.delete_area(pos1, pos2)`
* delete all mapblocks in the area from pos1 to pos2, inclusive
* `minetest.line_of_sight(pos1, pos2)`: returns `boolean, pos`
* Checks if there is anything other than air between pos1 and pos2.
* Returns false if something is blocking the sight.
* Returns the position of the blocking node when `false`
* `pos1`: First position
* `pos2`: Second position
* `minetest.raycast(pos1, pos2, objects, liquids)`: returns `Raycast`
* Creates a `Raycast` object.
* `pos1`: start of the ray
* `pos2`: end of the ray
* `objects`: if false, only nodes will be returned. Default is `true`.
* `liquids`: if false, liquid nodes (`liquidtype ~= "none"`) won't be
returned. Default is `false`.
* `minetest.find_path(pos1,pos2,searchdistance,max_jump,max_drop,algorithm)`
* returns table containing path that can be walked on
* returns a table of 3D points representing a path from `pos1` to `pos2` or
`nil` on failure.
* Reasons for failure:
* No path exists at all
* No path exists within `searchdistance` (see below)
* Start or end pos is buried in land
* `pos1`: start position
* `pos2`: end position
* `searchdistance`: maximum distance from the search positions to search in.
In detail: Path must be completely inside a cuboid. The minimum
`searchdistance` of 1 will confine search between `pos1` and `pos2`.
Larger values will increase the size of this cuboid in all directions
* `max_jump`: maximum height difference to consider walkable
* `max_drop`: maximum height difference to consider droppable
* `algorithm`: One of `"A*_noprefetch"` (default), `"A*"`, `"Dijkstra"`.
Difference between `"A*"` and `"A*_noprefetch"` is that
`"A*"` will pre-calculate the cost-data, the other will calculate it
on-the-fly
* `minetest.spawn_tree (pos, {treedef})`
* spawns L-system tree at given `pos` with definition in `treedef` table
* `minetest.transforming_liquid_add(pos)`
* add node to liquid flow update queue
* `minetest.get_node_max_level(pos)`
* get max available level for leveled node
* `minetest.get_node_level(pos)`
* get level of leveled node (water, snow)
* `minetest.set_node_level(pos, level)`
* set level of leveled node, default `level` equals `1`
* if `totallevel > maxlevel`, returns rest (`total-max`).
* `minetest.add_node_level(pos, level)`
* increase level of leveled node by level, default `level` equals `1`
* if `totallevel > maxlevel`, returns rest (`total-max`)
* `level` must be between -127 and 127
* `minetest.fix_light(pos1, pos2)`: returns `true`/`false`
* resets the light in a cuboid-shaped part of
the map and removes lighting bugs.
* Loads the area if it is not loaded.
* `pos1` is the corner of the cuboid with the least coordinates
(in node coordinates), inclusive.
* `pos2` is the opposite corner of the cuboid, inclusive.
* The actual updated cuboid might be larger than the specified one,
because only whole map blocks can be updated.
The actual updated area consists of those map blocks that intersect
with the given cuboid.
* However, the neighborhood of the updated area might change
as well, as light can spread out of the cuboid, also light
might be removed.
* returns `false` if the area is not fully generated,
`true` otherwise
* `minetest.check_single_for_falling(pos)`
* causes an unsupported `group:falling_node` node to fall and causes an
unattached `group:attached_node` node to fall.
* does not spread these updates to neighbors.
* `minetest.check_for_falling(pos)`
* causes an unsupported `group:falling_node` node to fall and causes an
unattached `group:attached_node` node to fall.
* spread these updates to neighbors and can cause a cascade
of nodes to fall.
* `minetest.get_spawn_level(x, z)`
* Returns a player spawn y co-ordinate for the provided (x, z)
co-ordinates, or `nil` for an unsuitable spawn point.
* For most mapgens a 'suitable spawn point' is one with y between
`water_level` and `water_level + 16`, and in mgv7 well away from rivers,
so `nil` will be returned for many (x, z) co-ordinates.
* The spawn level returned is for a player spawn in unmodified terrain.
* The spawn level is intentionally above terrain level to cope with
full-node biome 'dust' nodes.
Mod channels
------------
* `minetest.mod_channel_join(channel_name)`
* Server joins channel `channel_name`, and creates it if necessary. You
should listen for incoming messages with
`minetest.register_on_modchannel_message`
Inventory
---------
* `location` = e.g.
* `{type="player", name="celeron55"}`
* `{type="node", pos={x=, y=, z=}}`
* `{type="detached", name="creative"}`
* `minetest.create_detached_inventory(name, callbacks, [player_name])`: returns
an `InvRef`.
* `callbacks`: See [Detached inventory callbacks]
* `player_name`: Make detached inventory available to one player
exclusively, by default they will be sent to every player (even if not
used).
Note that this parameter is mostly just a workaround and will be removed
in future releases.
* Creates a detached inventory. If it already exists, it is cleared.
* `minetest.remove_detached_inventory(name)`
* Returns a `boolean` indicating whether the removal succeeded.
* `minetest.do_item_eat(hp_change, replace_with_item, itemstack, user,
pointed_thing)`:
returns leftover ItemStack or nil to indicate no inventory change
* See `minetest.item_eat` and `minetest.register_on_item_eat`
Formspec
--------
Item handling
-------------
{
{
method = "cooking", width = 3,
output = "default:gold_ingot", items = {"default:gold_lump"}
},
{
method = "normal", width = 1,
output = "default:gold_ingot 9", items = {"default:goldblock"}
}
}
Rollback
--------
Sounds
------
Timing
------
* `job:cancel()`
* Cancels the job function from being called
Async environment
-----------------
The async environment does *not* have access to the map, entities, players or any
globals defined in the 'usual' environment. Consequently, functions like
`minetest.get_node()` or `minetest.get_player_by_name()` simply do not exist in it.
Arguments and return values passed through this can contain certain userdata
objects that will be seamlessly copied (not shared) to the async environment.
This allows you easy interoperability for delegating work to jobs.
Classes:
* `ItemStack`
* `PerlinNoise`
* `PerlinNoiseMap`
* `PseudoRandom`
* `PcgRandom`
* `SecureRandom`
* `VoxelArea`
* `VoxelManip`
* only if transferred into environment; can't read/write to map
* `Settings`
Functions:
* Standalone helpers such as logging, filesystem, encoding,
hashing or compression APIs
* `minetest.request_insecure_environment` (same restrictions apply)
Variables:
* `minetest.settings`
* `minetest.registered_items`, `registered_nodes`, `registered_tools`,
`registered_craftitems` and `registered_aliases`
* with all functions and userdata values replaced by `true`, calling any
callbacks here is obviously not possible
Server
------
Bans
----
Particles
---------
* `minetest.add_particle(particle definition)`
* Deprecated: `minetest.add_particle(pos, velocity, acceleration,
expirationtime, size, collisiondetection, texture, playername)`
* `minetest.add_particlespawner(particlespawner definition)`
* Add a `ParticleSpawner`, an object that spawns an amount of particles
over `time` seconds.
* Returns an `id`, and -1 if adding didn't succeed
* Deprecated: `minetest.add_particlespawner(amount, time,
minpos, maxpos,
minvel, maxvel,
minacc, maxacc,
minexptime, maxexptime,
minsize, maxsize,
collisiondetection, texture, playername)`
* `minetest.delete_particlespawner(id, player)`
* Delete `ParticleSpawner` with `id` (return value from
`minetest.add_particlespawner`).
* If playername is specified, only deletes on the player's client,
otherwise on all clients.
Schematics
----------
* `minetest.read_schematic(schematic, options)`
* Returns a Lua table representing the schematic (see: [Schematic specifier])
* `schematic` is the schematic to read (see: [Schematic specifier])
* `options` is a table containing the following optional parameters:
* `write_yslice_prob`: string value:
* `none`: no `write_yslice_prob` table is inserted,
* `low`: only probabilities that are not 254 or 255 are written in
the `write_ylisce_prob` table,
* `all`: write all probabilities to the `write_yslice_prob` table.
* The default for this option is `all`.
* Any invalid value will be interpreted as `all`.
HTTP Requests
-------------
* `minetest.request_http_api()`:
* returns `HTTPApiTable` containing http functions if the calling mod has
been granted access by being listed in the `secure.http_mods` or
`secure.trusted_mods` setting, otherwise returns `nil`.
* The returned table contains the functions `fetch`, `fetch_async` and
`fetch_async_get` described below.
* Only works at init time and must be called from the mod's main scope
(not from a function).
* Function only exists if minetest server was built with cURL support.
* **DO NOT ALLOW ANY OTHER MODS TO ACCESS THE RETURNED TABLE, STORE IT IN
A LOCAL VARIABLE!**
* `HTTPApiTable.fetch(HTTPRequest req, callback)`
* Performs given request asynchronously and calls callback upon completion
* callback: `function(HTTPRequestResult res)`
* Use this HTTP function if you are unsure, the others are for advanced use
* `HTTPApiTable.fetch_async(HTTPRequest req)`: returns handle
* Performs given request asynchronously and returns handle for
`HTTPApiTable.fetch_async_get`
* `HTTPApiTable.fetch_async_get(handle)`: returns HTTPRequestResult
* Return response data for given asynchronous HTTP request
Storage API
-----------
* `minetest.get_mod_storage()`:
* returns reference to mod private `StorageRef`
* must be called during mod load time
Misc.
-----
* `minetest.forceload_free_block(pos[, transient])`
* stops forceloading the position `pos`
* If `transient` is `false` or absent, frees a persistent forceload.
If `true`, frees a transient forceload.
* `minetest.compare_block_status(pos, condition)`
* Checks whether the mapblock at position `pos` is in the wanted condition.
* `condition` may be one of the following values:
* `"unknown"`: not in memory
* `"emerging"`: in the queue for loading from disk or generating
* `"loaded"`: in memory but inactive (no ABMs are executed)
* `"active"`: in memory and active
* Other values are reserved for future functionality extensions
* Return value, the comparison status:
* `false`: Mapblock does not fulfill the wanted condition
* `true`: Mapblock meets the requirement
* `nil`: Unsupported `condition` value
* `minetest.global_exists(name)`
* Checks if a global variable has been set, without triggering a warning.
Global objects
--------------
Global tables
-------------
* `minetest.registered_items`
* Map of registered items, indexed by name
* `minetest.registered_nodes`
* Map of registered node definitions, indexed by name
* `minetest.registered_craftitems`
* Map of registered craft item definitions, indexed by name
* `minetest.registered_tools`
* Map of registered tool definitions, indexed by name
* `minetest.registered_entities`
* Map of registered entity prototypes, indexed by name
* Values in this table may be modified directly.
Note: changes to initial properties will only affect entities spawned
afterwards,
as they are only read when spawning.
* `minetest.object_refs`
* Map of object references, indexed by active object id
* `minetest.luaentities`
* Map of Lua entities, indexed by active object id
* `minetest.registered_abms`
* List of ABM definitions
* `minetest.registered_lbms`
* List of LBM definitions
* `minetest.registered_aliases`
* Map of registered aliases, indexed by name
* `minetest.registered_ores`
* Map of registered ore definitions, indexed by the `name` field.
* If `name` is nil, the key is the object handle returned by
`minetest.register_ore`.
* `minetest.registered_biomes`
* Map of registered biome definitions, indexed by the `name` field.
* If `name` is nil, the key is the object handle returned by
`minetest.register_biome`.
* `minetest.registered_decorations`
* Map of registered decoration definitions, indexed by the `name` field.
* If `name` is nil, the key is the object handle returned by
`minetest.register_decoration`.
* `minetest.registered_schematics`
* Map of registered schematic definitions, indexed by the `name` field.
* If `name` is nil, the key is the object handle returned by
`minetest.register_schematic`.
* `minetest.registered_chatcommands`
* Map of registered chat command definitions, indexed by name
* `minetest.registered_privileges`
* Map of registered privilege definitions, indexed by name
* Registered privileges can be modified directly in this table.
All callbacks registered with [Global callback registration functions] are added
to corresponding `minetest.registered_*` tables.
Class reference
===============
Sorted alphabetically.
`AreaStore`
-----------
Despite its name, mods must take care of persisting AreaStore data. They may
use the provided load and write functions for this.
### Methods
* `AreaStore(type_name)`
* Returns a new AreaStore instance
* `type_name`: optional, forces the internally used API.
* Possible values: `"LibSpatial"` (default).
* When other values are specified, or SpatialIndex is not available,
the custom Minetest functions are used.
* `get_area(id, include_corners, include_data)`
* Returns the area information about the specified ID.
* Returned values are either of these:
`InvRef`
--------
### Methods
### Callbacks
Detached & nodemeta inventories provide the following callbacks for move actions:
#### Before
#### After
The `on_*` callbacks are called after the items have been placed in the
inventories.
#### Swapping
When a player tries to put an item to a place where another item is, the items are
*swapped*.
This means that all callbacks will be called twice (once for each action).
`ItemStack`
-----------
### Methods
### Operators
* `stack1 == stack2`:
* Returns whether `stack1` and `stack2` are identical.
* Note: `stack1:to_string() == stack2:to_string()` is not reliable,
as stack metadata can be serialized in arbitrary order.
* Note: if `stack2` is an itemstring or table representation of an
ItemStack, this will always return false, even if it is
"equivalent".
`ItemStackMetaRef`
------------------
### Methods
`MetaDataRef`
-------------
Note: If a metadata value is in the format `${k}`, an attempt to get the value
will return the value associated with key `k`. There is a low recursion limit.
This behavior is **deprecated** and will be removed in a future version. Usage
of the `${k}` syntax in formspecs is not deprecated.
### Methods
Example:
metadata_table = {
-- metadata fields (key/value store)
fields = {
infotext = "Container",
anoter_key = "Another Value",
},
`ModChannel`
------------
### Methods
### Methods
`NodeTimerRef`
--------------
### Methods
* `set(timeout,elapsed)`
* set a timer's state
* `timeout` is in seconds, and supports fractional values (0.1 etc)
* `elapsed` is in seconds, and supports fractional values (0.1 etc)
* will trigger the node's `on_timer` function after `(timeout - elapsed)`
seconds.
* `start(timeout)`
* start a timer
* equivalent to `set(timeout,0)`
* `stop()`
* stops the timer
* `get_timeout()`: returns current timeout in seconds
* if `timeout` equals `0`, timer is inactive
* `get_elapsed()`: returns current elapsed time in seconds
* the node's `on_timer` function will be called after `(timeout - elapsed)`
seconds.
* `is_started()`: returns boolean state of timer
* returns `true` if timer is started, otherwise `false`
`ObjectRef`
-----------
### Attachments
To change position or rotation call `set_attach` again with the new values.
It is also possible to attach to a bone of the parent object. In that case the
child will follow movement and rotation of that bone.
### Methods
`PcgRandom`
-----------
### Methods
`PerlinNoise`
-------------
`PerlinNoise(noiseparams)`
`PerlinNoise(seed, octaves, persistence, spread)` (Deprecated).
`minetest.get_perlin(noiseparams)`
`minetest.get_perlin(seeddiff, octaves, persistence, spread)` (Deprecated).
### Methods
`PerlinNoiseMap`
----------------
### Methods
`PlayerMetaRef`
---------------
Player metadata.
Uses the same method of storage as the deprecated player attribute API, so
data there will also be in player meta.
Can be obtained using `player:get_meta()`.
### Methods
`PseudoRandom`
--------------
### Methods
`Raycast`
---------
The map is loaded as the ray advances. If the map is modified after the
`Raycast` is created, the changes may or may not have an effect on the object.
### Limitations
Raycasts don't always work properly for attached objects as the server has no
knowledge of models & bones.
### Methods
`SecureRandom`
--------------
### Methods
`Settings`
----------
### Methods
### Format
`StorageRef`
------------
WARNING: This storage backend is incapable of saving raw binary data due
to restrictions of JSON.
### Methods
Definition tables
=================
Object properties
-----------------
{
hp_max = 10,
-- Defines the maximum and default HP of the entity
-- For Lua entities the maximum is not enforced.
-- For players this defaults to `minetest.PLAYER_MAX_HP_DEFAULT`.
breath_max = 0,
-- For players only. Defaults to `minetest.PLAYER_MAX_BREATH_DEFAULT`.
zoom_fov = 0.0,
-- For players only. Zoom FOV in degrees.
-- Note that zoom loads and/or generates world beyond the server's
-- maximum send and generate distances, so acts like a telescope.
-- Smaller zoom_fov values increase the distance loaded/generated.
-- Defaults to 15 in creative mode, 0 in survival mode.
-- zoom_fov = 0 disables zooming for the player.
eye_height = 1.625,
-- For players only. Camera height above feet position in nodes.
physical = false,
-- Collide with `walkable` nodes.
collide_with_objects = true,
-- Collide with other objects if physical = true
pointable = true,
-- Whether the object can be pointed at
visual_size = {x = 1, y = 1, z = 1},
-- Multipliers for the visual size. If `z` is not specified, `x` will be
used
-- to scale the entity along both horizontal axes.
mesh = "model.obj",
-- File name of mesh when using "mesh" visual
textures = {},
-- Number of required textures depends on visual.
-- "cube" uses 6 textures just like a node, but all 6 must be defined.
-- "sprite" uses 1 texture.
-- "upright_sprite" uses 2 textures: {front, back}.
-- "wielditem" expects 'textures = {itemname}' (see 'visual' above).
-- "mesh" requires one texture for each mesh buffer/material (in order)
colors = {},
-- Number of required colors depends on visual
use_texture_alpha = false,
-- Use texture's alpha channel.
-- Excludes "upright_sprite" and "wielditem".
-- Note: currently causes visual issues when viewed through other
-- semi-transparent materials such as water.
spritediv = {x = 1, y = 1},
-- Used with spritesheet textures for animation and/or frame selection
-- according to position relative to player.
-- Defines the number of columns and rows in the spritesheet:
-- {columns, rows}.
initial_sprite_basepos = {x = 0, y = 0},
-- Used with spritesheet textures.
-- Defines the {column, row} position of the initially used frame in the
-- spritesheet.
is_visible = true,
-- If false, object is invisible and can't be pointed.
makes_footstep_sound = false,
-- If true, is able to make footstep sounds of nodes
-- (see node sound definition for details).
automatic_rotate = 0,
-- Set constant rotation in radians per second, positive or negative.
-- Object rotates along the local Y-axis, and works with set_rotation.
-- Set to 0 to disable constant rotation.
stepheight = 0,
-- If positive number, object will climb upwards when it moves
-- horizontally against a `walkable` node, if the height difference
-- is within `stepheight`.
automatic_face_movement_dir = 0.0,
-- Automatically set yaw to movement direction, offset in degrees.
-- 'false' to disable.
automatic_face_movement_max_rotation_per_sec = -1,
-- Limit automatic rotation to this value in degrees per second.
-- No limit if value <= 0.
backface_culling = true,
-- Set to false to disable backface_culling for model
glow = 0,
-- Add this much extra lighting when calculating texture color.
-- Value < 0 disables light's effect on texture color.
-- For faking self-lighting, UI style entities, or programmatic coloring
-- in mods.
nametag = "",
-- The name to display on the head of the object. By default empty.
-- If the object is a player, a nil or empty nametag is replaced by the
player's name.
-- For all other objects, a nil or empty string removes the nametag.
-- To hide a nametag, set its color alpha to zero. That will disable it
entirely.
nametag_color = <ColorSpec>,
-- Sets text color of nametag
nametag_bgcolor = <ColorSpec>,
-- Sets background color of nametag
-- `false` will cause the background to be set automatically based on user
settings.
-- Default: false
infotext = "",
-- Same as infotext for nodes. Empty by default
static_save = true,
-- If false, never save this object statically. It will simply be
-- deleted when the block gets unloaded.
-- The get_staticdata() callback is never called then.
-- Defaults to 'true'.
damage_texture_modifier = "^[brighten",
-- Texture modifier to be applied for a short duration when object is hit
shaded = true,
-- Setting this to 'false' disables diffuse lighting of entity
show_on_minimap = false,
-- Defaults to true for players, false for other entities.
-- If set to true the entity will show as a marker on the minimap.
}
Entity definition
-----------------
Used by `minetest.register_entity`.
{
initial_properties = {
visual = "mesh",
mesh = "boats_boat.obj",
...,
},
-- A table of object properties, see the `Object properties` section.
-- The properties in this table are applied to the object
-- once when it is spawned.
_custom_field = whatever,
-- You can define arbitrary member variables here (see Item definition
-- for more info) by using a '_' prefix
}
Used by `minetest.register_abm`.
{
label = "Lava cooling",
-- Descriptive label for profiling purposes (optional).
-- Definitions with identical labels will be listed as one.
nodenames = {"default:lava_source"},
-- Apply `action` function to these nodes.
-- `group:groupname` can also be used here.
interval = 10.0,
-- Operation interval in seconds
chance = 50,
-- Chance of triggering `action` per-node per-interval is 1.0 / chance
min_y = -32768,
max_y = 32767,
-- min and max height levels where ABM will be processed (inclusive)
-- can be used to reduce CPU usage
catch_up = true,
-- If true, catch-up behavior is enabled: The `chance` value is
-- temporarily reduced when returning to an area to simulate time lost
-- by the area being unattended. Note that the `chance` value can often
-- be reduced to 1.
Used by `minetest.register_lbm`.
A loading block modifier (LBM) is used to define a function that is called for
specific nodes (defined by `nodenames`) when a mapblock which contains such nodes
gets activated (not loaded!)
{
label = "Upgrade legacy doors",
-- Descriptive label for profiling purposes (optional).
-- Definitions with identical labels will be listed as one.
name = "modname:replace_legacy_door",
-- Identifier of the LBM, should follow the modname:<whatever> convention
nodenames = {"default:lava_source"},
-- List of node names to trigger the LBM on.
-- Names of non-registered nodes and groups (as group:groupname)
-- will work as well.
run_at_every_load = false,
-- Whether to run the LBM's action every time a block gets activated,
-- and not only the first time the block gets activated after the LBM
-- was introduced.
Tile definition
---------------
* `"image.png"`
* `{name="image.png", animation={Tile Animation definition}}`
* `{name="image.png", backface_culling=bool, align_style="node"/"world"/"user",
scale=int}`
* backface culling enabled by default for most nodes
* align style determines whether the texture will be rotated with the node
or kept aligned with its surroundings. "user" means that client
setting will be used, similar to `glasslike_framed_optional`.
Note: supported by solid nodes and nodeboxes only.
* scale is used to make texture span several (exactly `scale`) nodes,
instead of just one, in each direction. Works for world-aligned
textures only.
Note that as the effect is applied on per-mapblock basis, `16` should
be equally divisible by `scale` or you may get wrong results.
* `{name="image.png", color=ColorSpec}`
* the texture's color will be multiplied with this color.
* the tile's color overrides the owning node's color in all cases.
* deprecated, yet still supported field names:
* `image` (name)
{
type = "vertical_frames",
aspect_w = 16,
-- Width of a frame in pixels
aspect_h = 16,
-- Height of a frame in pixels
length = 3.0,
-- Full loop length
}
{
type = "sheet_2d",
frames_w = 5,
-- Width in number of frames
frames_h = 3,
-- Height in number of frames
frame_length = 0.5,
-- Length of a single frame
}
Item definition
---------------
{
description = "",
-- Can contain new lines. "\n" has to be used as new line character.
-- See also: `get_description` in [`ItemStack`]
short_description = "",
-- Must not contain new lines.
-- Defaults to nil.
-- Use an [`ItemStack`] to get the short description, e.g.:
-- ItemStack(itemname):get_short_description()
groups = {},
-- key = name, value = rating; rating = <number>.
-- If rating not applicable, use 1.
-- e.g. {wool = 1, fluffy = 3}
-- {soil = 2, outerspace = 1, crumbly = 1}
-- {bendy = 2, snappy = 1},
-- {hard = 1, metal = 1, spikes = 1}
inventory_image = "",
-- Texture shown in the inventory GUI
-- Defaults to a 3D rendering of the node if left empty.
inventory_overlay = "",
-- An overlay texture which is not affected by colorization
wield_image = "",
-- Texture shown when item is held in hand
-- Defaults to a 3D rendering of the node if left empty.
wield_overlay = "",
-- Like inventory_overlay but only used in the same situation as
wield_image
wield_scale = {x = 1, y = 1, z = 1},
-- Scale for the item when held in hand
palette = "",
-- An image file containing the palette of a node.
-- You can set the currently used color as the "palette_index" field of
-- the item stack metadata.
-- The palette is always stretched to fit indices between 0 and 255, to
-- ensure compatibility with "colorfacedir" (and similar) nodes.
color = "#ffffffff",
-- Color the item is colorized with. The palette overrides this.
stack_max = 99,
-- Maximum amount of items that can be in a single stack.
-- The default can be changed by the setting `default_stack_max`
range = 4.0,
-- Range of node and object pointing that is possible with this item held
liquids_pointable = false,
-- If true, item can point to all liquid nodes (`liquidtype ~= "none"`),
-- even those for which `pointable = false`
light_source = 0,
-- When used for nodes: Defines amount of light emitted by node.
-- Otherwise: Defines texture glow when viewed as a dropped item
-- To set the maximum (14), use the value 'minetest.LIGHT_MAX'.
-- A value outside the range 0 to minetest.LIGHT_MAX causes undefined
-- behavior.
-- See "Tool Capabilities" section for an example including explanation
tool_capabilities = {
full_punch_interval = 1.0,
max_drop_level = 0,
groupcaps = {
-- For example:
choppy = {times = {2.50, 1.40, 1.00}, uses = 20, maxlevel = 2},
},
damage_groups = {groupname = damage},
-- Damage values must be between -32768 and 32767 (2^15)
punch_attack_uses = nil,
-- Amount of uses this tool has for attacking players and entities
-- by punching them (0 = infinite uses).
-- For compatibility, this is automatically set from the first
-- suitable groupcap using the formula "uses * 3^(maxlevel - 1)".
-- It is recommend to set this explicitly instead of relying on the
-- fallback behavior.
},
node_placement_prediction = nil,
-- If nil and item is node, prediction is made automatically.
-- If nil and item is not a node, no prediction is made.
-- If "" and item is anything, no prediction is made.
-- Otherwise should be name of node which the client immediately places
-- on ground when the player places the item. Server will always update
-- with actual result shortly.
node_dig_prediction = "air",
-- if "", no prediction is made.
-- if "air", node is removed.
-- Otherwise should be name of node which the client immediately places
-- upon digging. Server will always update with actual result shortly.
sound = {
-- Definition of item sounds to be played at various events.
-- All fields in this table are optional.
breaks = <SimpleSoundSpec>,
-- When tool breaks due to wear. Ignored for non-tools
eat = <SimpleSoundSpec>,
-- When item is eaten with `minetest.do_item_eat`
punch_use = <SimpleSoundSpec>,
-- When item is used with the 'punch/mine' key pointing at a node or
entity
punch_use_air = <SimpleSoundSpec>,
-- When item is used with the 'punch/mine' key pointing at nothing
(air)
},
_custom_field = whatever,
-- Add your own custom fields. By convention, all custom field names
-- should start with `_` to avoid naming collisions with future engine
-- usage.
}
Node definition
---------------
Used by `minetest.register_node`.
{
-- <all fields allowed in item definitions>
visual_scale = 1.0,
-- Supported for drawtypes "plantlike", "signlike", "torchlike",
-- "firelike", "mesh", "nodebox", "allfaces".
-- For plantlike and firelike, the image will start at the bottom of the
-- node. For torchlike, the image will start at the surface to which the
-- node "attaches". For the other drawtypes the image will be centered
-- on the node.
color = ColorSpec,
-- The node's original color will be multiplied with this color.
-- If the node has a palette, then this setting only has an effect in
-- the inventory and on the wield item.
use_texture_alpha = ...,
-- Specifies how the texture's alpha channel will be used for rendering.
-- possible values:
-- * "opaque": Node is rendered opaque regardless of alpha channel
-- * "clip": A given pixel is either fully see-through or opaque
-- depending on the alpha channel being below/above 50% in value
-- * "blend": The alpha channel specifies how transparent a given pixel
-- of the rendered node is
-- The default is "opaque" for drawtypes normal, liquid and flowingliquid;
-- "clip" otherwise.
-- If set to a boolean value (deprecated): true either sets it to blend
-- or clip, false sets it to clip or opaque mode depending on the drawtype.
palette = "",
-- The node's `param2` is used to select a pixel from the image.
-- Pixels are arranged from left to right and from top to bottom.
-- The node's color will be multiplied with the selected pixel's color.
-- Tiles can override this behavior.
-- Only when `paramtype2` supports palettes.
post_effect_color = "#00000000",
-- Screen tint if player is inside node, see "ColorSpec"
place_param2 = 0,
-- Value for param2 that is set when player places node
is_ground_content = true,
-- If false, the cave generator and dungeon generator will not carve
-- through this node.
-- Specifically, this stops mod-added nodes being removed by caves and
-- dungeons when those generate in a neighbor mapchunk and extend out
-- beyond the edge of that mapchunk.
sunlight_propagates = false,
-- If true, sunlight will go infinitely through this node
move_resistance = 0,
-- Slows down movement of players through this node (max. 7).
-- If this is nil, it will be equal to liquid_viscosity.
-- Note: If liquid movement physics apply to the node
-- (see `liquid_move_physics`), the movement speed will also be
-- affected by the `movement_liquid_*` settings.
floodable = false,
-- If true, liquids flow into and replace this node.
-- Warning: making a liquid node 'floodable' will cause problems.
liquid_alternative_flowing = "",
liquid_alternative_source = "",
-- These fields may contain node names that represent the
-- flowing version (`liquid_alternative_flowing`) and
-- source version (`liquid_alternative_source`) of a liquid.
--
-- Specifically, these fields are required if any of these is true:
-- * `liquidtype ~= "none" or
-- * `drawtype == "liquid" or
-- * `drawtype == "flowingliquid"
--
-- Liquids consist of up to two nodes: source and flowing.
--
-- There are two ways to define a liquid:
-- 1) Source node and flowing node. This requires both fields to be
-- specified for both nodes.
-- 2) Standalone source node (cannot flow). `liquid_alternative_source`
-- must be specified and `liquid_range` must be set to 0.
--
-- Example:
-- liquid_alternative_flowing = "example:water_flowing",
-- liquid_alternative_source = "example:water_source",
liquid_viscosity = 0,
-- Controls speed at which the liquid spreads/flows (max. 7).
-- 0 is fastest, 7 is slowest.
-- By default, this also slows down movement of players inside the node
-- (can be overridden using `move_resistance`)
liquid_renewable = true,
-- If true, a new liquid source can be created by placing two or more
-- sources nearby
leveled = 0,
-- Only valid for "nodebox" drawtype with 'type = "leveled"'.
-- Allows defining the nodebox height without using param2.
-- The nodebox height is 'leveled' / 64 nodes.
-- The maximum value of 'leveled' is `leveled_max`.
leveled_max = 127,
-- Maximum value for `leveled` (0-127), enforced in
-- `minetest.set_node_level` and `minetest.add_node_level`.
-- Values above 124 might causes collision detection issues.
liquid_range = 8,
-- Maximum distance that flowing liquid nodes can spread around
-- source on flat land;
-- maximum = 8; set to 0 to disable liquid flow
drowning = 0,
-- Player will take this amount of damage if no bubbles are left
damage_per_second = 0,
-- If player is inside node, this damage is caused
connects_to = {},
-- Used for nodebox nodes with the type == "connected".
-- Specifies to what neighboring nodes connections will be drawn.
-- e.g. `{"group:fence", "default:wood"}` or `"default:stone"`
connect_sides = {},
-- Tells connected nodebox nodes to connect only to these sides of this
-- node. possible: "top", "bottom", "front", "left", "back", "right"
mesh = "",
-- File name of mesh when using "mesh" drawtype
selection_box = {
-- see [Node boxes] for possibilities
},
-- Custom selection box definition. Multiple boxes can be defined.
-- If "nodebox" drawtype is used and selection_box is nil, then node_box
-- definition is used for the selection box.
collision_box = {
-- see [Node boxes] for possibilities
},
-- Custom collision box definition. Multiple boxes can be defined.
-- If "nodebox" drawtype is used and collision_box is nil, then node_box
-- definition is used for the collision box.
waving = 0,
-- Valid for drawtypes:
-- mesh, nodebox, plantlike, allfaces_optional, liquid, flowingliquid.
-- 1 - wave node like plants (node top moves side-to-side, bottom is fixed)
-- 2 - wave node like leaves (whole node moves side-to-side)
-- 3 - wave node like liquids (whole node moves up and down)
-- Not all models will properly wave.
-- plantlike drawtype can only wave like plants.
-- allfaces_optional drawtype can only wave like leaves.
-- liquid, flowingliquid drawtypes can only wave like liquids.
sounds = {
-- Definition of node sounds to be played at various events.
-- All fields in this table are optional.
footstep = <SimpleSoundSpec>,
-- If walkable, played when object walks on it. If node is
-- climbable or a liquid, played when object moves through it
dug = <SimpleSoundSpec>,
-- Node was dug
place = <SimpleSoundSpec>,
-- Node was placed. Also played after falling
place_failed = <SimpleSoundSpec>,
-- When node placement failed.
-- Note: This happens if the _built-in_ node placement failed.
-- This sound will still be played if the node is placed in the
-- `on_place` callback manually.
fall = <SimpleSoundSpec>,
-- When node starts to fall or is detached
},
drop = "",
-- Name of dropped item when dug.
-- Default dropped item is the node itself.
-- Using a table allows multiple items, drop chances and item filtering:
drop = {
max_items = 1,
-- Maximum number of item lists to drop.
-- The entries in 'items' are processed in order. For each:
-- Item filtering is applied, chance of drop is applied, if both are
-- successful the entire item list is dropped.
-- Entry processing continues until the number of dropped item lists
-- equals 'max_items'.
-- Therefore, entries should progress from low to high drop chance.
items = {
-- Examples:
{
-- 1 in 1000 chance of dropping a diamond.
-- Default rarity is '1'.
rarity = 1000,
items = {"default:diamond"},
},
{
-- Only drop if using an item whose name is identical to one
-- of these.
tools = {"default:shovel_mese", "default:shovel_diamond"},
rarity = 5,
items = {"default:dirt"},
-- Whether all items in the dropped item list inherit the
-- hardware coloring palette color from the dug node.
-- Default is 'false'.
inherit_color = true,
},
{
-- Only drop if using an item whose name contains
-- "default:shovel_" (this item filtering by string matching
-- is deprecated, use tool_groups instead).
tools = {"~default:shovel_"},
rarity = 2,
-- The item list dropped.
items = {"default:sand", "default:desert_sand"},
},
{
-- Only drop if using an item in the "magicwand" group, or
-- an item that is in both the "pickaxe" and the "lucky"
-- groups.
tool_groups = {
"magicwand",
{"pickaxe", "lucky"}
},
items = {"default:coal_lump"},
},
},
},
on_construct = function(pos),
-- Node constructor; called after adding node.
-- Can set up metadata and stuff like that.
-- Not called for bulk node placement (i.e. schematics and VoxelManip).
-- Note: Within an on_construct callback, minetest.set_node can cause an
-- infinite loop if it invokes the same callback.
-- Consider using minetest.swap_node instead.
-- default: nil
on_destruct = function(pos),
-- Node destructor; called before removing node.
-- Not called for bulk node placement.
-- default: nil
mod_origin = "modname",
-- stores which mod actually registered a node
-- If the source could not be determined it contains "??"
-- Useful for getting which mod truly registered something
-- example: if a node is registered as ":othermodname:nodename",
-- nodename will show "othermodname", but mod_origin will say "modname"
}
Crafting recipes
----------------
Recipe input items can either be specified by item name (item count = 1)
or by group (see "Groups in crafting recipes" for details).
### Shaped
For example, for a 3x3 recipe, the `recipes` table must have
3 rows and 3 columns.
Parameters:
#### Examples
-- Stone pickaxe
{
output = "example:stone_pickaxe",
-- A 3x3 recipe which needs 3 stone in the 1st row,
-- and 1 stick in the horizontal middle in each of the 2nd and 3nd row.
-- The 4 remaining slots have to be empty.
recipe = {
{"example:stone", "example:stone", "example:stone"}, -- row 1
{"", "example:stick", "" }, -- row 2
{"", "example:stick", "" }, -- row 3
-- ^ column 1 ^ column 2 ^ column 3
},
-- There is no replacements table, so every input item
-- will be consumed.
}
-- Wet sponge
{
output = "example:wet_sponge",
-- 1x2 recipe with a water bucket above a dry sponge
recipe = {
{"example:water_bucket"},
{"example:dry_sponge"},
},
-- When the wet sponge is crafted, the water bucket
-- in the input slot is replaced with an empty
-- bucket
replacements = {
{"example:water_bucket", "example:empty_bucket"},
},
}
-- Magic book:
-- 3 magic orbs + 1 book crafts a magic book,
-- and the orbs will be replaced with 3 different runes.
{
output = "example:magic_book",
-- 3x2 recipe
recipe = {
-- 3 items in the group `magic_orb` on top of a book in the middle
{"group:magic_orb", "group:magic_orb", "group:magic_orb"},
{"", "example:book", ""},
},
-- When the book is crafted, the 3 magic orbs will be turned into
-- 3 runes: ice rune, earth rune and fire rune (from left to right)
replacements = {
{"group:magic_orb", "example:ice_rune"},
{"group:magic_orb", "example:earth_rune"},
{"group:magic_orb", "example:fire_rune"},
},
}
### Shapeless
Takes a list of input items (at least 1). The order or arrangement
of input items does not matter.
In order to craft the recipe, the players' crafting grid must have matching or
larger *count* of slots. The grid dimensions do not matter.
Parameters:
#### Example
{
-- Craft a mushroom stew from a bowl, a brown mushroom and a red mushroom
-- (no matter where in the input grid the items are placed)
type = "shapeless",
output = "example:mushroom_stew",
recipe = {
"example:bowl",
"example:mushroom_brown",
"example:mushroom_red",
},
}
Syntax:
{
type = "toolrepair",
additional_wear = -0.02, -- multiplier of 65536
}
Adds a shapeless recipe for *every* tool that doesn't have the `disable_repair=1`
group. If this recipe is used, repairing is possible with any crafting grid
with at least 2 slots.
The player can put 2 equal tools in the craft grid to get one "repaired" tool
back.
The wear of the output is determined by the wear of both tools, plus a
'repair bonus' given by `additional_wear`. To reduce the wear (i.e. 'repair'),
you want `additional_wear` to be negative.
The result is rounded and can't be lower than 0. If the result is 65536 or higher,
no crafting is possible.
### Cooking
A cooking recipe has a single input item, a single output item stack
and a cooking time. It represents cooking/baking/smelting/etc. items in
an oven, furnace, or something similar; the exact meaning is up for games
to decide, if they choose to use cooking at all.
The engine does not implement anything specific to cooking recipes, but
the recipes can be retrieved later using `minetest.get_craft_result` to
have a consistent interface across different games/mods.
Parameters:
Note: Games and mods are free to re-interpret the cooktime in special
cases, e.g. for a super furnace that cooks items twice as fast.
#### Example
{
type = "cooking",
output = "example:glass",
recipe = "example:sand",
cooktime = 3.0,
}
### Fuel
Like with cooking recipes, the engine does not do anything specific with
fuel recipes and it's up to games and mods to use them by retrieving
them via `minetest.get_craft_result`.
Parameters:
Note: Games and mods are free to re-interpret the burntime in special
cases, e.g. for an efficient furnace in which fuels burn twice as
long.
#### Examples
{
type = "fuel",
recipe = "example:coal_lump",
burntime = 20.0,
}
Lava bucket with a burn time of 60 seconds. Will become an empty bucket
if used:
{
type = "fuel",
recipe = "example:lava_bucket",
burntime = 60.0,
replacements = {{"example:lava_bucket", "example:empty_bucket"}},
}
Ore definition
--------------
Used by `minetest.register_ore`.
{
ore_type = "",
-- Supported: "scatter", "sheet", "puff", "blob", "vein", "stratum"
ore = "",
-- Ore node to place
ore_param2 = 0,
-- Param2 to set for ore (e.g. facedir rotation)
wherein = "",
-- Node to place ore in. Multiple are possible by passing a list.
clust_scarcity = 8 * 8 * 8,
-- Ore has a 1 out of clust_scarcity chance of spawning in a node.
-- If the desired average distance between ores is 'd', set this to
-- d * d * d.
clust_num_ores = 8,
-- Number of ores in a cluster
clust_size = 3,
-- Size of the bounding box of the cluster.
-- In this example, there is a 3 * 3 * 3 cluster where 8 out of the 27
-- nodes are coal ore.
y_min = -31000,
y_max = 31000,
-- Lower and upper limits for ore (inclusive)
flags = "",
-- Attributes for the ore generation, see 'Ore attributes' section above
noise_threshold = 0,
-- If noise is above this threshold, ore is placed. Not needed for a
-- uniform distribution.
noise_params = {
offset = 0,
scale = 1,
spread = {x = 100, y = 100, z = 100},
seed = 23,
octaves = 3,
persistence = 0.7
},
-- NoiseParams structure describing one of the perlin noises used for
-- ore distribution.
-- Needed by "sheet", "puff", "blob" and "vein" ores.
-- Omit from "scatter" ore for a uniform ore distribution.
-- Omit from "stratum" ore for a simple horizontal strata from y_min to
-- y_max.
-- Type-specific parameters
-- "sheet"
column_height_min = 1,
column_height_max = 16,
column_midpoint_factor = 0.5,
-- "puff"
np_puff_top = {
offset = 4,
scale = 2,
spread = {x = 100, y = 100, z = 100},
seed = 47,
octaves = 3,
persistence = 0.7
},
np_puff_bottom = {
offset = 4,
scale = 2,
spread = {x = 100, y = 100, z = 100},
seed = 11,
octaves = 3,
persistence = 0.7
},
-- "vein"
random_factor = 1.0,
-- "stratum"
np_stratum_thickness = {
offset = 8,
scale = 4,
spread = {x = 100, y = 100, z = 100},
seed = 17,
octaves = 3,
persistence = 0.7
},
stratum_thickness = 8, -- only used if no noise defined
}
Biome definition
----------------
Used by `minetest.register_biome`.
The maximum number of biomes that can be used is 65535. However, using an
excessive number of biomes will slow down map generation. Depending on desired
performance and computing power the practical limit is much lower.
{
name = "tundra",
node_dust = "default:snow",
-- Node dropped onto upper surface after all else is generated
node_top = "default:dirt_with_snow",
depth_top = 1,
-- Node forming surface layer of biome and thickness of this layer
node_filler = "default:permafrost",
depth_filler = 3,
-- Node forming lower layer of biome and thickness of this layer
node_stone = "default:bluestone",
-- Node that replaces all stone nodes between roughly y_min and y_max.
node_water_top = "default:ice",
depth_water_top = 10,
-- Node forming a surface layer in seawater with the defined thickness
node_water = "",
-- Node that replaces all seawater nodes not in the surface layer
node_river_water = "default:ice",
-- Node that replaces river water in mapgens that use
-- default:river_water
node_riverbed = "default:gravel",
depth_riverbed = 2,
-- Node placed under river water and thickness of this layer
node_cave_liquid = "default:lava_source",
node_cave_liquid = {"default:water_source", "default:lava_source"},
-- Nodes placed inside 50% of the medium size caves.
-- Multiple nodes can be specified, each cave will use a randomly
-- chosen node from the list.
-- If this field is left out or 'nil', cave liquids fall back to
-- classic behavior of lava and water distributed using 3D noise.
-- For no cave liquid, specify "air".
node_dungeon = "default:cobble",
-- Node used for primary dungeon structure.
-- If absent, dungeon nodes fall back to the 'mapgen_cobble' mapgen
-- alias, if that is also absent, dungeon nodes fall back to the biome
-- 'node_stone'.
-- If present, the following two nodes are also used.
node_dungeon_alt = "default:mossycobble",
-- Node used for randomly-distributed alternative structure nodes.
-- If alternative structure nodes are not wanted leave this absent.
node_dungeon_stair = "stairs:stair_cobble",
-- Node used for dungeon stairs.
-- If absent, stairs fall back to 'node_dungeon'.
y_max = 31000,
y_min = 1,
-- Upper and lower limits for biome.
-- Alternatively you can use xyz limits as shown below.
vertical_blend = 8,
-- Vertical distance in nodes above 'y_max' over which the biome will
-- blend with the biome above.
-- Set to 0 for no vertical blend. Defaults to 0.
heat_point = 0,
humidity_point = 50,
-- Characteristic temperature and humidity for the biome.
-- These values create 'biome points' on a voronoi diagram with heat and
-- humidity as axes. The resulting voronoi cells determine the
-- distribution of the biomes.
-- Heat and humidity have average values of 50, vary mostly between
-- 0 and 100 but can exceed these values.
}
Decoration definition
---------------------
{
deco_type = "simple",
-- Type. "simple" or "schematic" supported
place_on = "default:dirt_with_grass",
-- Node (or list of nodes) that the decoration can be placed on
sidelen = 8,
-- Size of the square (X / Z) divisions of the mapchunk being generated.
-- Determines the resolution of noise variation if used.
-- If the chunk size is not evenly divisible by sidelen, sidelen is made
-- equal to the chunk size.
fill_ratio = 0.02,
-- The value determines 'decorations per surface node'.
-- Used only if noise_params is not specified.
-- If >= 10.0 complete coverage is enabled and decoration placement uses
-- a different and much faster method.
noise_params = {
offset = 0,
scale = 0.45,
spread = {x = 100, y = 100, z = 100},
seed = 354,
octaves = 3,
persistence = 0.7,
lacunarity = 2.0,
flags = "absvalue"
},
-- NoiseParams structure describing the perlin noise used for decoration
-- distribution.
-- A noise value is calculated for each square division and determines
-- 'decorations per surface node' within each division.
-- If the noise value >= 10.0 complete coverage is enabled and
-- decoration placement uses a different and much faster method.
y_min = -31000,
y_max = 31000,
-- Lower and upper limits for decoration (inclusive).
-- These parameters refer to the Y co-ordinate of the 'place_on' node.
spawn_by = "default:water",
-- Node (or list of nodes) that the decoration only spawns next to.
-- Checks the 8 neighboring nodes on the same Y, and also the ones
-- at Y+1, excluding both center nodes.
num_spawn_by = 1,
-- Number of spawn_by nodes that must be surrounding the decoration
-- position to occur.
-- If absent or -1, decorations occur next to any nodes.
decoration = "default:grass",
-- The node name used as the decoration.
-- If instead a list of strings, a randomly selected node from the list
-- is placed as the decoration.
height = 1,
-- Decoration height in nodes.
-- If height_max is not 0, this is the lower limit of a randomly
-- selected height.
height_max = 0,
-- Upper limit of the randomly selected height.
-- If absent, the parameter 'height' is used as a constant.
param2 = 0,
-- Param2 value of decoration nodes.
-- If param2_max is not 0, this is the lower limit of a randomly
-- selected param2.
param2_max = 0,
-- Upper limit of the randomly selected param2.
-- If absent, the parameter 'param2' is used as a constant.
place_offset_y = 0,
-- Y offset of the decoration base node relative to the standard base
-- node position.
-- Can be positive or negative. Default is 0.
-- Effect is inverted for "all_ceilings" decorations.
-- Ignored by 'y_min', 'y_max' and 'spawn_by' checks, which always refer
-- to the 'place_on' node.
schematic = "foobar.mts",
-- If schematic is a string, it is the filepath relative to the current
-- working directory of the specified Minetest schematic file.
-- Could also be the ID of a previously registered schematic.
schematic = {
size = {x = 4, y = 6, z = 4},
data = {
{name = "default:cobble", param1 = 255, param2 = 0},
{name = "default:dirt_with_grass", param1 = 255, param2 = 0},
{name = "air", param1 = 255, param2 = 0},
...
},
yslice_prob = {
{ypos = 2, prob = 128},
{ypos = 5, prob = 64},
...
},
},
-- Alternative schematic specification by supplying a table. The fields
-- size and data are mandatory whereas yslice_prob is optional.
-- See 'Schematic specifier' for details.
rotation = "90",
-- Rotation can be "0", "90", "180", "270", or "random"
place_offset_y = 0,
-- If the flag 'place_center_y' is set this parameter is ignored.
-- Y offset of the schematic base node layer relative to the 'place_on'
-- node.
-- Can be positive or negative. Default is 0.
-- Effect is inverted for "all_ceilings" decorations.
-- Ignored by 'y_min', 'y_max' and 'spawn_by' checks, which always refer
-- to the 'place_on' node.
}
Used by `minetest.register_chatcommand`.
Specifies the function to be called and the privileges required when a player
issues the command. A help message that is the concatenation of the params and
description fields is shown when the "/help" chatcommand is issued.
{
params = "",
-- Short parameter description. See the below note.
description = "",
-- General description of the command's purpose.
privs = {},
-- Required privileges to run. See `minetest.check_player_privs()` for
-- the format and see [Privileges] for an overview of privileges.
Example:
{
params = "<name> <privilege>",
Privilege definition
--------------------
Used by `minetest.register_privilege`.
{
description = "",
-- Privilege description
give_to_singleplayer = true,
-- Whether to grant the privilege to singleplayer.
give_to_admin = true,
-- Whether to grant the privilege to the server admin.
-- Uses value of 'give_to_singleplayer' by default.
-- Note that the above two callbacks will be called twice if a player is
-- responsible, once with the player name, and then with a nil player
-- name.
-- Return true in the above callbacks to stop register_on_priv_grant or
-- revoke being called.
}
Used by `minetest.create_detached_inventory`.
{
allow_move = function(inv, from_list, from_index, to_list, to_index, count,
player),
-- Called when a player wants to move items inside the inventory.
-- Return value: number of items allowed to move.
HUD Definition
--------------
Since most values have multiple different functions, please see the
documentation in [HUD] section.
{
hud_elem_type = "image",
-- Type of element, can be "image", "text", "statbar", "inventory",
-- "waypoint", "image_waypoint", "compass" or "minimap"
name = "<name>",
scale = {x = 1, y = 1},
text = "<text>",
text2 = "<text>",
number = 0,
item = 0,
direction = 0,
-- Direction: 0: left-right, 1: right-left, 2: top-bottom, 3: bottom-top
z_index = 0,
-- Z index: lower z-index HUDs are displayed behind higher z-index HUDs
style = 0,
}
Particle definition
-------------------
Used by `minetest.add_particle`.
{
pos = {x=0, y=0, z=0},
velocity = {x=0, y=0, z=0},
acceleration = {x=0, y=0, z=0},
-- Spawn particle at pos with velocity and acceleration
expirationtime = 1,
-- Disappears after expirationtime seconds
size = 1,
-- Scales the visual size of the particle texture.
-- If `node` is set, size can be set to 0 to spawn a randomly-sized
-- particle (just like actual node dig particles).
collisiondetection = false,
-- If true collides with `walkable` nodes and, depending on the
-- `object_collision` field, objects too.
collision_removal = false,
-- If true particle is removed when it collides.
-- Requires collisiondetection = true to have any effect.
object_collision = false,
-- If true particle collides with objects that are defined as
-- `physical = true,` and `collide_with_objects = true,`.
-- Requires collisiondetection = true to have any effect.
vertical = false,
-- If true faces player using y axis only
texture = "image.png",
-- The texture of the particle
-- v5.6.0 and later: also supports the table format described in the
-- following section
playername = "singleplayer",
-- Optional, if specified spawns particle only on the player's client
glow = 0
-- Optional, specify particle self-luminescence in darkness.
-- Values 0-14.
node_tile = 0,
-- Optional, only valid in combination with `node`
-- If set to a valid number 1-6, specifies the tile from which the
-- particle texture is picked.
-- Otherwise, the default behavior is used. (currently: any random tile)
Used by `minetest.add_particlespawner`.
Before v5.6.0, particlespawners used a different syntax and had a more limited set
of features. Definition fields that are the same in both legacy and modern versions
are shown in the next listing, and the fields that are used by legacy versions are
shown separated by a comment; the modern fields are too complex to compactly
describe in this manner and are documented after the listing.
The older syntax can be used in combination with the newer syntax (e.g. having
`minpos`, `maxpos`, and `pos` all set) to support older servers. On newer servers,
the new syntax will override the older syntax; on older servers, the newer syntax
will be ignored.
{
-- Common fields (same name and meaning in both new and legacy syntax)
amount = 1,
-- Number of particles spawned over the time period `time`.
time = 1,
-- Lifespan of spawner in seconds.
-- If time is 0 spawner has infinite lifespan and spawns the `amount` on
-- a per-second basis.
collisiondetection = false,
-- If true collide with `walkable` nodes and, depending on the
-- `object_collision` field, objects too.
collision_removal = false,
-- If true particles are removed when they collide.
-- Requires collisiondetection = true to have any effect.
object_collision = false,
-- If true particles collide with objects that are defined as
-- `physical = true,` and `collide_with_objects = true,`.
-- Requires collisiondetection = true to have any effect.
attached = ObjectRef,
-- If defined, particle positions, velocities and accelerations are
-- relative to this object's position and yaw
vertical = false,
-- If true face player using y axis only
texture = "image.png",
-- The texture of the particle
playername = "singleplayer",
-- Optional, if specified spawns particles only on the player's client
glow = 0,
-- Optional, specify particle self-luminescence in darkness.
-- Values 0-14.
node_tile = 0,
-- Optional, only valid in combination with `node`
-- If set to a valid number 1-6, specifies the tile from which the
-- particle texture is picked.
-- Otherwise, the default behavior is used. (currently: any random tile)
After v5.6.0, spawner properties can be defined in several different ways depending
on the level of control you need. `pos` for instance can be set as a single vector,
in which case all particles will appear at that exact point throughout the lifetime
of the spawner. Alternately, it can be specified as a min-max pair, specifying a
cubic range the particles can appear randomly within. Finally, some properties can
be animated by suffixing their key with `_tween` (e.g. `pos_tween`) and supplying
a tween table.
The following definitions are all equivalent, listed in order of precedence from
lowest (the legacy syntax) to highest (tween tables). If multiple forms of a
property definition are present, the highest-precedence form will be selected
and all lower-precedence fields will be ignored, allowing for graceful
degradation in older clients).
{
-- old syntax
maxpos = {x = 0, y = 0, z = 0},
minpos = {x = 0, y = 0, z = 0},
-- absolute value
pos = 0,
-- all components of every particle's position vector will be set to this
-- value
-- vec3
pos = vector.new(0,0,0),
-- all particles will appear at this exact position throughout the lifetime
-- of the particlespawner
-- vec3 range
pos = {
-- the particle will appear at a position that is picked at random from
-- within a cubic range
min = vector.new(0,0,0),
-- `min` is the minimum value this property will be set to in particles
-- spawned by the generator
max = vector.new(0,0,0),
-- `max` is the minimum value this property will be set to in particles
-- spawned by the generator
bias = 0,
-- when `bias` is 0, all random values are exactly as likely as any
-- other. when it is positive, the higher it is, the more likely values
-- will appear towards the minimum end of the allowed spectrum. when
-- it is negative, the lower it is, the more likely values will appear
-- towards the maximum end of the allowed spectrum. the curve is
-- exponential and there is no particular maximum or minimum value
},
-- tween table
pos_tween = {...},
-- a tween table should consist of a list of frames in the same form as the
-- untweened pos property above, which the engine will interpolate between,
-- and optionally a number of properties that control how the interpolation
-- takes place. currently **only two frames**, the first and the last, are
-- used, but extra frames are accepted for the sake of forward
compatibility.
-- any of the above definition styles can be used here as well in any
combination
-- supported by the property type
pos_tween = {
style = "fwd",
-- linear animation from first to last frame (default)
style = "rev",
-- linear animation from last to first frame
style = "pulse",
-- linear animation from first to last then back to first again
style = "flicker",
-- like "pulse", but slightly randomized to add a bit of stutter
reps = 1,
-- number of times the animation is played over the particle's lifespan
start = 0.0,
-- point in the spawner's lifespan at which the animation begins. 0 is
-- the very beginning, 1 is the very end
-- frames can be defined in a number of different ways, depending on
the
-- underlying type of the property. for now, all but the first and last
-- frame are ignored
-- frames
-- floats
0, 0,
-- vec3s
vector.new(0,0,0),
vector.new(0,0,0),
-- vec3 ranges
{ min = vector.new(0,0,0), max = vector.new(0,0,0), bias = 0 },
{ min = vector.new(0,0,0), max = vector.new(0,0,0), bias = 0 },
-- mixed
0, { min = vector.new(0,0,0), max = vector.new(0,0,0), bias = 0 },
},
}
All of the properties that can be defined in this way are listed in the next
section, along with the datatypes they accept.
### Textures
texture = {
name = "mymod_particle_texture.png",
-- the texture specification string
alpha = 1.0,
-- controls how visible the particle is; at 1.0 the particle is fully
-- visible, at 0, it is completely invisible.
scale = 1,
scale = {x = 1, y = 1},
-- scales the texture onscreen
scale_tween = {
{x = 1, y = 1},
{x = 0, y = 1},
},
-- animates the scale over the particle's lifetime. works like the
-- alpha_tween table, but can accept two-dimensional vectors as well as
-- integer values. the example value would cause the particle to shrink
-- in one dimension over the course of its life until it disappears
blend = "alpha",
-- (default) blends transparent pixels with those they are drawn atop
-- according to the alpha channel of the source texture. useful for
-- e.g. material objects like rocks, dirt, smoke, or node chunks
blend = "add",
-- adds the value of pixels to those underneath them, modulo the sources
-- alpha channel. useful for e.g. bright light effects like sparks or fire
blend = "screen",
-- like "add" but less bright. useful for subtler light effects. note that
-- this is NOT formally equivalent to the "screen" effect used in image
-- editors and compositors, as it does not respect the alpha channel of
-- of the image being blended
blend = "sub",
-- the inverse of "add"; the value of the source pixel is subtracted from
-- the pixel underneath it. a white pixel will turn whatever is underneath
-- it black; a black pixel will be "transparent". useful for creating
-- darkening effects
texpool = {
"mymod_particle_texture.png";
{ name = "mymod_spark.png", fade = "out" },
{
name = "mymod_dust.png",
alpha = 0.3,
scale = 1.5,
animation = {
type = "vertical_frames",
aspect_w = 16, aspect_h = 16,
length = 3,
-- the animation lasts for 3s and then repeats
length = -3,
-- repeat the animation three times over the particle's lifetime
-- (post-v5.6.0 clients only)
},
},
}
While animated particlespawner values vary over the course of the particlespawner's
lifetime, animated texture properties vary over the lifespans of the individual
particles spawned with that texture. So a particle with the texture property
alpha_tween = {
0.0, 1.0,
style = "pulse",
reps = 4,
}
would be invisible at its spawning, pulse visible four times throughout its
lifespan, and then vanish again before expiring.
`HTTPRequest` definition
------------------------
{
url = "http://example.org",
timeout = 10,
-- Timeout for request to be completed in seconds. Default depends on
engine settings.
user_agent = "ExampleUserAgent",
-- Optional, if specified replaces the default minetest user agent with
-- given string
`HTTPRequestResult` definition
------------------------------
{
completed = true,
-- If true, the request has finished (either succeeded, failed or timed
-- out)
succeeded = true,
-- If true, the request was successful
timeout = false,
-- If true, the request timed out
code = 200,
-- HTTP status code
data = "response"
}
Used by `minetest.register_authentication_handler`.
{
get_auth = function(name),
-- Get authentication data for existing player `name` (`nil` if player
-- doesn't exist).
-- Returns following structure:
-- `{password=<string>, privileges=<table>, last_login=<number or nil>}`
delete_auth = function(name),
-- Delete auth data of player `name`.
-- Returns boolean indicating success (false if player is nonexistent).
reload = function(),
-- Reload authentication data from the storage location.
-- Returns boolean indicating success.
record_login = function(name),
-- Called when player joins, used for keeping track of last_login
iterate = function(),
-- Returns an iterator (use with `for` loops) for all player names
-- currently in the auth database
}
Bit Library
-----------
Error Handling
--------------
When an error occurs that is not caught, Minetest calls the function
`minetest.error_handler` with the error object as its first argument. The second
argument is the stack level where the error occurred. The return value is the
error string that should be shown. By default this is a backtrace from
`debug.traceback`. If the error object is not a string, it is first converted
with `tostring` before being displayed. This means that you can use tables as
error objects so long as you give them `__tostring` metamethods.
You can override `minetest.error_handler`. You should call the previous handler
with the correct stack level in your implementation.