Particles: Make collision with objects optional (#7682)
[oweals/minetest.git] / doc / client_lua_api.txt
1 Minetest Lua Client Modding API Reference 5.0.0
2 ================================================
3 * More information at <http://www.minetest.net/>
4 * Developer Wiki: <http://dev.minetest.net/>
5
6 Introduction
7 ------------
8
9 ** WARNING: The client API is currently unstable, and may break/change without warning. **
10
11 Content and functionality can be added to Minetest 0.4.15-dev+ by using Lua
12 scripting in run-time loaded mods.
13
14 A mod is a self-contained bunch of scripts, textures and other related
15 things that is loaded by and interfaces with Minetest.
16
17 Transferring client-sided mods from the server to the client is planned, but not implemented yet.
18
19 If you see a deficiency in the API, feel free to attempt to add the
20 functionality in the engine and API. You can send such improvements as
21 source code patches on GitHub (https://github.com/minetest/minetest).
22
23 Programming in Lua
24 ------------------
25 If you have any difficulty in understanding this, please read
26 [Programming in Lua](http://www.lua.org/pil/).
27
28 Startup
29 -------
30 Mods are loaded during client startup from the mod load paths by running
31 the `init.lua` scripts in a shared environment.
32
33 Paths
34 -----
35 * `RUN_IN_PLACE=1` (Windows release, local build)
36     *  `$path_user`:
37         * Linux: `<build directory>`
38         * Windows: `<build directory>`
39     * `$path_share`
40         * Linux: `<build directory>`
41         * Windows:  `<build directory>`
42 * `RUN_IN_PLACE=0`: (Linux release)
43     * `$path_share`
44         * Linux: `/usr/share/minetest`
45         * Windows: `<install directory>/minetest-0.4.x`
46     * `$path_user`:
47         * Linux: `$HOME/.minetest`
48         * Windows: `C:/users/<user>/AppData/minetest` (maybe)
49
50 Mod load path
51 -------------
52 Generic:
53
54 * `$path_share/clientmods/`
55 * `$path_user/clientmods/` (User-installed mods)
56
57 In a run-in-place version (e.g. the distributed windows version):
58
59 * `minetest-0.4.x/clientmods/` (User-installed mods)
60
61 On an installed version on Linux:
62
63 * `/usr/share/minetest/clientmods/`
64 * `$HOME/.minetest/clientmods/` (User-installed mods)
65
66 Modpack support
67 ----------------
68 **NOTE: Not implemented yet.**
69
70 Mods can be put in a subdirectory, if the parent directory, which otherwise
71 should be a mod, contains a file named `modpack.txt`. This file shall be
72 empty, except for lines starting with `#`, which are comments.
73
74 Mod directory structure
75 ------------------------
76
77     clientmods
78     ├── modname
79     |   ├── depends.txt
80     |   ├── init.lua
81     └── another
82
83 ### modname
84 The location of this directory.
85
86 ### depends.txt
87 List of mods that have to be loaded before loading this mod.
88
89 A single line contains a single modname.
90
91 Optional dependencies can be defined by appending a question mark
92 to a single modname. Their meaning is that if the specified mod
93 is missing, that does not prevent this mod from being loaded.
94
95 ### init.lua
96 The main Lua script. Running this script should register everything it
97 wants to register. Subsequent execution depends on minetest calling the
98 registered callbacks.
99
100 `minetest.setting_get(name)` and `minetest.setting_getbool(name)` can be used
101 to read custom or existing settings at load time, if necessary.
102
103 ### `sounds`
104 Media files (sounds) that will be transferred to the
105 client and will be available for use by the mod.
106
107 Naming convention for registered textual names
108 ----------------------------------------------
109 Registered names should generally be in this format:
110
111     "modname:<whatever>" (<whatever> can have characters a-zA-Z0-9_)
112
113 This is to prevent conflicting names from corrupting maps and is
114 enforced by the mod loader.
115
116 ### Example
117 In the mod `experimental`, there is the ideal item/node/entity name `tnt`.
118 So the name should be `experimental:tnt`.
119
120 Enforcement can be overridden by prefixing the name with `:`. This can
121 be used for overriding the registrations of some other mod.
122
123 Example: Any mod can redefine `experimental:tnt` by using the name
124
125     :experimental:tnt
126
127 when registering it.
128 (also that mod is required to have `experimental` as a dependency)
129
130 The `:` prefix can also be used for maintaining backwards compatibility.
131
132 Sounds
133 ------
134 **NOTE: max_hear_distance and connecting to objects is not implemented.**
135
136 Only Ogg Vorbis files are supported.
137
138 For positional playing of sounds, only single-channel (mono) files are
139 supported. Otherwise OpenAL will play them non-positionally.
140
141 Mods should generally prefix their sounds with `modname_`, e.g. given
142 the mod name "`foomod`", a sound could be called:
143
144     foomod_foosound.ogg
145
146 Sounds are referred to by their name with a dot, a single digit and the
147 file extension stripped out. When a sound is played, the actual sound file
148 is chosen randomly from the matching sounds.
149
150 When playing the sound `foomod_foosound`, the sound is chosen randomly
151 from the available ones of the following files:
152
153 * `foomod_foosound.ogg`
154 * `foomod_foosound.0.ogg`
155 * `foomod_foosound.1.ogg`
156 * (...)
157 * `foomod_foosound.9.ogg`
158
159 Examples of sound parameter tables:
160
161     -- Play locationless
162     {
163         gain = 1.0, -- default
164     }
165     -- Play locationless, looped
166     {
167         gain = 1.0, -- default
168         loop = true,
169     }
170     -- Play in a location
171     {
172         pos = {x = 1, y = 2, z = 3},
173         gain = 1.0, -- default
174         max_hear_distance = 32, -- default, uses an euclidean metric
175     }
176     -- Play connected to an object, looped
177     {
178         object = <an ObjectRef>,
179         gain = 1.0, -- default
180         max_hear_distance = 32, -- default, uses an euclidean metric
181         loop = true,
182     }
183
184 Looped sounds must either be connected to an object or played locationless.
185
186 ### SimpleSoundSpec
187 * e.g. `""`
188 * e.g. `"default_place_node"`
189 * e.g. `{}`
190 * e.g. `{name = "default_place_node"}`
191 * e.g. `{name = "default_place_node", gain = 1.0}`
192
193 Representations of simple things
194 --------------------------------
195
196 ### Position/vector
197
198     {x=num, y=num, z=num}
199
200 For helper functions see "Vector helpers".
201
202 ### pointed_thing
203 * `{type="nothing"}`
204 * `{type="node", under=pos, above=pos}`
205 * `{type="object", id=ObjectID}`
206
207 Flag Specifier Format
208 ---------------------
209 Flags using the standardized flag specifier format can be specified in either of
210 two ways, by string or table.
211
212 The string format is a comma-delimited set of flag names; whitespace and
213 unrecognized flag fields are ignored. Specifying a flag in the string sets the
214 flag, and specifying a flag prefixed by the string `"no"` explicitly
215 clears the flag from whatever the default may be.
216
217 In addition to the standard string flag format, the schematic flags field can
218 also be a table of flag names to boolean values representing whether or not the
219 flag is set. Additionally, if a field with the flag name prefixed with `"no"`
220 is present, mapped to a boolean of any value, the specified flag is unset.
221
222 E.g. A flag field of value
223
224     {place_center_x = true, place_center_y=false, place_center_z=true}
225
226 is equivalent to
227
228     {place_center_x = true, noplace_center_y=true, place_center_z=true}
229
230 which is equivalent to
231
232     "place_center_x, noplace_center_y, place_center_z"
233
234 or even
235
236     "place_center_x, place_center_z"
237
238 since, by default, no schematic attributes are set.
239
240 Formspec
241 --------
242 Formspec defines a menu. It is a string, with a somewhat strange format.
243
244 Spaces and newlines can be inserted between the blocks, as is used in the
245 examples.
246
247 ### Examples
248
249 #### Chest
250
251     size[8,9]
252     list[context;main;0,0;8,4;]
253     list[current_player;main;0,5;8,4;]
254
255 #### Furnace
256
257     size[8,9]
258     list[context;fuel;2,3;1,1;]
259     list[context;src;2,1;1,1;]
260     list[context;dst;5,1;2,2;]
261     list[current_player;main;0,5;8,4;]
262
263 #### Minecraft-like player inventory
264
265     size[8,7.5]
266     image[1,0.6;1,2;player.png]
267     list[current_player;main;0,3.5;8,4;]
268     list[current_player;craft;3,0;3,3;]
269     list[current_player;craftpreview;7,1;1,1;]
270
271 ### Elements
272
273 #### `size[<W>,<H>,<fixed_size>]`
274 * Define the size of the menu in inventory slots
275 * `fixed_size`: `true`/`false` (optional)
276 * deprecated: `invsize[<W>,<H>;]`
277
278 #### `container[<X>,<Y>]`
279 * Start of a container block, moves all physical elements in the container by (X, Y)
280 * Must have matching container_end
281 * Containers can be nested, in which case the offsets are added
282   (child containers are relative to parent containers)
283
284 #### `container_end[]`
285 * End of a container, following elements are no longer relative to this container
286
287 #### `list[<inventory location>;<list name>;<X>,<Y>;<W>,<H>;]`
288 * Show an inventory list
289
290 #### `list[<inventory location>;<list name>;<X>,<Y>;<W>,<H>;<starting item index>]`
291 * Show an inventory list
292
293 #### `listring[<inventory location>;<list name>]`
294 * Allows to create a ring of inventory lists
295 * Shift-clicking on items in one element of the ring
296   will send them to the next inventory list inside the ring
297 * The first occurrence of an element inside the ring will
298   determine the inventory where items will be sent to
299
300 #### `listring[]`
301 * Shorthand for doing `listring[<inventory location>;<list name>]`
302   for the last two inventory lists added by list[...]
303
304 #### `listcolors[<slot_bg_normal>;<slot_bg_hover>]`
305 * Sets background color of slots as `ColorString`
306 * Sets background color of slots on mouse hovering
307
308 #### `listcolors[<slot_bg_normal>;<slot_bg_hover>;<slot_border>]`
309 * Sets background color of slots as `ColorString`
310 * Sets background color of slots on mouse hovering
311 * Sets color of slots border
312
313 #### `listcolors[<slot_bg_normal>;<slot_bg_hover>;<slot_border>;<tooltip_bgcolor>;<tooltip_fontcolor>]`
314 * Sets background color of slots as `ColorString`
315 * Sets background color of slots on mouse hovering
316 * Sets color of slots border
317 * Sets default background color of tooltips
318 * Sets default font color of tooltips
319
320 #### `tooltip[<gui_element_name>;<tooltip_text>;<bgcolor>,<fontcolor>]`
321 * Adds tooltip for an element
322 * `<bgcolor>` tooltip background color as `ColorString` (optional)
323 * `<fontcolor>` tooltip font color as `ColorString` (optional)
324
325 #### `image[<X>,<Y>;<W>,<H>;<texture name>]`
326 * Show an image
327 * Position and size units are inventory slots
328
329 #### `item_image[<X>,<Y>;<W>,<H>;<item name>]`
330 * Show an inventory image of registered item/node
331 * Position and size units are inventory slots
332
333 #### `bgcolor[<color>;<fullscreen>]`
334 * Sets background color of formspec as `ColorString`
335 * If `true`, the background color is drawn fullscreen (does not effect the size of the formspec)
336
337 #### `background[<X>,<Y>;<W>,<H>;<texture name>]`
338 * Use a background. Inventory rectangles are not drawn then.
339 * Position and size units are inventory slots
340 * Example for formspec 8x4 in 16x resolution: image shall be sized
341   8 times 16px  times  4 times 16px.
342
343 #### `background[<X>,<Y>;<W>,<H>;<texture name>;<auto_clip>]`
344 * Use a background. Inventory rectangles are not drawn then.
345 * Position and size units are inventory slots
346 * Example for formspec 8x4 in 16x resolution:
347   image shall be sized 8 times 16px  times  4 times 16px
348 * If `true` the background is clipped to formspec size
349   (`x` and `y` are used as offset values, `w` and `h` are ignored)
350
351 #### `pwdfield[<X>,<Y>;<W>,<H>;<name>;<label>]`
352 * Textual password style field; will be sent to server when a button is clicked
353 * When enter is pressed in field, fields.key_enter_field will be sent with the name
354   of this field.
355 * `x` and `y` position the field relative to the top left of the menu
356 * `w` and `h` are the size of the field
357 * Fields are a set height, but will be vertically centred on `h`
358 * Position and size units are inventory slots
359 * `name` is the name of the field as returned in fields to `on_receive_fields`
360 * `label`, if not blank, will be text printed on the top left above the field
361 * See field_close_on_enter to stop enter closing the formspec
362
363 #### `field[<X>,<Y>;<W>,<H>;<name>;<label>;<default>]`
364 * Textual field; will be sent to server when a button is clicked
365 * When enter is pressed in field, fields.key_enter_field will be sent with the name
366   of this field.
367 * `x` and `y` position the field relative to the top left of the menu
368 * `w` and `h` are the size of the field
369 * Fields are a set height, but will be vertically centred on `h`
370 * Position and size units are inventory slots
371 * `name` is the name of the field as returned in fields to `on_receive_fields`
372 * `label`, if not blank, will be text printed on the top left above the field
373 * `default` is the default value of the field
374     * `default` may contain variable references such as `${text}'` which
375       will fill the value from the metadata value `text`
376     * **Note**: no extra text or more than a single variable is supported ATM.
377 * See field_close_on_enter to stop enter closing the formspec
378
379 #### `field[<name>;<label>;<default>]`
380 * As above, but without position/size units
381 * When enter is pressed in field, fields.key_enter_field will be sent with the name
382   of this field.
383 * Special field for creating simple forms, such as sign text input
384 * Must be used without a `size[]` element
385 * A "Proceed" button will be added automatically
386 * See field_close_on_enter to stop enter closing the formspec
387
388 #### `field_close_on_enter[<name>;<close_on_enter>]`
389 * <name> is the name of the field
390 * if <close_on_enter> is false, pressing enter in the field will submit the form but not close it
391 * defaults to true when not specified (ie: no tag for a field)
392
393 #### `textarea[<X>,<Y>;<W>,<H>;<name>;<label>;<default>]`
394 * Same as fields above, but with multi-line input
395
396 #### `label[<X>,<Y>;<label>]`
397 * `x` and `y` work as per field
398 * `label` is the text on the label
399 * Position and size units are inventory slots
400
401 #### `vertlabel[<X>,<Y>;<label>]`
402 * Textual label drawn vertically
403 * `x` and `y` work as per field
404 * `label` is the text on the label
405 * Position and size units are inventory slots
406
407 #### `button[<X>,<Y>;<W>,<H>;<name>;<label>]`
408 * Clickable button. When clicked, fields will be sent.
409 * `x`, `y` and `name` work as per field
410 * `w` and `h` are the size of the button
411 * Fixed button height. It will be vertically centred on `h`
412 * `label` is the text on the button
413 * Position and size units are inventory slots
414
415 #### `image_button[<X>,<Y>;<W>,<H>;<texture name>;<name>;<label>]`
416 * `x`, `y`, `w`, `h`, and `name` work as per button
417 * `texture name` is the filename of an image
418 * Position and size units are inventory slots
419
420 #### `image_button[<X>,<Y>;<W>,<H>;<texture name>;<name>;<label>;<noclip>;<drawborder>;<pressed texture name>]`
421 * `x`, `y`, `w`, `h`, and `name` work as per button
422 * `texture name` is the filename of an image
423 * Position and size units are inventory slots
424 * `noclip=true` means the image button doesn't need to be within specified formsize
425 * `drawborder`: draw button border or not
426 * `pressed texture name` is the filename of an image on pressed state
427
428 #### `item_image_button[<X>,<Y>;<W>,<H>;<item name>;<name>;<label>]`
429 * `x`, `y`, `w`, `h`, `name` and `label` work as per button
430 * `item name` is the registered name of an item/node,
431    tooltip will be made out of its description
432    to override it use tooltip element
433 * Position and size units are inventory slots
434
435 #### `button_exit[<X>,<Y>;<W>,<H>;<name>;<label>]`
436 * When clicked, fields will be sent and the form will quit.
437
438 #### `image_button_exit[<X>,<Y>;<W>,<H>;<texture name>;<name>;<label>]`
439 * When clicked, fields will be sent and the form will quit.
440
441 #### `textlist[<X>,<Y>;<W>,<H>;<name>;<listelem 1>,<listelem 2>,...,<listelem n>]`
442 * Scrollable item list showing arbitrary text elements
443 * `x` and `y` position the itemlist relative to the top left of the menu
444 * `w` and `h` are the size of the itemlist
445 * `name` fieldname sent to server on doubleclick value is current selected element
446 * `listelements` can be prepended by #color in hexadecimal format RRGGBB (only),
447      * if you want a listelement to start with "#" write "##".
448
449 #### `textlist[<X>,<Y>;<W>,<H>;<name>;<listelem 1>,<listelem 2>,...,<listelem n>;<selected idx>;<transparent>]`
450 * Scrollable itemlist showing arbitrary text elements
451 * `x` and `y` position the item list relative to the top left of the menu
452 * `w` and `h` are the size of the item list
453 * `name` fieldname sent to server on doubleclick value is current selected element
454 * `listelements` can be prepended by #RRGGBB (only) in hexadecimal format
455      * if you want a listelement to start with "#" write "##"
456 * Index to be selected within textlist
457 * `true`/`false`: draw transparent background
458 * See also `minetest.explode_textlist_event` (main menu: `engine.explode_textlist_event`)
459
460 #### `tabheader[<X>,<Y>;<name>;<caption 1>,<caption 2>,...,<caption n>;<current_tab>;<transparent>;<draw_border>]`
461 * Show a tab**header** at specific position (ignores formsize)
462 * `x` and `y` position the itemlist relative to the top left of the menu
463 * `name` fieldname data is transferred to Lua
464 * `caption 1`...: name shown on top of tab
465 * `current_tab`: index of selected tab 1...
466 * `transparent` (optional): show transparent
467 * `draw_border` (optional): draw border
468
469 #### `box[<X>,<Y>;<W>,<H>;<color>]`
470 * Simple colored semitransparent box
471 * `x` and `y` position the box relative to the top left of the menu
472 * `w` and `h` are the size of box
473 * `color` is color specified as a `ColorString`
474
475 #### `dropdown[<X>,<Y>;<W>;<name>;<item 1>,<item 2>, ...,<item n>;<selected idx>]`
476 * Show a dropdown field
477 * **Important note**: There are two different operation modes:
478      1. handle directly on change (only changed dropdown is submitted)
479      2. read the value on pressing a button (all dropdown values are available)
480 * `x` and `y` position of dropdown
481 * Width of dropdown
482 * Fieldname data is transferred to Lua
483 * Items to be shown in dropdown
484 * Index of currently selected dropdown item
485
486 #### `checkbox[<X>,<Y>;<name>;<label>;<selected>]`
487 * Show a checkbox
488 * `x` and `y`: position of checkbox
489 * `name` fieldname data is transferred to Lua
490 * `label` to be shown left of checkbox
491 * `selected` (optional): `true`/`false`
492
493 #### `scrollbar[<X>,<Y>;<W>,<H>;<orientation>;<name>;<value>]`
494 * Show a scrollbar
495 * There are two ways to use it:
496      1. handle the changed event (only changed scrollbar is available)
497      2. read the value on pressing a button (all scrollbars are available)
498 * `x` and `y`: position of trackbar
499 * `w` and `h`: width and height
500 * `orientation`:  `vertical`/`horizontal`
501 * Fieldname data is transferred to Lua
502 * Value this trackbar is set to (`0`-`1000`)
503 * See also `minetest.explode_scrollbar_event` (main menu: `engine.explode_scrollbar_event`)
504
505 #### `table[<X>,<Y>;<W>,<H>;<name>;<cell 1>,<cell 2>,...,<cell n>;<selected idx>]`
506 * Show scrollable table using options defined by the previous `tableoptions[]`
507 * Displays cells as defined by the previous `tablecolumns[]`
508 * `x` and `y`: position the itemlist relative to the top left of the menu
509 * `w` and `h` are the size of the itemlist
510 * `name`: fieldname sent to server on row select or doubleclick
511 * `cell 1`...`cell n`: cell contents given in row-major order
512 * `selected idx`: index of row to be selected within table (first row = `1`)
513 * See also `minetest.explode_table_event` (main menu: `engine.explode_table_event`)
514
515 #### `tableoptions[<opt 1>;<opt 2>;...]`
516 * Sets options for `table[]`
517 * `color=#RRGGBB`
518      * default text color (`ColorString`), defaults to `#FFFFFF`
519 * `background=#RRGGBB`
520      * table background color (`ColorString`), defaults to `#000000`
521 * `border=<true/false>`
522      * should the table be drawn with a border? (default: `true`)
523 * `highlight=#RRGGBB`
524      * highlight background color (`ColorString`), defaults to `#466432`
525 * `highlight_text=#RRGGBB`
526      * highlight text color (`ColorString`), defaults to `#FFFFFF`
527 * `opendepth=<value>`
528      * all subtrees up to `depth < value` are open (default value = `0`)
529      * only useful when there is a column of type "tree"
530
531 #### `tablecolumns[<type 1>,<opt 1a>,<opt 1b>,...;<type 2>,<opt 2a>,<opt 2b>;...]`
532 * Sets columns for `table[]`
533 * Types: `text`, `image`, `color`, `indent`, `tree`
534     * `text`:   show cell contents as text
535     * `image`:  cell contents are an image index, use column options to define images
536     * `color`:   cell contents are a ColorString and define color of following cell
537     * `indent`: cell contents are a number and define indentation of following cell
538     * `tree`:   same as indent, but user can open and close subtrees (treeview-like)
539 * Column options:
540     * `align=<value>`
541         * for `text` and `image`: content alignment within cells.
542           Available values: `left` (default), `center`, `right`, `inline`
543     * `width=<value>`
544         * for `text` and `image`: minimum width in em (default: `0`)
545         * for `indent` and `tree`: indent width in em (default: `1.5`)
546     * `padding=<value>`: padding left of the column, in em (default `0.5`).
547       Exception: defaults to 0 for indent columns
548     * `tooltip=<value>`: tooltip text (default: empty)
549     * `image` column options:
550         * `0=<value>` sets image for image index 0
551         * `1=<value>` sets image for image index 1
552         * `2=<value>` sets image for image index 2
553         * and so on; defined indices need not be contiguous empty or
554           non-numeric cells are treated as `0`.
555     * `color` column options:
556         * `span=<value>`: number of following columns to affect (default: infinite)
557
558 **Note**: do _not_ use a element name starting with `key_`; those names are reserved to
559 pass key press events to formspec!
560
561 Spatial Vectors
562 ---------------
563 * `vector.new(a[, b, c])`: returns a vector:
564     * A copy of `a` if `a` is a vector.
565     * `{x = a, y = b, z = c}`, if all `a, b, c` are defined
566 * `vector.direction(p1, p2)`: returns a vector
567 * `vector.distance(p1, p2)`: returns a number
568 * `vector.length(v)`: returns a number
569 * `vector.normalize(v)`: returns a vector
570 * `vector.floor(v)`: returns a vector, each dimension rounded down
571 * `vector.round(v)`: returns a vector, each dimension rounded to nearest int
572 * `vector.apply(v, func)`: returns a vector
573 * `vector.equals(v1, v2)`: returns a boolean
574
575 For the following functions `x` can be either a vector or a number:
576
577 * `vector.add(v, x)`: returns a vector
578 * `vector.subtract(v, x)`: returns a vector
579 * `vector.multiply(v, x)`: returns a scaled vector or Schur product
580 * `vector.divide(v, x)`: returns a scaled vector or Schur quotient
581
582 Helper functions
583 ----------------
584 * `dump2(obj, name="_", dumped={})`
585      * Return object serialized as a string, handles reference loops
586 * `dump(obj, dumped={})`
587     * Return object serialized as a string
588 * `math.hypot(x, y)`
589     * Get the hypotenuse of a triangle with legs x and y.
590       Useful for distance calculation.
591 * `math.sign(x, tolerance)`
592     * Get the sign of a number.
593       Optional: Also returns `0` when the absolute value is within the tolerance (default: `0`)
594 * `string.split(str, separator=",", include_empty=false, max_splits=-1, sep_is_pattern=false)`
595     * If `max_splits` is negative, do not limit splits.
596     * `sep_is_pattern` specifies if separator is a plain string or a pattern (regex).
597     * e.g. `string:split("a,b", ",") == {"a","b"}`
598 * `string:trim()`
599     * e.g. `string.trim("\n \t\tfoo bar\t ") == "foo bar"`
600 * `minetest.wrap_text(str, limit)`: returns a string
601     * Adds new lines to the string to keep it within the specified character limit
602     * limit: Maximal amount of characters in one line
603 * `minetest.pos_to_string({x=X,y=Y,z=Z}, decimal_places))`: returns string `"(X,Y,Z)"`
604     * Convert position to a printable string
605       Optional: 'decimal_places' will round the x, y and z of the pos to the given decimal place.
606 * `minetest.string_to_pos(string)`: returns a position
607     * Same but in reverse. Returns `nil` if the string can't be parsed to a position.
608 * `minetest.string_to_area("(X1, Y1, Z1) (X2, Y2, Z2)")`: returns two positions
609     * Converts a string representing an area box into two positions
610 * `minetest.is_yes(arg)`
611     * returns whether `arg` can be interpreted as yes
612 * `minetest.is_nan(arg)`
613     * returns true true when the passed number represents NaN.
614 * `table.copy(table)`: returns a table
615     * returns a deep copy of `table`
616
617 Minetest namespace reference
618 ------------------------------
619
620 ### Utilities
621
622 * `minetest.get_current_modname()`: returns the currently loading mod's name, when we are loading a mod
623 * `minetest.get_language()`: returns the currently set gettext language.
624 * `minetest.get_version()`: returns a table containing components of the
625    engine version.  Components:
626     * `project`: Name of the project, eg, "Minetest"
627     * `string`: Simple version, eg, "1.2.3-dev"
628     * `hash`: Full git version (only set if available), eg, "1.2.3-dev-01234567-dirty"
629   Use this for informational purposes only. The information in the returned
630   table does not represent the capabilities of the engine, nor is it
631   reliable or verifiable. Compatible forks will have a different name and
632   version entirely. To check for the presence of engine features, test
633   whether the functions exported by the wanted features exist. For example:
634   `if minetest.check_for_falling then ... end`.
635 * `minetest.sha1(data, [raw])`: returns the sha1 hash of data
636     * `data`: string of data to hash
637     * `raw`: return raw bytes instead of hex digits, default: false
638
639 ### Logging
640 * `minetest.debug(...)`
641     * Equivalent to `minetest.log(table.concat({...}, "\t"))`
642 * `minetest.log([level,] text)`
643     * `level` is one of `"none"`, `"error"`, `"warning"`, `"action"`,
644       `"info"`, or `"verbose"`.  Default is `"none"`.
645
646 ### Global callback registration functions
647 Call these functions only at load time!
648
649 * `minetest.register_globalstep(func(dtime))`
650     * Called every client environment step, usually interval of 0.1s
651 * `minetest.register_on_mods_loaded(func())`
652     * Called just after mods have finished loading.
653 * `minetest.register_on_shutdown(func())`
654     * Called before client shutdown
655     * **Warning**: If the client terminates abnormally (i.e. crashes), the registered
656       callbacks **will likely not be run**. Data should be saved at
657       semi-frequent intervals as well as on server shutdown.
658 * `minetest.register_on_receiving_chat_message(func(message))`
659     * Called always when a client receive a message
660     * Return `true` to mark the message as handled, which means that it will not be shown to chat
661 * `minetest.register_on_sending_chat_message(func(message))`
662     * Called always when a client send a message from chat
663     * Return `true` to mark the message as handled, which means that it will not be sent to server
664 * `minetest.register_chatcommand(cmd, chatcommand definition)`
665     * Adds definition to minetest.registered_chatcommands
666 * `minetest.unregister_chatcommand(name)`
667     * Unregisters a chatcommands registered with register_chatcommand.
668 * `minetest.register_on_death(func())`
669     * Called when the local player dies
670 * `minetest.register_on_hp_modification(func(hp))`
671     * Called when server modified player's HP
672 * `minetest.register_on_damage_taken(func(hp))`
673     * Called when the local player take damages
674 * `minetest.register_on_formspec_input(func(formname, fields))`
675     * Called when a button is pressed in the local player's inventory form
676     * Newest functions are called first
677     * If function returns `true`, remaining functions are not called
678 * `minetest.register_on_dignode(func(pos, node))`
679     * Called when the local player digs a node
680     * Newest functions are called first
681     * If any function returns true, the node isn't dug
682 * `minetest.register_on_punchnode(func(pos, node))`
683     * Called when the local player punches a node
684     * Newest functions are called first
685     * If any function returns true, the punch is ignored
686 * `minetest.register_on_placenode(function(pointed_thing, node))`
687     * Called when a node has been placed
688 * `minetest.register_on_item_use(func(item, pointed_thing))`
689     * Called when the local player uses an item.
690     * Newest functions are called first.
691     * If any function returns true, the item use is not sent to server.
692 * `minetest.register_on_modchannel_message(func(channel_name, sender, message))`
693     * Called when an incoming mod channel message is received
694     * You must have joined some channels before, and server must acknowledge the
695       join request.
696     * If message comes from a server mod, `sender` field is an empty string.
697 * `minetest.register_on_modchannel_signal(func(channel_name, signal))`
698     * Called when a valid incoming mod channel signal is received
699     * Signal id permit to react to server mod channel events
700     * Possible values are:
701       0: join_ok
702       1: join_failed
703       2: leave_ok
704       3: leave_failed
705       4: event_on_not_joined_channel
706       5: state_changed
707 * `minetest.register_on_inventory_open(func(inventory))`
708     * Called when the local player open inventory
709     * Newest functions are called first
710     * If any function returns true, inventory doesn't open
711 ### Sounds
712 * `minetest.sound_play(spec, parameters)`: returns a handle
713     * `spec` is a `SimpleSoundSpec`
714     * `parameters` is a sound parameter table
715 * `minetest.sound_stop(handle)`
716
717 ### Timing
718 * `minetest.after(time, func, ...)`
719     * Call the function `func` after `time` seconds, may be fractional
720     * Optional: Variable number of arguments that are passed to `func`
721 * `minetest.get_us_time()`
722     * Returns time with microsecond precision. May not return wall time.
723 * `minetest.get_day_count()`
724     * Returns number days elapsed since world was created, accounting for time changes.
725 * `minetest.get_timeofday()`
726     * Returns the time of day: `0` for midnight, `0.5` for midday
727
728 ### Map
729 * `minetest.get_node_or_nil(pos)`
730     * Returns the node at the given position as table in the format
731       `{name="node_name", param1=0, param2=0}`, returns `nil`
732       for unloaded areas or flavor limited areas.
733 * `minetest.find_node_near(pos, radius, nodenames, [search_center])`: returns pos or `nil`
734     * `radius`: using a maximum metric
735     * `nodenames`: e.g. `{"ignore", "group:tree"}` or `"default:dirt"`
736     * `search_center` is an optional boolean (default: `false`)
737       If true `pos` is also checked for the nodes
738 * `minetest.get_meta(pos)`
739     * Get a `NodeMetaRef` at that position
740 * `minetest.get_node_level(pos)`
741     * get level of leveled node (water, snow)
742 * `minetest.get_node_max_level(pos)`
743     * get max available level for leveled node
744
745 ### Player
746 * `minetest.get_wielded_item()`
747     * Returns the itemstack the local player is holding
748 * `minetest.send_chat_message(message)`
749     * Act as if `message` was typed by the player into the terminal.
750 * `minetest.run_server_chatcommand(cmd, param)`
751     * Alias for `minetest.send_chat_message("/" .. cmd .. " " .. param)`
752 * `minetest.clear_out_chat_queue()`
753     * Clears the out chat queue
754 * `minetest.localplayer`
755     * Reference to the LocalPlayer object. See [`LocalPlayer`](#localplayer) class reference for methods.
756
757 ### Privileges
758 * `minetest.get_privilege_list()`
759     * Returns a list of privileges the current player has in the format `{priv1=true,...}`
760 * `minetest.string_to_privs(str)`: returns `{priv1=true,...}`
761 * `minetest.privs_to_string(privs)`: returns `"priv1,priv2,..."`
762     * Convert between two privilege representations
763
764 ### Client Environment
765 * `minetest.get_player_names()`
766     * Returns list of player names on server
767 * `minetest.disconnect()`
768     * Disconnect from the server and exit to main menu.
769     * Returns `false` if the client is already disconnecting otherwise returns `true`.
770 * `minetest.get_server_info()`
771     * Returns [server info](#server-info).
772 * `minetest.send_respawn()`
773     * Sends a respawn request to the server.
774
775 ### Storage API
776 * `minetest.get_mod_storage()`:
777     * returns reference to mod private `StorageRef`
778     * must be called during mod load time
779
780 ### Mod channels
781 ![Mod channels communication scheme](docs/mod channels.png)
782
783 * `minetest.mod_channel_join(channel_name)`
784     * Client joins channel `channel_name`, and creates it, if necessary. You
785       should listen from incoming messages with `minetest.register_on_modchannel_message`
786       call to receive incoming messages. Warning, this function is asynchronous.
787
788 ### Particles
789 * `minetest.add_particle(particle definition)`
790
791 * `minetest.add_particlespawner(particlespawner definition)`
792     * Add a `ParticleSpawner`, an object that spawns an amount of particles over `time` seconds
793     * Returns an `id`, and -1 if adding didn't succeed
794
795 * `minetest.delete_particlespawner(id)`
796     * Delete `ParticleSpawner` with `id` (return value from `minetest.add_particlespawner`)
797
798 ### Misc.
799 * `minetest.parse_json(string[, nullvalue])`: returns something
800     * Convert a string containing JSON data into the Lua equivalent
801     * `nullvalue`: returned in place of the JSON null; defaults to `nil`
802     * On success returns a table, a string, a number, a boolean or `nullvalue`
803     * On failure outputs an error message and returns `nil`
804     * Example: `parse_json("[10, {\"a\":false}]")`, returns `{10, {a = false}}`
805 * `minetest.write_json(data[, styled])`: returns a string or `nil` and an error message
806     * Convert a Lua table into a JSON string
807     * styled: Outputs in a human-readable format if this is set, defaults to false
808     * Unserializable things like functions and userdata are saved as null.
809     * **Warning**: JSON is more strict than the Lua table format.
810         1. You can only use strings and positive integers of at least one as keys.
811         2. You can not mix string and integer keys.
812            This is due to the fact that JSON has two distinct array and object values.
813     * Example: `write_json({10, {a = false}})`, returns `"[10, {\"a\": false}]"`
814 * `minetest.serialize(table)`: returns a string
815     * Convert a table containing tables, strings, numbers, booleans and `nil`s
816       into string form readable by `minetest.deserialize`
817     * Example: `serialize({foo='bar'})`, returns `'return { ["foo"] = "bar" }'`
818 * `minetest.deserialize(string)`: returns a table
819     * Convert a string returned by `minetest.deserialize` into a table
820     * `string` is loaded in an empty sandbox environment.
821     * Will load functions, but they cannot access the global environment.
822     * Example: `deserialize('return { ["foo"] = "bar" }')`, returns `{foo='bar'}`
823     * Example: `deserialize('print("foo")')`, returns `nil` (function call fails)
824         * `error:[string "print("foo")"]:1: attempt to call global 'print' (a nil value)`
825 * `minetest.compress(data, method, ...)`: returns `compressed_data`
826     * Compress a string of data.
827     * `method` is a string identifying the compression method to be used.
828     * Supported compression methods:
829     *     Deflate (zlib): `"deflate"`
830     * `...` indicates method-specific arguments.  Currently defined arguments are:
831     *     Deflate: `level` - Compression level, `0`-`9` or `nil`.
832 * `minetest.decompress(compressed_data, method, ...)`: returns data
833     * Decompress a string of data (using ZLib).
834     * See documentation on `minetest.compress()` for supported compression methods.
835     * currently supported.
836     * `...` indicates method-specific arguments. Currently, no methods use this.
837 * `minetest.rgba(red, green, blue[, alpha])`: returns a string
838     * Each argument is a 8 Bit unsigned integer
839     * Returns the ColorString from rgb or rgba values
840     * Example: `minetest.rgba(10, 20, 30, 40)`, returns `"#0A141E28"`
841 * `minetest.encode_base64(string)`: returns string encoded in base64
842     * Encodes a string in base64.
843 * `minetest.decode_base64(string)`: returns string
844     * Decodes a string encoded in base64.
845 * `minetest.gettext(string)` : returns string
846     * look up the translation of a string in the gettext message catalog
847 * `fgettext_ne(string, ...)`
848     * call minetest.gettext(string), replace "$1"..."$9" with the given
849       extra arguments and return the result
850 * `fgettext(string, ...)` : returns string
851     * same as fgettext_ne(), but calls minetest.formspec_escape before returning result
852 * `minetest.pointed_thing_to_face_pos(placer, pointed_thing)`: returns a position
853     * returns the exact position on the surface of a pointed node
854 * `minetest.global_exists(name)`
855     * Checks if a global variable has been set, without triggering a warning.
856
857 ### UI
858 * `minetest.ui.minimap`
859     * Reference to the minimap object. See [`Minimap`](#minimap) class reference for methods.
860     * If client disabled minimap (using enable_minimap setting) this reference will be nil.
861 * `minetest.camera`
862     * Reference to the camera object. See [`Camera`](#camera) class reference for methods.
863 * `minetest.show_formspec(formname, formspec)` : returns true on success
864         * Shows a formspec to the player
865 * `minetest.display_chat_message(message)` returns true on success
866         * Shows a chat message to the current player.
867
868 Class reference
869 ---------------
870
871 ### ModChannel
872
873 An interface to use mod channels on client and server
874
875 #### Methods
876 * `leave()`: leave the mod channel.
877     * Client leaves channel `channel_name`.
878     * No more incoming or outgoing messages can be sent to this channel from client mods.
879     * This invalidate all future object usage
880     * Ensure your set mod_channel to nil after that to free Lua resources
881 * `is_writeable()`: returns true if channel is writable and mod can send over it.
882 * `send_all(message)`: Send `message` though the mod channel.
883     * If mod channel is not writable or invalid, message will be dropped.
884     * Message size is limited to 65535 characters by protocol.
885
886 ### Minimap
887 An interface to manipulate minimap on client UI
888
889 #### Methods
890 * `show()`: shows the minimap (if not disabled by server)
891 * `hide()`: hides the minimap
892 * `set_pos(pos)`: sets the minimap position on screen
893 * `get_pos()`: returns the minimap current position
894 * `set_angle(deg)`: sets the minimap angle in degrees
895 * `get_angle()`: returns the current minimap angle in degrees
896 * `set_mode(mode)`: sets the minimap mode (0 to 6)
897 * `get_mode()`: returns the current minimap mode
898 * `set_shape(shape)`: Sets the minimap shape. (0 = square, 1 = round)
899 * `get_shape()`: Gets the minimap shape. (0 = square, 1 = round)
900
901 ### Camera
902 An interface to get or set information about the camera and camera-node.
903 Please do not try to access the reference until the camera is initialized, otherwise the reference will be nil.
904
905 #### Methods
906 * `set_camera_mode(mode)`
907     * Pass `0` for first-person, `1` for third person, and `2` for third person front
908 * `get_camera_mode()`
909     * Returns 0, 1, or 2 as described above
910 * `get_fov()`
911     * Returns:
912
913 ```lua
914      {
915          x = number,
916          y = number,
917          max = number,
918          actual = number
919      }
920 ```
921
922 * `get_pos()`
923     * Returns position of camera with view bobbing
924 * `get_offset()`
925     * Returns eye offset vector
926 * `get_look_dir()`
927     * Returns eye direction unit vector
928 * `get_look_vertical()`
929     * Returns pitch in radians
930 * `get_look_horizontal()`
931     * Returns yaw in radians
932 * `get_aspect_ratio()`
933     * Returns aspect ratio of screen
934
935 ### LocalPlayer
936 An interface to retrieve information about the player.
937
938 Methods:
939
940 * `get_pos()`
941     * returns current player current position
942 * `get_velocity()`
943     * returns player speed vector
944 * `get_hp()`
945     * returns player HP
946 * `get_name()`
947     * returns player name
948 * `is_attached()`
949     * returns true if player is attached
950 * `is_touching_ground()`
951     * returns true if player touching ground
952 * `is_in_liquid()`
953     * returns true if player is in a liquid (This oscillates so that the player jumps a bit above the surface)
954 * `is_in_liquid_stable()`
955     * returns true if player is in a stable liquid (This is more stable and defines the maximum speed of the player)
956 * `get_liquid_viscosity()`
957     * returns liquid viscosity (Gets the viscosity of liquid to calculate friction)
958 * `is_climbing()`
959     * returns true if player is climbing
960 * `swimming_vertical()`
961     * returns true if player is swimming in vertical
962 * `get_physics_override()`
963     * returns:
964
965 ```lua
966     {
967         speed = float,
968         jump = float,
969         gravity = float,
970         sneak = boolean,
971         sneak_glitch = boolean
972     }
973 ```
974
975 * `get_override_pos()`
976     * returns override position
977 * `get_last_pos()`
978     * returns last player position before the current client step
979 * `get_last_velocity()`
980     * returns last player speed
981 * `get_breath()`
982     * returns the player's breath
983 * `get_movement_acceleration()`
984     * returns acceleration of the player in different environments:
985
986 ```lua
987     {
988        fast = float,
989        air = float,
990        default = float,
991     }
992 ```
993
994 * `get_movement_speed()`
995     * returns player's speed in different environments:
996
997 ```lua
998     {
999        walk = float,
1000        jump = float,
1001        crouch = float,
1002        fast = float,
1003        climb = float,
1004     }
1005 ```
1006
1007 * `get_movement()`
1008     * returns player's movement in different environments:
1009
1010 ```lua
1011     {
1012        liquid_fluidity = float,
1013        liquid_sink = float,
1014        liquid_fluidity_smooth = float,
1015        gravity = float,
1016     }
1017 ```
1018
1019 * `get_last_look_horizontal()`:
1020     * returns last look horizontal angle
1021 * `get_last_look_vertical()`:
1022     * returns last look vertical angle
1023 * `get_key_pressed()`:
1024     * returns last key typed by the player
1025 * `hud_add(definition)`
1026     * add a HUD element described by HUD def, returns ID number on success and `nil` on failure.
1027     * See [`HUD definition`](#hud-definition-hud_add-hud_get)
1028 * `hud_get(id)`
1029     * returns the [`definition`](#hud-definition-hud_add-hud_get) of the HUD with that ID number or `nil`, if non-existent.
1030 * `hud_remove(id)`
1031     * remove the HUD element of the specified id, returns `true` on success
1032 * `hud_change(id, stat, value)`
1033     * change a value of a previously added HUD element
1034     * element `stat` values: `position`, `name`, `scale`, `text`, `number`, `item`, `dir`
1035     * Returns `true` on success, otherwise returns `nil`
1036
1037 ### Settings
1038 An interface to read config files in the format of `minetest.conf`.
1039
1040 It can be created via `Settings(filename)`.
1041
1042 #### Methods
1043 * `get(key)`: returns a value
1044 * `get_bool(key)`: returns a boolean
1045 * `set(key, value)`
1046 * `remove(key)`: returns a boolean (`true` for success)
1047 * `get_names()`: returns `{key1,...}`
1048 * `write()`: returns a boolean (`true` for success)
1049     * write changes to file
1050 * `to_table()`: returns `{[key1]=value1,...}`
1051
1052 ### NodeMetaRef
1053 Node metadata: reference extra data and functionality stored in a node.
1054 Can be obtained via `minetest.get_meta(pos)`.
1055
1056 #### Methods
1057 * `get_string(name)`
1058 * `get_int(name)`
1059 * `get_float(name)`
1060 * `to_table()`: returns `nil` or a table with keys:
1061     * `fields`: key-value storage
1062     * `inventory`: `{list1 = {}, ...}}`
1063
1064 -----------------
1065 ### Definitions
1066 * `minetest.get_node_def(nodename)`
1067         * Returns [node definition](#node-definition) table of `nodename`
1068 * `minetest.get_item_def(itemstring)`
1069         * Returns item definition table of `itemstring`
1070
1071 #### Node Definition
1072
1073 ```lua
1074         {
1075                 has_on_construct = bool,        -- Whether the node has the on_construct callback defined
1076                 has_on_destruct = bool,         -- Whether the node has the on_destruct callback defined
1077                 has_after_destruct = bool,      -- Whether the node has the after_destruct callback defined
1078                 name = string,                  -- The name of the node e.g. "air", "default:dirt"
1079                 groups = table,                 -- The groups of the node
1080                 paramtype = string,             -- Paramtype of the node
1081                 paramtype2 = string,            -- ParamType2 of the node
1082                 drawtype = string,              -- Drawtype of the node
1083                 mesh = <string>,                -- Mesh name if existant
1084                 minimap_color = <Color>,        -- Color of node on minimap *May not exist*
1085                 visual_scale = number,          -- Visual scale of node
1086                 alpha = number,                 -- Alpha of the node. Only used for liquids
1087                 color = <Color>,                -- Color of node *May not exist*
1088                 palette_name = <string>,        -- Filename of palette *May not exist*
1089                 palette = <{                    -- List of colors
1090                         Color,
1091                         Color
1092                 }>,
1093                 waving = number,                -- 0 of not waving, 1 if waving
1094                 connect_sides = number,         -- Used for connected nodes
1095                 connects_to = {                 -- List of nodes to connect to
1096                         "node1",
1097                         "node2"
1098                 },
1099                 post_effect_color = Color,      -- Color overlayed on the screen when the player is in the node
1100                 leveled = number,               -- Max level for node
1101                 sunlight_propogates = bool,     -- Whether light passes through the block
1102                 light_source = number,          -- Light emitted by the block
1103                 is_ground_content = bool,       -- Whether caves should cut through the node
1104                 walkable = bool,                -- Whether the player collides with the node
1105                 pointable = bool,               -- Whether the player can select the node
1106                 diggable = bool,                -- Whether the player can dig the node
1107                 climbable = bool,               -- Whether the player can climb up the node
1108                 buildable_to = bool,            -- Whether the player can replace the node by placing a node on it
1109                 rightclickable = bool,          -- Whether the player can place nodes pointing at this node
1110                 damage_per_second = number,     -- HP of damage per second when the player is in the node
1111                 liquid_type = <string>,         -- A string containing "none", "flowing", or "source" *May not exist*
1112                 liquid_alternative_flowing = <string>, -- Alternative node for liquid *May not exist*
1113                 liquid_alternative_source = <string>, -- Alternative node for liquid *May not exist*
1114                 liquid_viscosity = <number>,    -- How fast the liquid flows *May not exist*
1115                 liquid_renewable = <boolean>,   -- Whether the liquid makes an infinite source *May not exist*
1116                 liquid_range = <number>,        -- How far the liquid flows *May not exist*
1117                 drowning = bool,                -- Whether the player will drown in the node
1118                 floodable = bool,               -- Whether nodes will be replaced by liquids (flooded)
1119                 node_box = table,               -- Nodebox to draw the node with
1120                 collision_box = table,          -- Nodebox to set the collision area
1121                 selection_box = table,          -- Nodebox to set the area selected by the player
1122                 sounds = {                      -- Table of sounds that the block makes
1123                         sound_footstep = SimpleSoundSpec,
1124                         sound_dig = SimpleSoundSpec,
1125                         sound_dug = SimpleSoundSpec
1126                 },
1127                 legacy_facedir_simple = bool,   -- Whether to use old facedir
1128                 legacy_wallmounted = bool       -- Whether to use old wallmounted
1129         }
1130 ```
1131
1132 #### Item Definition
1133
1134 ```lua
1135         {
1136                 name = string,                  -- Name of the item e.g. "default:stone"
1137                 description = string,           -- Description of the item e.g. "Stone"
1138                 type = string,                  -- Item type: "none", "node", "craftitem", "tool"
1139                 inventory_image = string,       -- Image in the inventory
1140                 wield_image = string,           -- Image in wieldmesh
1141                 palette_image = string,         -- Image for palette
1142                 color = Color,                  -- Color for item
1143                 wield_scale = Vector,           -- Wieldmesh scale
1144                 stack_max = number,             -- Number of items stackable together
1145                 usable = bool,                  -- Has on_use callback defined
1146                 liquids_pointable = bool,       -- Whether you can point at liquids with the item
1147                 tool_capabilities = <table>,    -- If the item is a tool, tool capabilities of the item
1148                 groups = table,                 -- Groups of the item
1149                 sound_place = SimpleSoundSpec,  -- Sound played when placed
1150                 sound_place_failed = SimpleSoundSpec, -- Sound played when placement failed
1151                 node_placement_prediction = string -- Node placed in client until server catches up
1152         }
1153 ```
1154 -----------------
1155
1156 ### Chat command definition (`register_chatcommand`)
1157
1158     {
1159         params = "<name> <privilege>", -- Short parameter description
1160         description = "Remove privilege from player", -- Full description
1161         func = function(param),        -- Called when command is run.
1162                                        -- Returns boolean success and text output.
1163     }
1164 ### Server info
1165 ```lua
1166 {
1167         address = "minetest.example.org", -- The domain name/IP address of a remote server or "" for a local server.
1168         ip = "203.0.113.156",             -- The IP address of the server.
1169         port = 30000,                     -- The port the client is connected to.
1170         protocol_version = 30             -- Will not be accurate at start up as the client might not be connected to the server yet, in that case it will be 0.
1171 }
1172 ```
1173
1174 ### HUD Definition (`hud_add`, `hud_get`)
1175 ```lua
1176     {
1177         hud_elem_type = "image", -- see HUD element types, default "text"
1178     --  ^ type of HUD element, can be either of "image", "text", "statbar", or "inventory"
1179         position = {x=0.5, y=0.5},
1180     --  ^ Left corner position of element, default `{x=0,y=0}`.
1181         name = "<name>",    -- default ""
1182         scale = {x=2, y=2}, -- default {x=0,y=0}
1183         text = "<text>",    -- default ""
1184         number = 2,         -- default 0
1185         item = 3,           -- default 0
1186     --  ^ Selected item in inventory.  0 for no item selected.
1187         direction = 0,      -- default 0
1188     --  ^ Direction: 0: left-right, 1: right-left, 2: top-bottom, 3: bottom-top
1189         alignment = {x=0, y=0},   -- default {x=0, y=0}
1190     --  ^ See "HUD Element Types"
1191         offset = {x=0, y=0},      -- default {x=0, y=0}
1192     --  ^ See "HUD Element Types"
1193         size = { x=100, y=100 },  -- default {x=0, y=0}
1194     --  ^ Size of element in pixels
1195     }
1196 ```
1197
1198 Escape sequences
1199 ----------------
1200 Most text can contain escape sequences, that can for example color the text.
1201 There are a few exceptions: tab headers, dropdowns and vertical labels can't.
1202 The following functions provide escape sequences:
1203 * `minetest.get_color_escape_sequence(color)`:
1204     * `color` is a [ColorString](#colorstring)
1205     * The escape sequence sets the text color to `color`
1206 * `minetest.colorize(color, message)`:
1207     * Equivalent to:
1208       `minetest.get_color_escape_sequence(color) ..
1209        message ..
1210        minetest.get_color_escape_sequence("#ffffff")`
1211 * `minetest.get_background_escape_sequence(color)`
1212     * `color` is a [ColorString](#colorstring)
1213     * The escape sequence sets the background of the whole text element to
1214       `color`. Only defined for item descriptions and tooltips.
1215 * `minetest.strip_foreground_colors(str)`
1216     * Removes foreground colors added by `get_color_escape_sequence`.
1217 * `minetest.strip_background_colors(str)`
1218     * Removes background colors added by `get_background_escape_sequence`.
1219 * `minetest.strip_colors(str)`
1220     * Removes all color escape sequences.
1221
1222 `ColorString`
1223 -------------
1224 `#RGB` defines a color in hexadecimal format.
1225
1226 `#RGBA` defines a color in hexadecimal format and alpha channel.
1227
1228 `#RRGGBB` defines a color in hexadecimal format.
1229
1230 `#RRGGBBAA` defines a color in hexadecimal format and alpha channel.
1231
1232 Named colors are also supported and are equivalent to
1233 [CSS Color Module Level 4](http://dev.w3.org/csswg/css-color/#named-colors).
1234 To specify the value of the alpha channel, append `#AA` to the end of the color name
1235 (e.g. `colorname#08`). For named colors the hexadecimal string representing the alpha
1236 value must (always) be two hexadecimal digits.
1237
1238 `Color`
1239 -------------
1240 `{a = alpha, r = red, g = green, b = blue}` defines an ARGB8 color.
1241
1242 HUD element types
1243 -----------------
1244 The position field is used for all element types.
1245
1246 To account for differing resolutions, the position coordinates are the percentage
1247 of the screen, ranging in value from `0` to `1`.
1248
1249 The name field is not yet used, but should contain a description of what the
1250 HUD element represents. The direction field is the direction in which something
1251 is drawn.
1252
1253 `0` draws from left to right, `1` draws from right to left, `2` draws from
1254 top to bottom, and `3` draws from bottom to top.
1255
1256 The `alignment` field specifies how the item will be aligned. It ranges from `-1` to `1`,
1257 with `0` being the center, `-1` is moved to the left/up, and `1` is to the right/down.
1258 Fractional values can be used.
1259
1260 The `offset` field specifies a pixel offset from the position. Contrary to position,
1261 the offset is not scaled to screen size. This allows for some precisely-positioned
1262 items in the HUD.
1263
1264 **Note**: `offset` _will_ adapt to screen DPI as well as user defined scaling factor!
1265
1266 Below are the specific uses for fields in each type; fields not listed for that type are ignored.
1267
1268 **Note**: Future revisions to the HUD API may be incompatible; the HUD API is still
1269 in the experimental stages.
1270
1271 ### `image`
1272 Displays an image on the HUD.
1273
1274 * `scale`: The scale of the image, with 1 being the original texture size.
1275   Only the X coordinate scale is used (positive values).
1276   Negative values represent that percentage of the screen it
1277   should take; e.g. `x=-100` means 100% (width).
1278 * `text`: The name of the texture that is displayed.
1279 * `alignment`: The alignment of the image.
1280 * `offset`: offset in pixels from position.
1281
1282 ### `text`
1283 Displays text on the HUD.
1284
1285 * `scale`: Defines the bounding rectangle of the text.
1286   A value such as `{x=100, y=100}` should work.
1287 * `text`: The text to be displayed in the HUD element.
1288 * `number`: An integer containing the RGB value of the color used to draw the text.
1289   Specify `0xFFFFFF` for white text, `0xFF0000` for red, and so on.
1290 * `alignment`: The alignment of the text.
1291 * `offset`: offset in pixels from position.
1292
1293 ### `statbar`
1294 Displays a horizontal bar made up of half-images.
1295
1296 * `text`: The name of the texture that is used.
1297 * `number`: The number of half-textures that are displayed.
1298   If odd, will end with a vertically center-split texture.
1299 * `direction`
1300 * `offset`: offset in pixels from position.
1301 * `size`: If used, will force full-image size to this value (override texture pack image size)
1302
1303 ### `inventory`
1304 * `text`: The name of the inventory list to be displayed.
1305 * `number`: Number of items in the inventory to be displayed.
1306 * `item`: Position of item that is selected.
1307 * `direction`
1308 * `offset`: offset in pixels from position.
1309
1310 ### `waypoint`
1311 Displays distance to selected world position.
1312
1313 * `name`: The name of the waypoint.
1314 * `text`: Distance suffix. Can be blank.
1315 * `number:` An integer containing the RGB value of the color used to draw the text.
1316 * `world_pos`: World position of the waypoint.
1317
1318 ### Particle definition (`add_particle`)
1319
1320     {
1321         pos = {x=0, y=0, z=0},
1322         velocity = {x=0, y=0, z=0},
1323         acceleration = {x=0, y=0, z=0},
1324     --  ^ Spawn particle at pos with velocity and acceleration
1325         expirationtime = 1,
1326     --  ^ Disappears after expirationtime seconds
1327         size = 1,
1328         collisiondetection = false,
1329     --  ^ collisiondetection: if true collides with physical objects
1330         collision_removal = false,
1331     --  ^ collision_removal: if true then particle is removed when it collides,
1332     --  ^ requires collisiondetection = true to have any effect
1333         vertical = false,
1334     --  ^ vertical: if true faces player using y axis only
1335         texture = "image.png",
1336     --  ^ Uses texture (string)
1337         animation = {Tile Animation definition},
1338     --  ^ optional, specifies how to animate the particle texture
1339         glow = 0
1340     --  ^ optional, specify particle self-luminescence in darkness
1341     }
1342
1343 ### `ParticleSpawner` definition (`add_particlespawner`)
1344
1345     {
1346         amount = 1,
1347         time = 1,
1348     --  ^ If time is 0 has infinite lifespan and spawns the amount on a per-second base
1349         minpos = {x=0, y=0, z=0},
1350         maxpos = {x=0, y=0, z=0},
1351         minvel = {x=0, y=0, z=0},
1352         maxvel = {x=0, y=0, z=0},
1353         minacc = {x=0, y=0, z=0},
1354         maxacc = {x=0, y=0, z=0},
1355         minexptime = 1,
1356         maxexptime = 1,
1357         minsize = 1,
1358         maxsize = 1,
1359     --  ^ The particle's properties are random values in between the bounds:
1360     --  ^ minpos/maxpos, minvel/maxvel (velocity), minacc/maxacc (acceleration),
1361     --  ^ minsize/maxsize, minexptime/maxexptime (expirationtime)
1362         collisiondetection = false,
1363     --  ^ collisiondetection: if true uses collision detection
1364         collision_removal = false,
1365     --  ^ collision_removal: if true then particle is removed when it collides,
1366     --  ^ requires collisiondetection = true to have any effect
1367         vertical = false,
1368     --  ^ vertical: if true faces player using y axis only
1369         texture = "image.png",
1370     --  ^ Uses texture (string)
1371     }