Mainmenu API

Introduction

The main menu is defined as a formspec by Lua in builtin/mainmenu/ Description of formspec language to show your menu is in "Formspec" tab.

Callbacks

  • core.button_handler(fields): called when a button is pressed.
    • fields: {name1 = value1, name2 = value2, ...}
  • core.event_handler(event):
    • event: "MenuQuit", "KeyEnter", "ExitButton" or "EditBoxEnter"

Gamedata

The "gamedata" table is read when calling core.start(). It should contain:

{
    playername     = <name>,
    password       = <password>,
    address        = <IP/adress>,
    port           = <port>,
    selected_world = <index>, -- 0 for client mode
    singleplayer   = <true/false>,
}

Functions

  • core.start():

    • Read Gamedata above for more information.
  • core.close():

    • Exits the game (or "kills" it)
  • core.get_min_supp_proto():

    • Returns the minimum supported network protocol
  • core.get_max_supp_proto():

    • Returns the maximum supported network protocol version
  • core.open_url(url):

    • Unsafely opens the URL in a web browser.
    • Must begin with http:// or https://
    • Returns false on failure.
  • core.open_dir(path):

    • opens the path in the system file browser/explorer.
    • Must be an existing directory.
    • Returns false on failure.
  • core.get_version():

    • Returns current core version
    • (possible in async calls)
  • core.get_system_ram():

    • Returns system memory in MB
  • core.copy_to_clipboard(text):

    • Copies text to the clipboard

Filesystem

  • core.get_builtin_path():

    • Returns path to builtin root.
  • core.create_dir(absolute_path):

    • absolute_path: Directory to create (needs to be absolute)
    • Returns true, or false on failure.
    • (possible in async calls)
  • core.delete_dir(absolute_path):

    • absolute_path: Directory to delete (needs to be absolute)
    • Returns true, or false on failure.
    • (possible in async calls)
  • core.copy_dir(source, destination, keep_source):

    • source: Source folder to copy to
    • destination: Destination folder where is source folder will be copied to
    • keep_source: Defaults to true. If set to false source is deleted after copying.
    • Returns true, or false on failure.
    • (possible in async calls)
  • core.is_dir(path):

    • Returns true, if path is a valid dir.
    • (possible in async calls)
  • core.extract_zip(zipfile, destination[, password]):

    • (unzip within path required)
    • zipfile: .ZIP file to extract
    • destination: folder to extract to
    • Returns true on success, or false on failure (example: wrong password)
  • core.sound_play(spec, looped) -> handle:

    • spec: SimpleSoundSpec (see [Sounds])
    • looped: sound will be looped bool.
  • core.sound_stop(handle):

    • Stops playing the sound by its handle.
  • core.get_video_drivers():

    • Get list of video drivers supported by engine. (not all modes are guaranteed to work!)
    • first element of returned list is guaranteed to be the NULL driver.
    • Example:
        {
          {
            name = "opengl",
            friendly_name = "OpenGL"
          },
          {
            name = "software",
            friendly_name = "Software Renderer"
          }
        }
      
    • Returns list of available video drivers' settings name and 'friendly' display name.
  • core.get_mapgen_names([include_hidden=false]):

    • Returns table of map generator algorithms registered in the core.
    • (possible in async calls)
  • core.get_cache_path() -> "/data/user/0/com.multicraft.game/cache/"

  • core.get_temp_path() -> "C:/Users/User/Appdata/Local/Temp"

HTTP Requests

  • core.download_file(request, target):

    • request: can either be a HTTPRequest or a URL (string)
    • target: the file to write to
    • Returns true or false
    • (possible in async calls)
  • core.cancel_all_download_files():

    • Cancels all calls to core.download_file() running in other threads
    • (possible in async calls)
  • core.get_http_api():

    • Returns HTTPApiTable containing http functions.
    • The returned table contains the functions fetch_sync, fetch_async and fetch_async_get described below.
    • Function only exists if multicraft server was built with cURL support.
    • (possible in async calls)
  • HTTPApiTable.fetch_sync(HTTPRequest req): returns HTTPRequestResult

    • Performs given request synchronously
  • 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
  • HTTPApiTable.get_download_stats(handle):

    • Returns bytes_downloaded, total_bytes
    • This is the sum of all HTTP requests, including core.download_file.
    • bytes_downloaded should never decrease, however total_bytes may decrease if a request fails (so that when no requests are running, bytes_downloaded == total_bytes).

HTTPRequest definition

Used by HTTPApiTable.fetch and HTTPApiTable.fetch_async.

  {
      url = "http://example.org",

      timeout = 10,
      -- Timeout for connection in seconds. Default is 3 seconds.

      post_data = "Raw POST request data string" OR {field1 = "data1", field2 = "data2"},
      -- Optional, if specified a POST request with post_data is performed.
      -- Accepts both a string and a table. If a table is specified, encodes
      -- table as x-www-form-urlencoded key-value pairs.
      -- If post_data is not specified, a GET request is performed instead.

      user_agent = "ExampleUserAgent",
      -- Optional, if specified replaces the default minetest user agent with
      -- given string

      extra_headers = { "Accept-Language: en-us", "Accept-Charset: utf-8" },
      -- Optional, if specified adds additional headers to the HTTP request.
      -- You must make sure that the header strings follow HTTP specification
      -- ("Key: Value").

      multipart = boolean
      -- Optional, if true performs a multipart HTTP request.
      -- Default is false.
  }

HTTPRequestResult definition

Passed to HTTPApiTable.fetch callback. Returned by HTTPApiTable.fetch_async_get.

  {
      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"
  }

Formspec

  • core.update_formspec(formspec):

    • formspec: new formspec string for updating current one.
  • core.get_table_index(tablename):

    • Can also handle textlists
    • Returns index of the table
  • core.formspec_escape(string):

    • Escapes characters [, ], \, , and ; that can not be used in formspecs
    • Returns escaped string
  • core.explode_table_event(string):

    • Returns table e.g. {type="CHG", row=1, column=2}
    • type: "INV" (no row selected), "CHG" (selected) or "DCL" (double-click)
  • core.explode_textlist_event(string):

    • Returns table e.g. {type="CHG", index=1}
    • type: "INV" (no row selected), "CHG" (selected) or "DCL" (double-click)
  • core.set_formspec_prepend(formspec):

    • formspec: tring to be added to every mainmenu formspec.
    • (this function is unused right now, but coming soon will be used for theming)

GUI

  • core.set_background(type, texturepath, [tile, minsize]):

    • type: "background", "overlay", "header" or "footer"
    • tile: tile the image instead of scaling (background only)
    • minsize: minimum tile size, images are scaled to at least this size prior doing tiling (background only)
  • core.set_clouds(enabled):

    • enabled: make clouds visible depends on the bool
  • core.set_sky(sky_params):

    • sky_params: a table like the one in-game
    • (Only "regular" skies are supported)
  • core.set_stars(params):

    • Changes parameters of stars displayed in main menu depending on params.
    • Here is all of the fields from params:
    • visible: visibility depending on bool
    • count: how many stars should be generated
    • star_color: color of the stars
    • star_scale: scale of the stars
  • core.set_sky_body_pos(moon_horizon_pos, moon_day_pos, moon_angle, sun_horizon_pos, sun_day_pos, sun_angle):

    • Set some sky body values in degrees that are used for rendering
  • core.set_moon(params):

    • Set some moon parameters.
    • Here is all of the fields from params:
    • texture: main texture name of the moon
    • tonemap: tonemap texture name of the moon
    • scale: scale of the moon
    • visible: visibility depending on bool
  • core.set_sun(params):

    • Set some sun parameters.
    • Here is all of the fields from params:
    • texture: main texture name of the sun
    • tonemap: tonemap texture name of the sun
    • scale: scale of the sun
    • visible: visibility depending on bool
  • core.set_timeofday(value):

    • Set time of day for rendering sky in main menu like in game
    • value: a float between 0 and 1
  • core.set_topleft_text(text):

    • Sets top left text of the screen, used for game name of the world
  • core.show_keys_menu(): shows menu for set up the keys (kinda useless on mobile, unless you'll connect keyboard and mouse to your phone)

  • core.show_path_select_dialog(formname, caption, is_file_select):

    • Shows a path select dialog.
    • formname: base name of dialog response returned in fields
    • If dialog was "_accepted", will be added to fieldname containing the path
    • If dialog was "_cancelled", will be added to fieldname value is set to formname itself
    • is_file_select: If true, a file, and not a folder will be selected
    • Returns nil, or selected file/folder
  • core.get_screen_info():

    • Returns table like:
        {
          density = 1.0,
          -- Screen density (DPI)
      
          high_dpi = 2.0,
          -- High-screen DPI
      
          display_width = 1280,
          -- Width of the display
      
          display_height = 720,
          -- Height of the display
      
          window_width = 1280,
          -- Current window width
      
          window_height = 720
          -- Current window height
        }
      

Content and Packages

Content - an installed mod, modpack, game, or texture pack (txt) Package - content which is downloadable from the content db, may or may not be installed.

  • core.get_user_path():

    • Returns path to global user data, the directory that contains user-provided mods, worlds, games, and texture packs.
    • (possible in async calls)
  • core.get_modpath():

    • Returns path to global modpath
    • (possible in async calls)
  • core.get_clientmodpath():

    • Returns path to global client-side modpath
    • (possible in async calls)
  • core.get_gamepath():

    • Returns path to global gamepath
    • (possible in async calls)
  • core.get_texturepath():

    • Returns path to default textures
    • (possible in async calls)
  • core.get_game(index):

    • Returns something like:
        {
            id = 1,
            -- Game Integer Identifier
      
            path = "/data/user/0/com.multicraft.game/cache/games/default",
            -- Absolute path to the game
      
            gamemods_path = "/data/user/0/com.multicraft.game/cache/games/default/mods",
            -- Absolute path to mods folder of the game
      
            name = "default",
            -- Game Name
      
            menuicon_path = "/data/user/0/com.multicraft.game/cache/games/default/menu/icon.png",
            -- Absolute path to game icon for menu
      
            author = "author",
            -- Author of the game
      
            -- DEPRECATED: Do not use
            addon_mods_paths = {[1] = <path>}
        }
      
  • core.get_games():

    • Returns table of all games in format above
    • (possible in async calls)
  • core.get_content_info(path):

    • Returns something like:
        {
            name = "content",
            -- internal name of the content
      
            type = "mod",
            -- type of the content ("mod", "modpack", "game", "txp")
      
            description = "Adds content",
            -- description for the content
      
            author = "author",
            -- author of the content
      
            path = "path/to/content",
            -- absolute path to the content folder
      
            depends = {"mod", "mod2"},
            -- required depends (mods only)
      
            optional_depends = {"mod", "mod2"},
            -- optional depends (mods only)
        }
      

Logging

  • core.debug(line):

    • Always printed to stderr and logfile (print() is redirected here)
    • (possible in async calls)
  • core.log(line):

    • (possible in async calls)
  • core.log(loglevel, line):

    • loglevel: one of "error", "action", "info" and "verbose"
    • (possible in async calls)

Settings

  • core.settings:set(name, value):

    • Sets the name to value.
  • core.settings:get(name) -> string or nil:

    • (possible in async calls)
  • core.settings:set_bool(name, value):

    • Sets tne bool name to value.
  • core.settings:get_bool(name) -> bool or nil:

    • (possible in async calls)
  • core.settings:save():

    • Saves all settings to config file.

For a complete list of methods of the Settings object see "'core' namespace reference" tab.

Worlds

  • core.get_worlds():

    • Returns list of worlds, like:
        {
          [1] = {
            path = "/storage/emulated/0/Android/data/com.multicraft.game/files/worlds/World 1",
            -- absolute path to the world folder
      
            name = "World 1",
            -- readable name of the world
      
            gameid = 1
            -- game id world uses
          }
        }
      
    • (possible in async calls)
  • core.create_world(worldname, gameid):

    • Creates new world with name worldname with game gameid.
  • core.delete_world(index):

    • Delete world by its index.

Helpers

  • core.get_us_time():

    • Returns time with microsecond precision.
  • core.gettext(string):

    • Look up the translation of a string in the gettext message catalog.
  • fgettext_ne(string, ...):

    • Call core.gettext(string), replace "$1"..."$9" with the given extra arguments and return the result
  • fgettext(string, ...):

    • Same as fgettext_ne(), but calls core.formspec_escape before returning result
  • core.parse_json(string[, nullvalue]):

    • See core.parse_json in "'core' namespace reference"
    • (possible in async calls)
  • dump(obj, dumped={}):

    • Returns object serialized as a string
  • "string":split(separator):

    • Example: string:split("a, b", ", ") == {"a", "b"}
  • "string":trim():

    • Example: string.trim("\n \t\tfoo bar\t ") == "foo bar"
  • core.is_yes(arg):

    • Returns whether arg can be interpreted as yes. ("y", "yes", "true", 1)
    • (possible in async calls)
  • core.encode_base64(string):

    • Encodes a string in base64.
  • core.decode_base64(string):

    • Decodes a string encoded in base64.

Async

  • core.handle_async(async_job, parameters, finished):

    • Executes a function asynchronously.
    • async_job: function receiving one parameter and returning one parameter.
    • parameters: parameter table passed to async_job.
    • finished: function to be called once when async_job has finished.
    • the result of async_job is passed to this function as a return.
  • Limitations of Async operations:

    • No access to global Lua variables (_G) (Don't even try :P)
    • Limited set of available functions
      • Example: no access to functions modifying menu and core.start(), core.close(), or core.show_path_select_dialog()

Background music

The main menu supports background music. It looks for a main_menu sound in $USER_PATH/sounds. The same naming conventions as for normal sounds apply. This means the player can add a custom sound. It will be played in the main menu (gain = 1.0), looped.