code:
#!/bin/bash

# This script generates normalmaps using The GIMP to do the heavy lifting.
# give any unrecognized switch (say, -h) for usage info.

rm /tmp/normals_filelist.txt

numprocs=6

skiptools=false
skipinventory=false
invresolution=64
dryrun=false
pattern="*.png *.jpg"

filter=0
scale=8
wrap=0
heightsource=0
conversion=0
invertx=0
inverty=0

while test -n "$1"; do
	case "$1" in
		--scale|-s)
			if [ -z "$2" ] ; then echo "Missing scale parameter"; exit 1; fi
			scale=$2
			shift
			shift
			;;
		--pattern|-p)
			if [ -z "$2" ] ; then echo "Missing pattern parameter"; exit 1; fi
			pattern=$2
			shift
			shift
			;;
		--skiptools|-t)
			skiptools=true
			shift
			;;
		--skipinventory|-i)
			if [[ $2 =~ ^[0-9]+$ ]]; then
				invresolution=$2
				shift
			fi
			skipinventory=true
			shift
			;;
		--filter|-f)
			if [ -z "$2" ] ; then echo "Missing filter parameter"; exit 1; fi

			case "$2" in
				sobel3|1)
					filter=1
					;;
				sobel5|2)
					filter=2
					;;
				prewitt3|3)
					filter=3
					;;
				prewitt5|4)
					filter=4
					;;
				3x3|5)
					filter=5
					;;
				5x5|6)
					filter=6
					;;
				7x7|7)
					filter=7
					;;
				9x9|8)
					filter=8
					;;
				*)
					filter=0
					;;
			esac

			shift
			shift
			;;
		--heightalpha|-a)
			heightsource=1
			shift
			;;
		--conversion|-c)
				if [ -z "$2" ] ; then echo "Missing conversion parameter"; exit 1; fi

				case "$2" in
					biased|1)
						conversion=1
						;;
					red|2)
						conversion=2
						;;
					green|3)
						conversion=3
						;;
					blue|4)
						conversion=4
						;;
					maxrgb|5)
						conversion=5
						;;
					minrgb|6)
						conversion=6
						;;
					colorspace|7)
						conversion=7
						;;
					normalize-only|8)
						conversion=8
						;;
					heightmap|9)
						conversion=9
						;;
					*)
						conversion=0
						;;
			esac

			shift
			shift
			;;
		--wrap|-w)
			wrap=1
			shift
			;;
		--invertx|-x)
			invertx=1
			shift
			;;
		--inverty|-y)
			inverty=1
			shift
			;;
		--dryrun|-d)
			dryrun=true
			shift
			;;
		*)
			echo -e "\nUsage:\n"
			echo "`basename $0` [--scale|-s <value>] [--filter|-f <string>]"
			echo " [--wrap|-w] [--heightalpha|-a] [--invertx|-x] [--inverty|-y]"
			echo " [--conversion|-c <string>] [--skiptools|-t] [--skipinventory|-i [<value>]]"
			echo " [--dryrun|-d] [--pattern|-p <pattern>]"
			echo -e "\nDefaults to a scale of 8, checking all files in the current directory, and not"
			echo "skipping apparent tools or inventory images.  Filter, if specified, may be one"
			echo "of: sobel3, sobel5, prewitt3, prewitt5, 3x3, 5x5, 7x7, or 9x9, or a value 1"
			echo "through 8 (1=sobel3, 2=sobel5, etc.). Defaults to 0 (four-sample).  The height"
			echo "source is taken from the image's alpha channel if heightalpha is specified.\n"
			echo ""
			echo "If inventory skip is specified, an optional resolution may also be included"
			echo "(default is 64).  Conversion can be one of: biased, red, green, blue, maxrgb,"
			echo "minrgb, colorspace, normalize-only, heightmap or a value from 1 to 9"
			echo "corresponding respectively to those keywords.  Defaults to 0 (simple"
			echo "normalize) if not specified.  Wrap, if specified, enables wrapping of the"
			echo "normalmap around the edges of the texture (defaults to no).  Invert X/Y"
			echo "reverses the calculated gradients  for the X and/or Y dimensions represented"
			echo "by the normalmap (both default to non-inverted)."
			echo ""
			echo "The pattern, can be an escaped pattern string such as \*apple\* or"
			echo "default_\*.png or similar (defaults to all PNG and JPG images in the current"
			echo "directory that do not contain \"_normal\" or \"_specular\" in their filenames)."
			echo ""
			echo "If set for dry-run, the actions this script will take will be printed, but no"
			echo "images will be generated.  Passing an invalid value to a switch will generally"
			echo "cause that switch to revert to its default value."
			echo ""
			exit 1
			;;
	esac
done

echo -e "\nProcessing files based on pattern \"$pattern\" ..."

normalMap()
{
	out=`echo "$1" | sed 's/.png/_normal.png/' | sed 's/.jpg/_normal.png/'`

	echo "Launched process to generate normalmap: \"$1\" --> \"$out\"" >&2

	gimp -i -b "
		(define
			(normalMap-fbx-conversion fileName newFileName filter nscale wrap heightsource conversion invertx inverty)
			(let*
				(
					(image (car (gimp-file-load RUN-NONINTERACTIVE fileName fileName)))
					(drawable (car (gimp-image-get-active-layer image)))
					(drawable (car (gimp-image-flatten image)))
				)
				(if (> (car (gimp-drawable-type drawable)) 1)
					(gimp-convert-rgb image) ()
				)

				(plug-in-normalmap
					RUN-NONINTERACTIVE
					image
					drawable
					filter
					0.0
					nscale
					wrap
					heightsource
					0
					conversion
					0
					invertx
					inverty
					0
					0.0
					drawable)
				(gimp-file-save RUN-NONINTERACTIVE image drawable newFileName newFileName)
				(gimp-image-delete image)
			)
		)
		(normalMap-fbx-conversion \"$1\" \"$out\" $2 $3 $4 $5 $6 $7 $8)" -b '(gimp-quit 0)'
}

export -f normalMap

for file in `ls $pattern |grep -v "_normal.png"|grep -v "_specular"` ; do

	invtest=`file "$file" |grep "$invresolution x $invresolution"`
	if $skipinventory && [ -n "$invtest" ] ; then
		echo "Skipped presumed "$invresolution"px inventory image: $file" >&2
		continue
	fi

	tooltest=`echo "$file" \
		| grep -v "_tool" \
		| grep -v "_shovel" \
		| grep -v "_pick" \
		| grep -v "_axe" \
		| grep -v "_sword" \
		| grep -v "_hoe" \
		| grep -v "bucket_"`

	if $skiptools && [ -z "$tooltest" ] ; then
		echo "Skipped presumed tool image: $file" >&2
		continue
	fi

	if $dryrun ; then
		echo "Would have generated a normalmap for $file" >&2
		continue
	else
		echo \"$file\" $filter $scale $wrap $heightsource $conversion $invertx $inverty
	fi
done | xargs -P $numprocs -n 8 -I{} bash -c normalMap\ \{\}\ \{\}\ \{\}\ \{\}\ \{\}\ \{\}\ \{\}\ \{\}


code:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-

# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# COPYING for more details.

# Made by Jogge, modified by celeron55
# 2011-05-29: j0gge: initial release
# 2011-05-30: celeron55: simultaneous support for sectors/sectors2, removed
# 2011-06-02: j0gge: command line parameters, coordinates, players, ...
# 2011-06-04: celeron55: added #!/usr/bin/python2 and converted \r\n to \n
#                        to make it easily executable on Linux
# 2011-07-30: WF: Support for content types extension, refactoring
# 2011-07-30: erlehmann: PEP 8 compliance.

# Requires Python Imaging Library: http://www.pythonware.com/products/pil/

# Some speed-up: ...lol, actually it slows it down.
#import psyco ; psyco.full()
#from psyco.classes import *

import zlib
import os
import string
import time
import getopt
import sys
import array
import cStringIO
import traceback
from PIL import Image, ImageDraw, ImageFont, ImageColor

TRANSLATION_TABLE = {
    1: 0x800,  # CONTENT_GRASS
    4: 0x801,  # CONTENT_TREE
    5: 0x802,  # CONTENT_LEAVES
    6: 0x803,  # CONTENT_GRASS_FOOTSTEPS
    7: 0x804,  # CONTENT_MESE
    8: 0x805,  # CONTENT_MUD
    10: 0x806,  # CONTENT_CLOUD
    11: 0x807,  # CONTENT_COALSTONE
    12: 0x808,  # CONTENT_WOOD
    13: 0x809,  # CONTENT_SAND
    18: 0x80a,  # CONTENT_COBBLE
    19: 0x80b,  # CONTENT_STEEL
    20: 0x80c,  # CONTENT_GLASS
    22: 0x80d,  # CONTENT_MOSSYCOBBLE
    23: 0x80e,  # CONTENT_GRAVEL
    24: 0x80f,  # CONTENT_SANDSTONE
    25: 0x810,  # CONTENT_CACTUS
    26: 0x811,  # CONTENT_BRICK
    27: 0x812,  # CONTENT_CLAY
    28: 0x813,  # CONTENT_PAPYRUS
    29: 0x814}  # CONTENT_BOOKSHELF

def hex_to_int(h):
    i = int(h, 16)
    if(i > 2047):
        i -= 4096
    return i

def hex4_to_int(h):
    i = int(h, 16)
    if(i > 32767):
        i -= 65536
    return i

def int_to_hex3(i):
    if(i < 0):
        return "%03X" % (i + 4096)
    else:
        return "%03X" % i

def int_to_hex4(i):
    if(i < 0):
        return "%04X" % (i + 65536)
    else:
        return "%04X" % i

def getBlockAsInteger(p):
    return p[2]*16777216 + p[1]*4096 + p[0]

def unsignedToSigned(i, max_positive):
    if i < max_positive:
        return i
    else:
        return i - 2*max_positive

def getIntegerAsBlock(i):
    x = unsignedToSigned(i % 4096, 2048)
    i = int((i - x) / 4096)
    y = unsignedToSigned(i % 4096, 2048)
    i = int((i - y) / 4096)
    z = unsignedToSigned(i % 4096, 2048)
    return x,y,z

def limit(i, l, h):
    if(i > h):
        i = h
    if(i < l):
        i = l
    return i

def readU8(f):
    return ord(f.read(1))

def readU16(f):
    return ord(f.read(1))*256 + ord(f.read(1))

def readU32(f):
    return ord(f.read(1))*256*256*256 + ord(f.read(1))*256*256 + ord(f.read(1))*256 + ord(f.read(1))

def readS32(f):
    return unsignedToSigned(ord(f.read(1))*256*256*256 + ord(f.read(1))*256*256 + ord(f.read(1))*256 + ord(f.read(1)), 2**31)

usagetext = """minetestmapper.py [options]
  -i/--input <world_path>
  -o/--output <output_image.png>
  --bgcolor <color>
  --scalecolor <color>
  --playercolor <color>
  --origincolor <color>
  --drawscale
  --drawplayers
  --draworigin
  --drawunderground
Color format: '#000000'"""

def usage():
    print(usagetext)

try:
    opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["help", "input=",
        "output=", "bgcolor=", "scalecolor=", "origincolor=",
        "playercolor=", "draworigin", "drawplayers", "drawscale",
        "drawunderground"])
except getopt.GetoptError as err:
    # print help information and exit:
    print(str(err))  # will print something like "option -a not recognized"
    usage()
    sys.exit(2)

path = None
output = "map.png"
border = 0
scalecolor = "black"
bgcolor = "white"
origincolor = "red"
playercolor = "red"
drawscale = False
drawplayers = False
draworigin = False
drawunderground = False

sector_xmin = -1500 / 16
sector_xmax = 1500 / 16
sector_zmin = -1500 / 16
sector_zmax = 1500 / 16

for o, a in opts:
    if o in ("-h", "--help"):
        usage()
        sys.exit()
    elif o in ("-i", "--input"):
        path = a
    elif o in ("-o", "--output"):
        output = a
    elif o == "--bgcolor":
        bgcolor = ImageColor.getrgb(a)
    elif o == "--scalecolor":
        scalecolor = ImageColor.getrgb(a)
    elif o == "--playercolor":
        playercolor = ImageColor.getrgb(a)
    elif o == "--origincolor":
        origincolor = ImageColor.getrgb(a)
    elif o == "--drawscale":
        drawscale = True
        border = 40
    elif o == "--drawplayers":
        drawplayers = True
    elif o == "--draworigin":
        draworigin = True
    elif o == "--drawunderground":
        drawunderground = True
    else:
        assert False, "unhandled option"

if path is None:
    print("Please select world path (eg. -i ../worlds/yourworld) (or use --help)")
    sys.exit(1)

if path[-1:] != "/" and path[-1:] != "\\":
    path = path + "/"

# Load color information for the blocks.
colors = {}
try:
    f = file("colors.txt")
except IOError:
    f = file(os.path.join(os.path.dirname(__file__), "colors.txt"))
for line in f:
    values = string.split(line)
    if len(values) < 4:
        continue
    identifier = values[0]
    is_hex = True
    for c in identifier:
        if c not in "0123456789abcdefABCDEF":
            is_hex = False
            break
    if is_hex:
        colors[int(values[0], 16)] = (
            int(values[1]),
            int(values[2]),
            int(values[3]))
    else:
        colors[values[0]] = (
            int(values[1]),
            int(values[2]),
            int(values[3]))
f.close()

#print("colors: "+repr(colors))
#sys.exit(1)

xlist = []
zlist = []

# List all sectors to memory and calculate the width and heigth of the
# resulting picture.

conn = None
cur = None
if os.path.exists(path + "map.sqlite"):
    import sqlite3
    conn = sqlite3.connect(path + "map.sqlite")
    cur = conn.cursor()

    cur.execute("SELECT `pos` FROM `blocks`")
    while True:
        r = cur.fetchone()
        if not r:
            break

        x, y, z = getIntegerAsBlock(r[0])

        if x < sector_xmin or x > sector_xmax:
            continue
        if z < sector_zmin or z > sector_zmax:
            continue

        xlist.append(x)
        zlist.append(z)

if os.path.exists(path + "sectors2"):
    for filename in os.listdir(path + "sectors2"):
        for filename2 in os.listdir(path + "sectors2/" + filename):
            x = hex_to_int(filename)
            z = hex_to_int(filename2)
            if x < sector_xmin or x > sector_xmax:
                continue
            if z < sector_zmin or z > sector_zmax:
                continue
            xlist.append(x)
            zlist.append(z)

if os.path.exists(path + "sectors"):
    for filename in os.listdir(path + "sectors"):
        x = hex4_to_int(filename[:4])
        z = hex4_to_int(filename[-4:])
        if x < sector_xmin or x > sector_xmax:
            continue
        if z < sector_zmin or z > sector_zmax:
            continue
        xlist.append(x)
        zlist.append(z)

if len(xlist) == 0 or len(zlist) == 0:
    print("World does not exist.")
    sys.exit(1)

# Get rid of doubles
xlist, zlist = zip(*sorted(set(zip(xlist, zlist))))

minx = min(xlist)
minz = min(zlist)
maxx = max(xlist)
maxz = max(zlist)

w = (maxx - minx) * 16 + 16
h = (maxz - minz) * 16 + 16

print("Result image (w=" + str(w) + " h=" + str(h) + ") will be written to "
        + output)

im = Image.new("RGB", (w + border, h + border), bgcolor)
draw = ImageDraw.Draw(im)
impix = im.load()

stuff = {}

unknown_node_names = []
unknown_node_ids = []

starttime = time.time()

CONTENT_WATER = 2

def content_is_ignore(d):
    return d in [0, "ignore"]

def content_is_water(d):
    return d in [2, 9]

def content_is_air(d):
    return d in [126, 127, 254, "air"]

def read_content(mapdata, version, datapos):
    if version >= 24:
        return (mapdata[datapos*2] << 8) | (mapdata[datapos*2 + 1])
    elif version >= 20:
        if mapdata[datapos] < 0x80:
            return mapdata[datapos]
        else:
            return (mapdata[datapos] << 4) | (mapdata[datapos + 0x2000] >> 4)
    elif 16 <= version < 20:
        return TRANSLATION_TABLE.get(mapdata[datapos], mapdata[datapos])
    else:
        raise Exception("Unsupported map format: " + str(version))

def read_mapdata(mapdata, version, pixellist, water, day_night_differs, id_to_name):
    global stuff  # oh my :-)
    global unknown_node_names
    global unknown_node_ids

    if(len(mapdata) < 4096):
        print("bad: " + xhex + "/" + zhex + "/" + yhex + " " + \
            str(len(mapdata)))
    else:
        chunkxpos = xpos * 16
        chunkypos = ypos * 16
        chunkzpos = zpos * 16
        content = 0
        datapos = 0
        for (x, z) in reversed(pixellist):
            for y in reversed(range(16)):
                datapos = x + y * 16 + z * 256
                content = read_content(mapdata, version, datapos)
                # Try to convert id to name
                try:
                    content = id_to_name[content]
                except KeyError:
                    pass

                if content_is_ignore(content):
                    pass
                elif content_is_air(content):
                    pass
                elif content_is_water(content):
                    water[(x, z)] += 1
                    # Add dummy stuff for drawing sea without seabed
                    stuff[(chunkxpos + x, chunkzpos + z)] = (
                        chunkypos + y, content, water[(x, z)], day_night_differs)
                elif content in colors:
                    # Memorize information on the type and height of
                    # the block and for drawing the picture.
                    stuff[(chunkxpos + x, chunkzpos + z)] = (
                        chunkypos + y, content, water[(x, z)], day_night_differs)
                    pixellist.remove((x, z))
                    break
                else:
                    if type(content) == str:
                        if content not in unknown_node_names:
                            unknown_node_names.append(content)
                        #print("unknown node: %s/%s/%s x: %d y: %d z: %d block name: %s"
                        #        % (xhex, zhex, yhex, x, y, z, content))
                    else:
                        if content not in unknown_node_ids:
                            unknown_node_ids.append(content)
                        #print("unknown node: %s/%s/%s x: %d y: %d z: %d block id: %x"
                        #        % (xhex, zhex, yhex, x, y, z, content))

# Go through all sectors.
for n in range(len(xlist)):
    #if n > 500:
    #   break
    if n % 200 == 0:
        nowtime = time.time()
        dtime = nowtime - starttime
        try:
            n_per_second = 1.0 * n / dtime
        except ZeroDivisionError:
            n_per_second = 0
        if n_per_second != 0:
            seconds_per_n = 1.0 / n_per_second
            time_guess = seconds_per_n * len(xlist)
            remaining_s = time_guess - dtime
            remaining_minutes = int(remaining_s / 60)
            remaining_s -= remaining_minutes * 60
            print("Processing sector " + str(n) + " of " + str(len(xlist))
                    + " (" + str(round(100.0 * n / len(xlist), 1)) + "%)"
                    + " (ETA: " + str(remaining_minutes) + "m "
                    + str(int(remaining_s)) + "s)")

    xpos = xlist[n]
    zpos = zlist[n]

    xhex = int_to_hex3(xpos)
    zhex = int_to_hex3(zpos)
    xhex4 = int_to_hex4(xpos)
    zhex4 = int_to_hex4(zpos)

    sector1 = xhex4.lower() + zhex4.lower()
    sector2 = xhex.lower() + "/" + zhex.lower()

    ylist = []

    sectortype = ""

    if cur:
        psmin = getBlockAsInteger((xpos, -2048, zpos))
        psmax = getBlockAsInteger((xpos, 2047, zpos))
        cur.execute("SELECT `pos` FROM `blocks` WHERE `pos`>=? AND `pos`<=? AND (`pos` - ?) % 4096 = 0", (psmin, psmax, psmin))
        while True:
            r = cur.fetchone()
            if not r:
                break
            pos = getIntegerAsBlock(r[0])[1]
            ylist.append(pos)
            sectortype = "sqlite"
    try:
        for filename in os.listdir(path + "sectors/" + sector1):
            if(filename != "meta"):
                pos = int(filename, 16)
                if(pos > 32767):
                    pos -= 65536
                ylist.append(pos)
                sectortype = "old"
    except OSError:
        pass

    if sectortype == "":
        try:
            for filename in os.listdir(path + "sectors2/" + sector2):
                if(filename != "meta"):
                    pos = int(filename, 16)
                    if(pos > 32767):
                        pos -= 65536
                    ylist.append(pos)
                    sectortype = "new"
        except OSError:
            pass

    if sectortype == "":
        continue

    ylist.sort()

    # Make a list of pixels of the sector that are to be looked for.
    pixellist = []
    water = {}
    for x in range(16):
        for z in range(16):
            pixellist.append((x, z))
            water[(x, z)] = 0

    # Go through the Y axis from top to bottom.
    for ypos in reversed(ylist):
        try:
            #print("("+str(xpos)+","+str(ypos)+","+str(zpos)+")")

            yhex = int_to_hex4(ypos)

            if sectortype == "sqlite":
                ps = getBlockAsInteger((xpos, ypos, zpos))
                cur.execute("SELECT `data` FROM `blocks` WHERE `pos`==? LIMIT 1", (ps,))
                r = cur.fetchone()
                if not r:
                    continue
                f = cStringIO.StringIO(r[0])
            else:
                if sectortype == "old":
                    filename = path + "sectors/" + sector1 + "/" + yhex.lower()
                else:
                    filename = path + "sectors2/" + sector2 + "/" + yhex.lower()
                f = file(filename, "rb")

            # Let's just memorize these even though it's not really necessary.
            version = readU8(f)
            flags = f.read(1)

            #print("version="+str(version))
            #print("flags="+str(version))

            # Check flags
            is_underground = ((ord(flags) & 1) != 0)
            day_night_differs = ((ord(flags) & 2) != 0)
            lighting_expired = ((ord(flags) & 4) != 0)
            generated = ((ord(flags) & 8) != 0)

            #print("is_underground="+str(is_underground))
            #print("day_night_differs="+str(day_night_differs))
            #print("lighting_expired="+str(lighting_expired))
            #print("generated="+str(generated))

            if version >= 22:
                content_width = readU8(f)
                params_width = readU8(f)

            # Node data
            dec_o = zlib.decompressobj()
            try:
                mapdata = array.array("B", dec_o.decompress(f.read()))
            except:
                mapdata = []

            # Reuse the unused tail of the file
            f.close();
            f = cStringIO.StringIO(dec_o.unused_data)
            #print("unused data: "+repr(dec_o.unused_data))

            # zlib-compressed node metadata list
            dec_o = zlib.decompressobj()
            try:
                metaliststr = array.array("B", dec_o.decompress(f.read()))
                # And do nothing with it
            except:
                metaliststr = []

            # Reuse the unused tail of the file
            f.close();
            f = cStringIO.StringIO(dec_o.unused_data)
            #print("* dec_o.unused_data: "+repr(dec_o.unused_data))
            data_after_node_metadata = dec_o.unused_data

            if version <= 21:
                # mapblockobject_count
                readU16(f)

            if version == 23:
                readU8(f) # Unused node timer version (always 0)
            if version == 24:
                ver = readU8(f)
                if ver == 1:
                    num = readU16(f)
                    for i in range(0,num):
                        readU16(f)
                        readS32(f)
                        readS32(f)

            static_object_version = readU8(f)
            static_object_count = readU16(f)
            for i in range(0, static_object_count):
                # u8 type (object type-id)
                object_type = readU8(f)
                # s32 pos_x_nodes * 10000
                pos_x_nodes = readS32(f)/10000
                # s32 pos_y_nodes * 10000
                pos_y_nodes = readS32(f)/10000
                # s32 pos_z_nodes * 10000
                pos_z_nodes = readS32(f)/10000
                # u16 data_size
                data_size = readU16(f)
                # u8[data_size] data
                data = f.read(data_size)

            timestamp = readU32(f)
            #print("* timestamp="+str(timestamp))

            id_to_name = {}
            if version >= 22:
                name_id_mapping_version = readU8(f)
                num_name_id_mappings = readU16(f)
                #print("* num_name_id_mappings: "+str(num_name_id_mappings))
                for i in range(0, num_name_id_mappings):
                    node_id = readU16(f)
                    name_len = readU16(f)
                    name = f.read(name_len)
                    #print(str(node_id)+" = "+name)
                    id_to_name[node_id] = name

            # Node timers
            if version >= 25:
                timer_size = readU8(f)
                num = readU16(f)
                for i in range(0,num):
                    readU16(f)
                    readS32(f)
                    readS32(f)

            read_mapdata(mapdata, version, pixellist, water, day_night_differs, id_to_name)

            # After finding all the pixels in the sector, we can move on to
            # the next sector without having to continue the Y axis.
            if(len(pixellist) == 0):
                break
        except Exception as e:
            print("Error at ("+str(xpos)+","+str(ypos)+","+str(zpos)+"): "+str(e))
            sys.stdout.write("Block data: ")
            for c in r[0]:
                sys.stdout.write("%2.2x "%ord(c))
            sys.stdout.write(os.linesep)
            sys.stdout.write("Data after node metadata: ")
            for c in data_after_node_metadata:
                sys.stdout.write("%2.2x "%ord(c))
            sys.stdout.write(os.linesep)
            traceback.print_exc()

print("Drawing image")
# Drawing the picture
starttime = time.time()
n = 0
for (x, z) in stuff.iterkeys():
    if n % 500000 == 0:
        nowtime = time.time()
        dtime = nowtime - starttime
        try:
            n_per_second = 1.0 * n / dtime
        except ZeroDivisionError:
            n_per_second = 0
        if n_per_second != 0:
            listlen = len(stuff)
            seconds_per_n = 1.0 / n_per_second
            time_guess = seconds_per_n * listlen
            remaining_s = time_guess - dtime
            remaining_minutes = int(remaining_s / 60)
            remaining_s -= remaining_minutes * 60
            print("Drawing pixel " + str(n) + " of " + str(listlen)
                    + " (" + str(round(100.0 * n / listlen, 1)) + "%)"
                    + " (ETA: " + str(remaining_minutes) + "m "
                    + str(int(remaining_s)) + "s)")
    n += 1

    (r, g, b) = colors[stuff[(x, z)][1]]

    dnd = stuff[(x, z)][3]  # day/night differs?
    if not dnd and not drawunderground:
        if stuff[(x, z)][2] > 0:  # water
            (r, g, b) = colors[CONTENT_WATER]
        else:
            continue

    # Comparing heights of a couple of adjacent blocks and changing
    # brightness accordingly.
    try:
        c = stuff[(x, z)][1]
        c1 = stuff[(x - 1, z)][1]
        c2 = stuff[(x, z + 1)][1]
        dnd1 = stuff[(x - 1, z)][3]
        dnd2 = stuff[(x, z + 1)][3]
        if not dnd:
            d = -69
        elif not content_is_water(c1) and not content_is_water(c2) and \
            not content_is_water(c):
            y = stuff[(x, z)][0]
            y1 = stuff[(x - 1, z)][0] if dnd1 else y
            y2 = stuff[(x, z + 1)][0] if dnd2 else y
            d = ((y - y1) + (y - y2)) * 12
        else:
            d = 0

        if(d > 36):
            d = 36

        r = limit(r + d, 0, 255)
        g = limit(g + d, 0, 255)
        b = limit(b + d, 0, 255)
    except:
        pass

    # Water
    if(stuff[(x, z)][2] > 0):
        r = int(r * .15 + colors[2][0] * .85)
        g = int(g * .15 + colors[2][1] * .85)
        b = int(b * .15 + colors[2][2] * .85)

    impix[x - minx * 16 + border, h - 1 - (z - minz * 16) + border] = (r, g, b)

if draworigin:
    draw.ellipse((minx * -16 - 5 + border, h - minz * -16 - 6 + border,
        minx * -16 + 5 + border, h - minz * -16 + 4 + border),
        outline=origincolor)

font = ImageFont.load_default()

if drawscale:
    draw.text((24, 0), "X", font=font, fill=scalecolor)
    draw.text((2, 24), "Z", font=font, fill=scalecolor)

    for n in range(int(minx / -4) * -4, maxx, 4):
        draw.text((minx * -16 + n * 16 + 2 + border, 0), str(n * 16),
            font=font, fill=scalecolor)
        draw.line((minx * -16 + n * 16 + border, 0,
            minx * -16 + n * 16 + border, border - 1), fill=scalecolor)

    for n in range(int(maxz / 4) * 4, minz, -4):
        draw.text((2, h - 1 - (n * 16 - minz * 16) + border), str(n * 16),
            font=font, fill=scalecolor)
        draw.line((0, h - 1 - (n * 16 - minz * 16) + border, border - 1,
            h - 1 - (n * 16 - minz * 16) + border), fill=scalecolor)

if drawplayers:
    try:
        for filename in os.listdir(path + "players"):
            f = file(path + "players/" + filename)
            lines = f.readlines()
            name = ""
            position = []
            for line in lines:
                p = string.split(line)
                if p[0] == "name":
                    name = p[2]
                    print(filename + ": name = " + name)
                if p[0] == "position":
                    position = string.split(p[2][1:-1], ",")
                    print(filename + ": position = " + p[2])
            if len(name) > 0 and len(position) == 3:
                x = (int(float(position[0]) / 10 - minx * 16))
                z = int(h - (float(position[2]) / 10 - minz * 16))
                draw.ellipse((x - 2 + border, z - 2 + border,
                    x + 2 + border, z + 2 + border), outline=playercolor)
                draw.text((x + 2 + border, z + 2 + border), name,
                    font=font, fill=playercolor)
            f.close()
    except OSError:
        pass

print("Saving")
im.save(output)

if unknown_node_names:
    sys.stdout.write("Unknown node names:")
    for name in unknown_node_names:
        sys.stdout.write(" "+name)
    sys.stdout.write(os.linesep)
if unknown_node_ids:
    sys.stdout.write("Unknown node ids:")
    for node_id in unknown_node_ids:
        sys.stdout.write(" "+str(hex(node_id)))
    sys.stdout.write(os.linesep)

repo_name: pgimeno/minetest

license: unknown


code:
#!/usr/bin/python3

# Loads block files from sectors folders into map.sqlite database.
# The sectors folder should be safe to remove after this prints "Finished."

import time, os, sys

try:
	import sqlite3
except:
	exit('You need to have the Python sqlite3 module.')

path = "../world/"

paths = []

# sectors2 gets to try first
if os.path.isdir(path + 'sectors2/'):
	paths.append('sectors2')
if os.path.isdir(path + 'sectors/'):
	paths.append('sectors')

if not paths:
	exit('Could not find sectors folder at ' + path + 'sectors2/ or ' + path + 'sectors/')

def parseSigned12bit(u):
	u = int('0x'+u, 16)
	return (u if u < 2**11 else u - 2**12)

def parseSigned16bit(u):
	u = int('0x'+u, 16)
	return (u if u < 2**15 else u - 2**16)

def int64(u):
	while u >= 2**63:
		u -= 2**64
	while u <= -2**63:
		u += 2**64
	return u

# Convert sector folder(s) to integer
def getSectorPos(dirname):
	if len(dirname) == 8:
		# Old layout
		x = parseSigned16bit(dirname[:4])
		z = parseSigned16bit(dirname[4:])
	elif len(dirname) == 7:
		# New layout
		x = parseSigned12bit(dirname[:3])
		z = parseSigned12bit(dirname[4:])
	else:
		print('Terrible sector at ' + dirname)
		return

	return x, z

# Convert block file to integer position
def getBlockPos(sectordir, blockfile):
	p2d = getSectorPos(sectordir)

	if not p2d:
		return

	if len(blockfile) != 4:
		print("Invalid block filename: " + blockfile)

	y = parseSigned16bit(blockfile)

	return p2d[0], y, p2d[1]

# Convert location to integer
def getBlockAsInteger(p):
	return int64(p[2]*16777216 + p[1]*4096 + p[0])

# Init

create = False
if not os.path.isfile(path + 'map.sqlite'):
	create = True

conn = sqlite3.connect(path + 'map.sqlite')

if not conn:
	exit('Could not open database.')

cur = conn.cursor()

if create:
	cur.execute("CREATE TABLE IF NOT EXISTS `blocks` (`pos` INT NOT NULL PRIMARY KEY, `data` BLOB);")
	conn.commit()
	print('Created database at ' + path + 'map.sqlite')

# Crawl the folders

count = 0
t = time.time()
for base in paths:
	v = 0
	if base == 'sectors':
		v = 1
	elif base == 'sectors2':
		v= 2
	else:
		print('Ignoring base ' + base)
		continue

	for root, dirs, files in os.walk(path + base):
		if files:
			for block in files:
				pos = getBlockAsInteger(getBlockPos(root[(-8 if v == 1 else -7 if v == 2 else 0):], block))

				if pos is None:
					print('Ignoring broken path ' + root + '/' + block)
					continue

				f = open(root+'/'+block, 'rb')
				blob = f.read()
				f.close()
				if sys.version_info.major == 2:
					blob = buffer(blob)
				else:
					blob = memoryview(blob)
				cur.execute('INSERT OR IGNORE INTO `blocks` VALUES(?, ?)', (pos, blob))
				count += 1

		if(time.time() - t > 3):
			t = time.time()
			print(str(count)+' blocks processed...')

conn.commit()

print('Finished. (' + str(count) + ' blocks)')


code:
#!/bin/bash
dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
gameid=minimal
minetest=$dir/../bin/minetest
testspath=$dir/../tests
worldpath=$testspath/testworld_$gameid
configpath=$testspath/configs
logpath=$testspath/log
conf_server=$configpath/minetest.conf.multi.server
conf_client1=$configpath/minetest.conf.multi.client1
conf_client2=$configpath/minetest.conf.multi.client2
log_server=$logpath/server.log
log_client1=$logpath/client1.log
log_client2=$logpath/client2.log

mkdir -p $worldpath
mkdir -p $configpath
mkdir -p $logpath

echo -ne 'client1::shout,interact,settime,teleport,give
client2::shout,interact,settime,teleport,give
' > $worldpath/auth.txt

echo -ne '' > $conf_server

echo -ne '# client 1 config
screenW=500
screenH=380
name=client1
viewing_range_nodes_min=10
' > $conf_client1

echo -ne '# client 2 config
screenW=500
screenH=380
name=client2
viewing_range_nodes_min=10
' > $conf_client2

echo $(sleep 1; $minetest --disable-unittests --logfile $log_client1 --config $conf_client1 --go --address localhost) &
echo $(sleep 2; $minetest --disable-unittests --logfile $log_client2 --config $conf_client2 --go --address localhost) &
$minetest --disable-unittests --server --logfile $log_server --config $conf_server --world $worldpath --gameid $gameid


code:
#!/bin/bash -e
echo "Preparing for $TRAVIS_COMMIT_RANGE"

if [[ "$LINT" == "1" ]]; then
	curl http://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -
	sudo add-apt-repository "deb http://apt.llvm.org/trusty/ llvm-toolchain-trusty-3.9 main"
	sudo apt-get -yq update
	sudo apt-get install clang-format-3.9
	exit 0
fi

. util/travis/common.sh
needs_compile || exit 0

if [[ $TRAVIS_OS_NAME == "linux" ]]; then
	sudo apt-get update
	sudo apt-get install p7zip-full $COMPILER
fi

if [[ $PLATFORM == "Unix" ]]; then
	if [[ $TRAVIS_OS_NAME == "linux" ]]; then
		sudo apt-get update
		sudo apt-get install libirrlicht-dev cmake libbz2-dev libpng12-dev \
			libjpeg-dev libxxf86vm-dev libgl1-mesa-dev libsqlite3-dev \
			libhiredis-dev libogg-dev libgmp-dev libvorbis-dev libopenal-dev \
			gettext libpq-dev postgresql-server-dev-all
		# Linking to LevelDB is broken, use a custom build
		wget http://minetest.kitsunemimi.pw/libleveldb-1.18-ubuntu12.04.7z
		sudo 7z x -o/usr libleveldb-1.18-ubuntu12.04.7z
		if [[ "$VALGRIND" == "1" ]]; then
			sudo apt-get install valgrind
		fi

	else
		brew update
		brew install freetype gettext hiredis irrlicht jpeg leveldb libogg libvorbis luajit
		#brew upgrade postgresql
	fi
elif [[ $PLATFORM == "Win32" ]]; then
	wget http://minetest.kitsunemimi.pw/mingw_w64_i686_ubuntu12.04_4.9.1.7z -O mingw.7z
	sed -e "s|%PREFIX%|i686-w64-mingw32|" \
		-e "s|%ROOTPATH%|/usr/i686-w64-mingw32|" \
		< util/travis/toolchain_mingw.cmake.in > util/buildbot/toolchain_mingw.cmake
	sudo 7z x -y -o/usr mingw.7z
elif [[ $PLATFORM == "Win64" ]]; then
	wget http://minetest.kitsunemimi.pw/mingw_w64_x86_64_ubuntu12.04_4.9.1.7z -O mingw.7z
	sed -e "s|%PREFIX%|x86_64-w64-mingw32|" \
		-e "s|%ROOTPATH%|/usr/x86_64-w64-mingw32|" \
		< util/travis/toolchain_mingw.cmake.in > util/buildbot/toolchain_mingw64.cmake
	sudo 7z x -y -o/usr mingw.7z
fi


code:
src/activeobject.h
src/ban.cpp
src/camera.cpp
src/camera.h
src/cavegen.cpp
src/cguittfont/CGUITTFont.cpp
src/cguittfont/CGUITTFont.h
src/cguittfont/irrUString.h
src/cguittfont/xCGUITTFont.h
src/chat.cpp
src/chat.h
src/chat_interface.h
src/client/clientlauncher.cpp
src/client/clientlauncher.h
src/client.cpp
src/clientenvironment.cpp
src/clientenvironment.h
src/client.h
src/clientiface.cpp
src/clientiface.h
src/client/joystick_controller.cpp
src/client/joystick_controller.h
src/clientmap.cpp
src/clientmap.h
src/clientmedia.cpp
src/clientmedia.h
src/clientobject.cpp
src/clientobject.h
src/client/tile.cpp
src/client/tile.h
src/clouds.cpp
src/clouds.h
src/collision.cpp
src/collision.h
src/config.h
src/content_cao.cpp
src/content_cao.h
src/content_cso.cpp
src/content_cso.h
src/content_mapblock.cpp
src/content_mapblock.h
src/content_mapnode.cpp
src/content_nodemeta.cpp
src/content_nodemeta.h
src/content_sao.cpp
src/content_sao.h
src/convert_json.cpp
src/convert_json.h
src/craftdef.cpp
src/craftdef.h
src/database.cpp
src/database-dummy.cpp
src/database-files.cpp
src/database-leveldb.cpp
src/database-postgresql.cpp
src/database-postgresql.h
src/database-redis.cpp
src/database-sqlite3.cpp
src/database-sqlite3.h
src/daynightratio.h
src/debug.cpp
src/debug.h
src/defaultsettings.cpp
src/drawscene.cpp
src/drawscene.h
src/dungeongen.cpp
src/dungeongen.h
src/emerge.cpp
src/emerge.h
src/environment.cpp
src/event.h
src/event_manager.h
src/exceptions.h
src/face_position_cache.cpp
src/face_position_cache.h
src/filecache.cpp
src/filesys.cpp
src/filesys.h
src/fontengine.cpp
src/fontengine.h
src/game.cpp
src/gamedef.h
src/game.h
src/genericobject.cpp
src/genericobject.h
src/gettext.cpp
src/gettext.h
src/guiChatConsole.cpp
src/guiChatConsole.h
src/guiEngine.cpp
src/guiEngine.h
src/guiFileSelectMenu.cpp
src/guiFormSpecMenu.cpp
src/guiFormSpecMenu.h
src/guiKeyChangeMenu.cpp
src/guiMainMenu.h
src/guiPasswordChange.cpp
src/guiscalingfilter.cpp
src/guiscalingfilter.h
src/guiTable.cpp
src/guiTable.h
src/guiVolumeChange.cpp
src/guiVolumeChange.h
src/httpfetch.cpp
src/hud.cpp
src/hud.h
src/imagefilters.cpp
src/imagefilters.h
src/intlGUIEditBox.cpp
src/intlGUIEditBox.h
src/inventory.cpp
src/inventory.h
src/inventorymanager.cpp
src/inventorymanager.h
src/irrlicht_changes/static_text.cpp
src/irrlicht_changes/static_text.h
src/irrlichttypes.h
src/itemdef.cpp
src/itemdef.h
src/itemstackmetadata.cpp
src/keycode.cpp
src/light.cpp
src/localplayer.cpp
src/log.cpp
src/log.h
src/main.cpp
src/mainmenumanager.h
src/mapblock.cpp
src/mapblock.h
src/mapblock_mesh.cpp
src/mapblock_mesh.h
src/map.cpp
src/mapgen.cpp
src/mapgen_flat.cpp
src/mapgen_fractal.cpp
src/mapgen.h
src/mapgen_singlenode.cpp
src/mapgen_v5.cpp
src/mapgen_v6.cpp
src/mapgen_v6.h
src/mapgen_v7.cpp
src/mapgen_v7.h
src/mapgen_valleys.cpp
src/mapgen_valleys.h
src/map.h
src/mapnode.cpp
src/mapnode.h
src/mapsector.cpp
src/mapsector.h
src/map_settings_manager.cpp
src/map_settings_manager.h
src/mesh.cpp
src/mesh.h
src/mesh_generator_thread.cpp
src/metadata.h
src/mg_biome.cpp
src/mg_biome.h
src/mg_decoration.cpp
src/mg_decoration.h
src/mg_ore.cpp
src/mg_ore.h
src/mg_schematic.cpp
src/mg_schematic.h
src/minimap.cpp
src/minimap.h
src/modalMenu.h
src/mods.cpp
src/mods.h
src/network/clientopcodes.cpp
src/network/clientopcodes.h
src/network/clientpackethandler.cpp
src/network/connection.cpp
src/network/connection.h
src/network/networkpacket.cpp
src/network/networkpacket.h
src/network/networkprotocol.h
src/network/serveropcodes.cpp
src/network/serveropcodes.h
src/network/serverpackethandler.cpp
src/nodedef.cpp
src/nodedef.h
src/nodemetadata.cpp
src/nodemetadata.h
src/nodetimer.cpp
src/nodetimer.h
src/noise.cpp
src/noise.h
src/objdef.cpp
src/objdef.h
src/object_properties.cpp
src/object_properties.h
src/particles.cpp
src/particles.h
src/pathfinder.cpp
src/pathfinder.h
src/player.cpp
src/player.h
src/porting_android.cpp
src/porting_android.h
src/porting.cpp
src/porting.h
src/profiler.h
src/quicktune.cpp
src/quicktune.h
src/quicktune_shortcutter.h
src/raycast.cpp
src/raycast.h
src/reflowscan.cpp
src/reflowscan.h
src/remoteplayer.cpp
src/rollback.cpp
src/rollback.h
src/rollback_interface.cpp
src/rollback_interface.h
src/script/common/c_content.cpp
src/script/common/c_content.h
src/script/common/c_converter.cpp
src/script/common/c_converter.h
src/script/common/c_internal.cpp
src/script/common/c_internal.h
src/script/common/c_types.cpp
src/script/common/c_types.h
src/script/cpp_api/s_async.cpp
src/script/cpp_api/s_async.h
src/script/cpp_api/s_base.cpp
src/script/cpp_api/s_base.h
src/script/cpp_api/s_client.cpp
src/script/cpp_api/s_entity.cpp
src/script/cpp_api/s_entity.h
src/script/cpp_api/s_env.cpp
src/script/cpp_api/s_env.h
src/script/cpp_api/s_internal.h
src/script/cpp_api/s_inventory.cpp
src/script/cpp_api/s_inventory.h
src/script/cpp_api/s_item.cpp
src/script/cpp_api/s_item.h
src/script/cpp_api/s_mainmenu.h
src/script/cpp_api/s_node.cpp
src/script/cpp_api/s_node.h
src/script/cpp_api/s_nodemeta.cpp
src/script/cpp_api/s_nodemeta.h
src/script/cpp_api/s_player.cpp
src/script/cpp_api/s_security.cpp
src/script/cpp_api/s_security.h
src/script/cpp_api/s_server.cpp
src/script/cpp_api/s_server.h
src/script/lua_api/l_areastore.cpp
src/script/lua_api/l_base.cpp
src/script/lua_api/l_base.h
src/script/lua_api/l_craft.cpp
src/script/lua_api/l_craft.h
src/script/lua_api/l_env.cpp
src/script/lua_api/l_env.h
src/script/lua_api/l_http.cpp
src/script/lua_api/l_http.h
src/script/lua_api/l_internal.h
src/script/lua_api/l_inventory.cpp
src/script/lua_api/l_inventory.h
src/script/lua_api/l_item.cpp
src/script/lua_api/l_item.h
src/script/lua_api/l_itemstackmeta.cpp
src/script/lua_api/l_itemstackmeta.h
src/script/lua_api/l_localplayer.cpp
src/script/lua_api/l_mainmenu.cpp
src/script/lua_api/l_mainmenu.h
src/script/lua_api/l_mapgen.cpp
src/script/lua_api/l_metadata.cpp
src/script/lua_api/l_minimap.cpp
src/script/lua_api/l_nodemeta.cpp
src/script/lua_api/l_nodemeta.h
src/script/lua_api/l_nodetimer.cpp
src/script/lua_api/l_noise.cpp
src/script/lua_api/l_object.cpp
src/script/lua_api/l_object.h
src/script/lua_api/l_particles.cpp
src/script/lua_api/l_particles.h
src/script/lua_api/l_rollback.cpp
src/script/lua_api/l_rollback.h
src/script/lua_api/l_server.cpp
src/script/lua_api/l_settings.cpp
src/script/lua_api/l_sound.cpp
src/script/lua_api/l_storage.cpp
src/script/lua_api/l_util.cpp
src/script/lua_api/l_vmanip.cpp
src/script/scripting_client.cpp
src/script/scripting_client.h
src/script/scripting_mainmenu.cpp
src/script/scripting_mainmenu.h
src/script/scripting_server.cpp
src/script/scripting_server.h
src/serialization.cpp
src/serialization.h
src/server.cpp
src/serverenvironment.cpp
src/serverenvironment.h
src/server.h
src/serverlist.cpp
src/serverlist.h
src/serverobject.cpp
src/serverobject.h
src/settings.cpp
src/settings.h
src/settings_translation_file.cpp
src/shader.cpp
src/shader.h
src/sky.cpp
src/socket.cpp
src/socket.h
src/sound.cpp
src/sound_openal.cpp
src/sound_openal.h
src/staticobject.cpp
src/staticobject.h
src/subgame.cpp
src/subgame.h
src/terminal_chat_console.cpp
src/terminal_chat_console.h
src/threading/atomic.h
src/threading/event.cpp
src/threading/mutex_auto_lock.h
src/threading/mutex.cpp
src/threading/mutex.h
src/threading/semaphore.cpp
src/threading/thread.cpp
src/threading/thread.h
src/threads.h
src/tileanimation.cpp
src/tool.cpp
src/tool.h
src/touchscreengui.cpp
src/treegen.cpp
src/treegen.h
src/unittest/test_areastore.cpp
src/unittest/test_collision.cpp
src/unittest/test_compression.cpp
src/unittest/test_connection.cpp
src/unittest/test.cpp
src/unittest/test_filepath.cpp
src/unittest/test.h
src/unittest/test_inventory.cpp
src/unittest/test_keycode.cpp
src/unittest/test_map_settings_manager.cpp
src/unittest/test_noderesolver.cpp
src/unittest/test_noise.cpp
src/unittest/test_random.cpp
src/unittest/test_schematic.cpp
src/unittest/test_serialization.cpp
src/unittest/test_settings.cpp
src/unittest/test_socket.cpp
src/unittest/test_threading.cpp
src/unittest/test_utilities.cpp
src/unittest/test_voxelalgorithms.cpp
src/unittest/test_voxelmanipulator.cpp
src/util/areastore.cpp
src/util/areastore.h
src/util/auth.cpp
src/util/auth.h
src/util/base64.cpp
src/util/base64.h
src/util/basic_macros.h
src/util/container.h
src/util/directiontables.cpp
src/util/directiontables.h
src/util/enriched_string.cpp
src/util/enriched_string.h
src/util/md32_common.h
src/util/numeric.cpp
src/util/numeric.h
src/util/pointedthing.cpp
src/util/pointedthing.h
src/util/pointer.h
src/util/serialize.cpp
src/util/serialize.h
src/util/sha1.cpp
src/util/srp.cpp
src/util/srp.h
src/util/strfnd.h
src/util/string.cpp
src/util/string.h
src/util/thread.h
src/util/timetaker.cpp
src/util/timetaker.h
src/version.cpp
src/version.h
src/voxelalgorithms.cpp
src/voxelalgorithms.h
src/voxel.cpp
src/voxel.h
src/wieldmesh.cpp


code:
#!/bin/bash -e

# Relative to git-repository root:
TRIGGER_COMPILE_PATHS="src/.*\.(c|cpp|h)|CMakeLists.txt|cmake/Modules/|util/travis/|util/buildbot/"

needs_compile() {
	git diff --name-only $TRAVIS_COMMIT_RANGE | egrep -q "^($TRIGGER_COMPILE_PATHS)"
}


code:
#! /bin/bash
function perform_lint() {
	echo "Performing LINT..."
	if hash clang-format-3.9 2>/dev/null; then
		CLANG_FORMAT=clang-format-3.9
	else
		CLANG_FORMAT=clang-format
	fi
	echo "LINT: Using binary $CLANG_FORMAT"
	CLANG_FORMAT_WHITELIST="util/travis/clang-format-whitelist.txt"

	files_to_lint="$(find src/ -name '*.cpp' -or -name '*.h')"

	local errorcount=0
	local fail=0
	for f in ${files_to_lint}; do
		d=$(diff -u "$f" <(${CLANG_FORMAT} "$f") || true)

		if ! [ -z "$d" ]; then
			whitelisted=$(awk '$1 == "'$f'" { print 1 }' "$CLANG_FORMAT_WHITELIST")

			# If file is not whitelisted, mark a failure
			if [ -z ${whitelisted} ]; then
				errorcount=$((errorcount+1))

				printf "The file %s is not compliant with the coding style" "$f"
				if [ ${errorcount} -gt 50 ]; then
					printf "\nToo many errors encountered previously, this diff is hidden.\n"
				else
					printf ":\n%s\n" "$d"
				fi

				fail=1
			fi
		fi
	done

	if [ "$fail" = 1 ]; then
		echo "LINT reports failure."
		exit 1
	fi

	echo "LINT OK"
}


code:
#!/bin/bash -e
. util/travis/common.sh
. util/travis/lint.sh

needs_compile || exit 0

if [[ "$LINT" == "1" ]]; then
	# Lint with exit CI
	perform_lint
	exit 0
fi

if [[ $PLATFORM == "Unix" ]]; then
	mkdir -p travisbuild
	cd travisbuild || exit 1

	CMAKE_FLAGS=''
	if [[ $COMPILER == "g++-6" ]]; then
		export CC=gcc-6
		export CXX=g++-6
	fi

	# Clang builds with FreeType fail on Travis
	if [[ $CC == "clang" ]]; then
		CMAKE_FLAGS+=' -DENABLE_FREETYPE=FALSE'
	fi

	if [[ $TRAVIS_OS_NAME == "osx" ]]; then
		CMAKE_FLAGS+=' -DCUSTOM_GETTEXT_PATH=/usr/local/opt/gettext'
	fi

	cmake -DCMAKE_BUILD_TYPE=Debug \
		-DRUN_IN_PLACE=TRUE \
		-DENABLE_GETTEXT=TRUE \
		-DBUILD_SERVER=TRUE \
		$CMAKE_FLAGS ..
	make -j2

	echo "Running unit tests."
	CMD="../bin/minetest --run-unittests"
	if [[ "$VALGRIND" == "1" ]]; then
		valgrind --leak-check=full --leak-check-heuristics=all --undef-value-errors=no --error-exitcode=9 ${CMD} && exit 0
	else
		${CMD} && exit 0
	fi

elif [[ $PLATFORM == Win* ]]; then
	[[ $CC == "clang" ]] && exit 1 # Not supposed to happen
	# We need to have our build directory outside of the minetest directory because
	#  CMake will otherwise get very very confused with symlinks and complain that
	#  something is not a subdirectory of something even if it actually is.
	# e.g.:
	# /home/travis/minetest/minetest/travisbuild/minetest
	# \/  \/  \/
	# /home/travis/minetest/minetest/travisbuild/minetest/travisbuild/minetest
	# \/  \/  \/
	# /home/travis/minetest/minetest/travisbuild/minetest/travisbuild/minetest/travisbuild/minetest
	# You get the idea.
	OLDDIR=$(pwd)
	cd ..
	export EXISTING_MINETEST_DIR=$OLDDIR
	export NO_MINETEST_GAME=1
	if [[ $PLATFORM == "Win32" ]]; then
		"$OLDDIR/util/buildbot/buildwin32.sh" travisbuild && exit 0
	elif [[ $PLATFORM == "Win64" ]]; then
		"$OLDDIR/util/buildbot/buildwin64.sh" travisbuild && exit 0
	fi
else
	echo "Unknown platform \"${PLATFORM}\"."
	exit 1
fi


code:
# Target operating system name
set(CMAKE_SYSTEM_NAME Windows)

# Compilers to use
set(CMAKE_C_COMPILER %PREFIX%-gcc)
set(CMAKE_CXX_COMPILER %PREFIX%-g++)
set(CMAKE_RC_COMPILER %PREFIX%-windres)

# Location of the target environment
set(CMAKE_FIND_ROOT_PATH %ROOTPATH%)

# Adjust the default behaviour of the FIND_XXX() commands:
# search for headers and libraries in the target environment,
# search for programs in the host environment
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)


code:
#!/bin/sh

# Update/create minetest po files

# an auxiliary function to abort processing with an optional error
# message
abort() {
	test -n "$1" && echo >&2 "$1"
	exit 1
}

# The po/ directory is assumed to be parallel to the directory where
# this script is. Relative paths are fine for us so we can just
# use the following trick (works both for manual invocations and for
# script found from PATH)
scriptisin="$(dirname "$(which "$0")")"

# The script is executed from the parent of po/, which is also the
# parent of the script directory and of the src/ directory.
# We go through $scriptisin so that it can be executed from whatever
# directory and still work correctly
cd "$scriptisin/.."

test -e po || abort "po/ directory not found"
test -d po || abort "po/ is not a directory!"

# Get a list of the languages we have to update/create

cd po || abort "couldn't change directory to po!"

# This assumes that we won't have dirnames with space, which is
# the case for language codes, which are the only subdirs we expect to
# find in po/ anyway. If you put anything else there, you need to suffer
# the consequences of your actions, so we don't do sanity checks
langs=""

for lang in * ; do
	if test ! -d $lang; then
		continue
	fi
	langs="$langs $lang"
done

# go back
cd ..

# First thing first, update the .pot template. We place it in the po/
# directory at the top level. You a recent enough xgettext that supports
# --package-name
potfile=po/minetest.pot
xgettext --package-name=minetest \
	--sort-by-file \
	--add-location=file \
	--keyword=N_ \
	--keyword=wgettext \
	--keyword=fgettext \
	--keyword=fgettext_ne \
	--keyword=strgettext \
	--keyword=wstrgettext \
	--output $potfile \
	`find src/ -name '*.cpp' -o -name '*.h'` \
	`find builtin/ -name '*.lua'`

# Now iterate on all languages and create the po file if missing, or update it
# if it exists already
for lang in $langs ; do # note the missing quotes around $langs
	pofile=po/$lang/minetest.po
	if test -e $pofile; then
		echo "[$lang]: updating strings"
		msgmerge --update --sort-by-file $pofile $potfile
	else
		# This will ask for the translator identity
		echo "[$lang]: NEW strings"
		msginit --locale=$lang --output-file=$pofile --input=$potfile
	fi
done


code:
-- minetest.lua
-- Packet dissector for the UDP-based Minetest protocol
-- Copy this to $HOME/.wireshark/plugins/

--
-- Minetest
-- Copyright (C) 2011 celeron55, Perttu Ahola <celeron55@gmail.com>
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along
-- with this program; if not, write to the Free Software Foundation, Inc.,
-- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--

-- Table of Contents:
--   Part 1: Client command dissectors (TOSERVER_*)
--   Part 2: Server command dissectors (TOCLIENT_*)
--   Part 3: Wrapper protocol subdissectors
--   Part 4: Wrapper protocol main dissector
--   Part 5: Utility functions

--------------------------------------------
-- Part 1                                 --
-- Client command dissectors (TOSERVER_*) --
--------------------------------------------

minetest_client_commands = {}
minetest_client_obsolete = {}

-- TOSERVER_INIT

do
	local f_ser_fmt = ProtoField.uint8("minetest.client.init_ser_version",
		"Maximum serialization format version", base.DEC)
	local f_player_name = ProtoField.stringz("minetest.client.init_player_name", "Player Name")
	local f_password = ProtoField.stringz("minetest.client.init_password", "Password")
	local f_version = ProtoField.uint16("minetest.client.init_version", "Version", base.DEC)

	minetest_client_commands[0x10] = {
		"INIT",                             -- Command name
		53,                                 -- Minimum message length including code
		{ f_ser_fmt,                        -- List of fields [optional]
		  f_player_name,
		  f_password,
		  f_version },
		function(buffer, pinfo, tree, t)    -- Dissector function [optional]
			t:add(f_ser_fmt, buffer(2,1))
			t:add(f_player_name, buffer(3,20))
			t:add(f_password, buffer(23,28))
			t:add(f_version, buffer(51,2))
		end
	}
end

-- TOSERVER_INIT2

minetest_client_commands[0x11] = { "INIT2", 2 }

-- TOSERVER_GETBLOCK (obsolete)

minetest_client_commands[0x20] = { "GETBLOCK", 2 }
minetest_client_obsolete[0x20] = true

-- TOSERVER_ADDNODE (obsolete)

minetest_client_commands[0x21] = { "ADDNODE", 2 }
minetest_client_obsolete[0x21] = true

-- TOSERVER_REMOVENODE (obsolete)

minetest_client_commands[0x22] = { "REMOVENODE", 2 }
minetest_client_obsolete[0x22] = true

-- TOSERVER_PLAYERPOS

do
	local f_x = ProtoField.int32("minetest.client.playerpos_x", "Position X", base.DEC)
	local f_y = ProtoField.int32("minetest.client.playerpos_y", "Position Y", base.DEC)
	local f_z = ProtoField.int32("minetest.client.playerpos_z", "Position Z", base.DEC)
	local f_speed_x = ProtoField.int32("minetest.client.playerpos_speed_x", "Speed X", base.DEC)
	local f_speed_y = ProtoField.int32("minetest.client.playerpos_speed_y", "Speed Y", base.DEC)
	local f_speed_z = ProtoField.int32("minetest.client.playerpos_speed_z", "Speed Z", base.DEC)
	local f_pitch = ProtoField.int32("minetest.client.playerpos_pitch", "Pitch", base.DEC)
	local f_yaw = ProtoField.int32("minetest.client.playerpos_yaw", "Yaw", base.DEC)

	minetest_client_commands[0x23] = {
		"PLAYERPOS", 34,
		{ f_x, f_y, f_z, f_speed_x, f_speed_y, f_speed_z, f_pitch, f_yaw },
		function(buffer, pinfo, tree, t)
			t:add(f_x, buffer(2,4))
			t:add(f_y, buffer(6,4))
			t:add(f_z, buffer(10,4))
			t:add(f_speed_x, buffer(14,4))
			t:add(f_speed_y, buffer(18,4))
			t:add(f_speed_z, buffer(22,4))
			t:add(f_pitch, buffer(26,4))
			t:add(f_yaw, buffer(30,4))
		end
	}
end

-- TOSERVER_GOTBLOCKS

do
	local f_count = ProtoField.uint8("minetest.client.gotblocks_count", "Count", base.DEC)
	local f_block = ProtoField.bytes("minetest.client.gotblocks_block", "Block", base.DEC)
	local f_x = ProtoField.int16("minetest.client.gotblocks_x", "Block position X", base.DEC)
	local f_y = ProtoField.int16("minetest.client.gotblocks_y", "Block position Y", base.DEC)
	local f_z = ProtoField.int16("minetest.client.gotblocks_z", "Block position Z", base.DEC)

	minetest_client_commands[0x24] = {
		"GOTBLOCKS", 3,
		{ f_count, f_block, f_x, f_y, f_z },
		function(buffer, pinfo, tree, t)
			t:add(f_count, buffer(2,1))
			local count = buffer(2,1):uint()
			if minetest_check_length(buffer, 3 + 6*count, t) then
				pinfo.cols.info:append(" * " .. count)
				local index
				for index = 0, count - 1 do
					local pos = 3 + 6*index
					local t2 = t:add(f_block, buffer(pos, 6))
					t2:set_text("Block, X: " .. buffer(pos, 2):int()
						.. ", Y: " .. buffer(pos + 2, 2):int()
						.. ", Z: " .. buffer(pos + 4, 2):int())
					t2:add(f_x, buffer(pos, 2))
					t2:add(f_y, buffer(pos + 2, 2))
					t2:add(f_z, buffer(pos + 4, 2))
				end
			end
		end
	}
end

-- TOSERVER_DELETEDBLOCKS
-- TODO: Test this

do
	local f_count = ProtoField.uint8("minetest.client.deletedblocks_count", "Count", base.DEC)
	local f_block = ProtoField.bytes("minetest.client.deletedblocks_block", "Block", base.DEC)
	local f_x = ProtoField.int16("minetest.client.deletedblocks_x", "Block position X", base.DEC)
	local f_y = ProtoField.int16("minetest.client.deletedblocks_y", "Block position Y", base.DEC)
	local f_z = ProtoField.int16("minetest.client.deletedblocks_z", "Block position Z", base.DEC)

	minetest_client_commands[0x25] = {
		"DELETEDBLOCKS", 3,
		{ f_count, f_block, f_x, f_y, f_z },
		function(buffer, pinfo, tree, t)
			t:add(f_count, buffer(2,1))
			local count = buffer(2,1):uint()
			if minetest_check_length(buffer, 3 + 6*count, t) then
				pinfo.cols.info:append(" * " .. count)
				local index
				for index = 0, count - 1 do
					local pos = 3 + 6*index
					local t2 = t:add(f_block, buffer(pos, 6))
					t2:set_text("Block, X: " .. buffer(pos, 2):int()
						.. ", Y: " .. buffer(pos + 2, 2):int()
						.. ", Z: " .. buffer(pos + 4, 2):int())
					t2:add(f_x, buffer(pos, 2))
					t2:add(f_y, buffer(pos + 2, 2))
					t2:add(f_z, buffer(pos + 4, 2))
				end
			end
		end
	}
end

-- TOSERVER_ADDNODE_FROM_INVENTORY (obsolete)

minetest_client_commands[0x26] = { "ADDNODE_FROM_INVENTORY", 2 }
minetest_client_obsolete[0x26] = true

-- TOSERVER_CLICK_OBJECT
-- TODO: Test this

do
	local vs_button = {
		[0] = "left",
		[1] = "right"
	}

	local f_button = ProtoField.uint8("minetest.client.click_object_button", "Button", base.DEC, vs_button)
	local f_blockpos_x = ProtoField.int16("minetest.client.click_object_blockpos_x", "Block position X", base.DEC)
	local f_blockpos_y = ProtoField.int16("minetest.client.click_object_blockpos_y", "Block position Y", base.DEC)
	local f_blockpos_z = ProtoField.int16("minetest.client.click_object_blockpos_z", "Block position Z", base.DEC)
	local f_id = ProtoField.int16("minetest.client.click_object_id", "ID", base.DEC)
	local f_item = ProtoField.uint16("minetest.client.click_object_item", "Item", base.DEC)

	minetest_client_commands[0x27] = {
		"CLICK_OBJECT", 13,
		{ f_button, f_blockpos_x, f_blockpos_y, f_blockpos_z, f_id, f_item },
		function(buffer, pinfo, tree, t)
			t:add(f_button, buffer(2,1))
			t:add(f_blockpos_x, buffer(3,2))
			t:add(f_blockpos_y, buffer(5,2))
			t:add(f_blockpos_z, buffer(7,2))
			t:add(f_id, buffer(9,2))
			t:add(f_item, buffer(11,2))
		end
	}
end

-- TOSERVER_GROUND_ACTION

do
	local vs_action = {
		[0] = "Start digging",
		[1] = "Place block",
		[2] = "Stop digging",
		[3] = "Digging completed"
	}

	local f_action = ProtoField.uint8("minetest.client.ground_action", "Action", base.DEC, vs_action)
	local f_nodepos_undersurface_x = ProtoField.int16(
		"minetest.client.ground_action_nodepos_undersurface_x",
		"Node position (under surface) X")
	local f_nodepos_undersurface_y = ProtoField.int16(
		"minetest.client.ground_action_nodepos_undersurface_y",
		"Node position (under surface) Y")
	local f_nodepos_undersurface_z = ProtoField.int16(
		"minetest.client.ground_action_nodepos_undersurface_z",
		"Node position (under surface) Z")
	local f_nodepos_abovesurface_x = ProtoField.int16(
		"minetest.client.ground_action_nodepos_abovesurface_x",
		"Node position (above surface) X")
	local f_nodepos_abovesurface_y = ProtoField.int16(
		"minetest.client.ground_action_nodepos_abovesurface_y",
		"Node position (above surface) Y")
	local f_nodepos_abovesurface_z = ProtoField.int16(
		"minetest.client.ground_action_nodepos_abovesurface_z",
		"Node position (above surface) Z")
	local f_item = ProtoField.uint16("minetest.client.ground_action_item", "Item")

	minetest_client_commands[0x28] = {
		"GROUND_ACTION", 17,
		{ f_action,
		  f_nodepos_undersurface_x,
		  f_nodepos_undersurface_y,
		  f_nodepos_undersurface_z,
		  f_nodepos_abovesurface_x,
		  f_nodepos_abovesurface_y,
		  f_nodepos_abovesurface_z,
		  f_item },
		function(buffer, pinfo, tree, t)
			t:add(f_action, buffer(2,1))
			t:add(f_nodepos_undersurface_x, buffer(3,2))
			t:add(f_nodepos_undersurface_y, buffer(5,2))
			t:add(f_nodepos_undersurface_z, buffer(7,2))
			t:add(f_nodepos_abovesurface_x, buffer(9,2))
			t:add(f_nodepos_abovesurface_y, buffer(11,2))
			t:add(f_nodepos_abovesurface_z, buffer(13,2))
			t:add(f_item, buffer(15,2))
		end
	}
end

-- TOSERVER_RELEASE (obsolete)

minetest_client_commands[0x29] = { "RELEASE", 2 }
minetest_client_obsolete[0x29] = true

-- TOSERVER_SIGNTEXT (old signs)
-- TODO: Test this or mark obsolete

do
	local f_blockpos_x = ProtoField.int16("minetest.client.signtext_blockpos_x", "Block position X", base.DEC)
	local f_blockpos_y = ProtoField.int16("minetest.client.signtext_blockpos_y", "Block position Y", base.DEC)
	local f_blockpos_z = ProtoField.int16("minetest.client.signtext_blockpos_z", "Block position Z", base.DEC)
	local f_id = ProtoField.int16("minetest.client.signtext_id", "ID", base.DEC)
	local f_textlen = ProtoField.uint16("minetest.client.signtext_textlen", "Text length", base.DEC)
	local f_text = ProtoField.string("minetest.client.signtext_text", "Text")

	minetest_client_commands[0x30] = {
		"SIGNTEXT", 12,
		{ f_blockpos_x, f_blockpos_y, f_blockpos_z, f_id, f_textlen, f_text },
		function(buffer, pinfo, tree, t)
			t:add(f_blockpos_x, buffer(2,2))
			t:add(f_blockpos_y, buffer(4,2))
			t:add(f_blockpos_z, buffer(6,2))
			t:add(f_id, buffer(8,2))
			t:add(f_textlen, buffer(10,2))
			local textlen = buffer(10,2):uint()
			if minetest_check_length(buffer, 12 + textlen, t) then
				t:add(f_text, buffer, buffer(12,textlen))
			end
		end
	}
end

-- TOSERVER_INVENTORY_ACTION

do
	local f_action = ProtoField.string("minetest.client.inventory_action", "Action")

	minetest_client_commands[0x31] = {
		"INVENTORY_ACTION", 2,
		{ f_action },
		function(buffer, pinfo, tree, t)
			t:add(f_action, buffer(2, buffer:len() - 2))
		end
	}
end

-- TOSERVER_CHAT_MESSAGE

do
	local f_length = ProtoField.uint16("minetest.client.chat_message_length", "Length", base.DEC)
	local f_message = ProtoField.string("minetest.client.chat_message", "Message")

	minetest_client_commands[0x32] = {
		"CHAT_MESSAGE", 4,
		{ f_length, f_message },
		function(buffer, pinfo, tree, t)
			t:add(f_length, buffer(2,2))
			local textlen = buffer(2,2):uint()
			if minetest_check_length(buffer, 4 + textlen*2, t) then
				t:add(f_message, minetest_convert_utf16(buffer(4, textlen*2), "Converted chat message"))
			end
		end
	}
end

-- TOSERVER_SIGNNODETEXT

do
	local f_pos_x = ProtoField.int16("minetest.client.signnodetext_pos_x", "Block position X", base.DEC)
	local f_pos_y = ProtoField.int16("minetest.client.signnodetext_pos_y", "Block position Y", base.DEC)
	local f_pos_z = ProtoField.int16("minetest.client.signnodetext_pos_z", "Block position Z", base.DEC)
	local f_textlen = ProtoField.uint16("minetest.client.signnodetext_textlen", "Text length", base.DEC)
	local f_text = ProtoField.string("minetest.client.signnodetext_text", "Text")

	minetest_client_commands[0x33] = {
		"SIGNNODETEXT", 10,
		{ f_pos_x, f_pos_y, f_pos_z, f_textlen, f_text },
		function(buffer, pinfo, tree, t)
			t:add(f_pos_x, buffer(2,2))
			t:add(f_pos_y, buffer(4,2))
			t:add(f_pos_z, buffer(6,2))
			t:add(f_textlen, buffer(8,2))
			local textlen = buffer(8,2):uint()
			if minetest_check_length(buffer, 10 + textlen, t) then
				t:add(f_text, buffer(10, textlen))
			end
		end
	}
end

-- TOSERVER_CLICK_ACTIVEOBJECT

do
	local vs_button = {
		[0] = "left",
		[1] = "right"
	}

	local f_button = ProtoField.uint8("minetest.client.click_activeobject_button", "Button", base.DEC, vs_button)
	local f_id = ProtoField.uint16("minetest.client.click_activeobject_id", "ID", base.DEC)
	local f_item = ProtoField.uint16("minetest.client.click_activeobject_item", "Item", base.DEC)

	minetest_client_commands[0x34] = {
		"CLICK_ACTIVEOBJECT", 7,
		{ f_button, f_id, f_item },
		function(buffer, pinfo, tree, t)
			t:add(f_button, buffer(2,1))
			t:add(f_id, buffer(3,2))
			t:add(f_item, buffer(5,2))
		end
	}
end

-- TOSERVER_DAMAGE

do
	local f_amount = ProtoField.uint8("minetest.client.damage_amount", "Amount", base.DEC)

	minetest_client_commands[0x35] = {
		"DAMAGE", 3,
		{ f_amount },
		function(buffer, pinfo, tree, t)
			t:add(f_amount, buffer(2,1))
		end
	}
end

-- TOSERVER_PASSWORD

do
	local f_old_password = ProtoField.string("minetest.client.password_old", "Old password")
	local f_new_password = ProtoField.string("minetest.client.password_new", "New password")

	minetest_client_commands[0x36] = {
		"PASSWORD", 58,
		{ f_old_password, f_new_password },
		function(buffer, pinfo, tree, t)
			t:add(f_old_password, buffer(2,28))
			t:add(f_new_password, buffer(30,28))
		end
	}
end

-- TOSERVER_PLAYERITEM

do
	local f_item = ProtoField.uint16("minetest.client.playeritem_item", "Wielded item")

	minetest_client_commands[0x37] = {
		"PLAYERITEM", 4,
		{ f_item },
		function(buffer, pinfo, tree, t)
			t:add(f_item, buffer(2,2))
		end
	}
end

-- TOSERVER_RESPAWN

minetest_client_commands[0x38] = { "RESPAWN", 2 }

--------------------------------------------
-- Part 2                                 --
-- Server command dissectors (TOCLIENT_*) --
--------------------------------------------

minetest_server_commands = {}
minetest_server_obsolete = {}

-- TOCLIENT_INIT

do
	local f_version = ProtoField.uint8("minetest.server.init_version", "Deployed version", base.DEC)
	local f_pos_x = ProtoField.int16("minetest.server.init_pos_x", "Position X", base.DEC)
	local f_pos_y = ProtoField.int16("minetest.server.init_pos_y", "Position Y", base.DEC)
	local f_pos_z = ProtoField.int16("minetest.server.init_pos_x", "Position Z", base.DEC)
	local f_map_seed = ProtoField.uint64("minetest.server.init_map_seed", "Map seed", base.DEC)

	minetest_server_commands[0x10] = {
		"INIT", 17,
		{ f_version, f_pos_x, f_pos_y, f_pos_z, f_map_seed },
		function(buffer, pinfo, tree, t)
			t:add(f_version, buffer(2,1))
			t:add(f_pos_x, buffer(3,2))
			t:add(f_pos_y, buffer(5,2))
			t:add(f_pos_z, buffer(7,2))
			t:add(f_map_seed, buffer(9,8))
		end
	}
end

-- TOCLIENT_BLOCKDATA

do
	local f_x = ProtoField.int16("minetest.server.blockdata_x", "Block position X", base.DEC)
	local f_y = ProtoField.int16("minetest.server.blockdata_y", "Block position Y", base.DEC)
	local f_z = ProtoField.int16("minetest.server.blockdata_z", "Block position Z", base.DEC)
	local f_data = ProtoField.bytes("minetest.server.blockdata_block", "Serialized MapBlock")

	minetest_server_commands[0x20] = {
		"BLOCKDATA", 8,
		{ f_x, f_y, f_z, f_data },
		function(buffer, pinfo, tree, t)
			t:add(f_x, buffer(2,2))
			t:add(f_y, buffer(4,2))
			t:add(f_z, buffer(6,2))
			t:add(f_data, buffer(8, buffer:len() - 8))
		end
	}
end

-- TOCLIENT_ADDNODE

do
	local f_x = ProtoField.int16("minetest.server.addnode_x", "Position X", base.DEC)
	local f_y = ProtoField.int16("minetest.server.addnode_y", "Position Y", base.DEC)
	local f_z = ProtoField.int16("minetest.server.addnode_z", "Position Z", base.DEC)
	local f_data = ProtoField.bytes("minetest.server.addnode_node", "Serialized MapNode")

	minetest_server_commands[0x21] = {
		"ADDNODE", 8,
		{ f_x, f_y, f_z, f_data },
		function(buffer, pinfo, tree, t)
			t:add(f_x, buffer(2,2))
			t:add(f_y, buffer(4,2))
			t:add(f_z, buffer(6,2))
			t:add(f_data, buffer(8, buffer:len() - 8))
		end
	}
end

-- TOCLIENT_REMOVENODE

do
	local f_x = ProtoField.int16("minetest.server.removenode_x", "Position X", base.DEC)
	local f_y = ProtoField.int16("minetest.server.removenode_y", "Position Y", base.DEC)
	local f_z = ProtoField.int16("minetest.server.removenode_z", "Position Z", base.DEC)

	minetest_server_commands[0x22] = {
		"REMOVENODE", 8,
		{ f_x, f_y, f_z },
		function(buffer, pinfo, tree, t)
			t:add(f_x, buffer(2,2))
			t:add(f_y, buffer(4,2))
			t:add(f_z, buffer(6,2))
		end
	}
end

-- TOCLIENT_PLAYERPOS (obsolete)

minetest_server_commands[0x23] = { "PLAYERPOS", 2 }
minetest_server_obsolete[0x23] = true

-- TOCLIENT_PLAYERINFO

do
	local f_count = ProtoField.uint16("minetest.server.playerinfo_count", "Count", base.DEC)
	local f_player = ProtoField.bytes("minetest.server.playerinfo_player", "Player", base.DEC)
	local f_peer_id = ProtoField.uint16("minetest.server.playerinfo_peer_id", "Peer ID", base.DEC)
	local f_name = ProtoField.string("minetest.server.playerinfo_name", "Name")

	minetest_server_commands[0x24] = {
		"PLAYERINFO", 2,
		{ f_count, f_player, f_peer_id, f_name },
		function(buffer, pinfo, tree, t)
			local count = 0
			local pos, index
			for pos = 2, buffer:len() - 22, 22 do  -- does lua have integer division?
				count = count + 1
			end
			t:add(f_count, count):set_generated()
			t:set_len(2 + 22 * count)
			pinfo.cols.info:append(" * " .. count)
			for index = 0, count - 1 do
				local pos = 2 + 22 * index
				local t2 = t:add(f_player, buffer(pos, 22))
				t2:set_text("Player, ID: " .. buffer(pos, 2):uint()
					.. ", Name: " .. buffer(pos + 2, 20):string())
				t2:add(f_peer_id, buffer(pos, 2))
				t2:add(f_name, buffer(pos + 2, 20))
			end
		end
	}
end

-- TOCLIENT_OPT_BLOCK_NOT_FOUND (obsolete)

minetest_server_commands[0x25] = { "OPT_BLOCK_NOT_FOUND", 2 }
minetest_server_obsolete[0x25] = true

-- TOCLIENT_SECTORMETA (obsolete)

minetest_server_commands[0x26] = { "SECTORMETA", 2 }
minetest_server_obsolete[0x26] = true

-- TOCLIENT_INVENTORY

do
	local f_inventory = ProtoField.string("minetest.server.inventory", "Inventory")

	minetest_server_commands[0x27] = {
		"INVENTORY", 2,
		{ f_inventory },
		function(buffer, pinfo, tree, t)
			t:add(f_inventory, buffer(2, buffer:len() - 2))
		end
	}
end

-- TOCLIENT_OBJECTDATA

do
	local f_player_count = ProtoField.uint16("minetest.server.objectdata_player_count",
		"Count of player positions", base.DEC)
	local f_player = ProtoField.bytes("minetest.server.objectdata_player", "Player position")
	local f_peer_id = ProtoField.uint16("minetest.server.objectdata_player_peer_id", "Peer ID")
	local f_x = ProtoField.int32("minetest.server.objectdata_player_x", "Position X", base.DEC)
	local f_y = ProtoField.int32("minetest.server.objectdata_player_y", "Position Y", base.DEC)
	local f_z = ProtoField.int32("minetest.server.objectdata_player_z", "Position Z", base.DEC)
	local f_speed_x = ProtoField.int32("minetest.server.objectdata_player_speed_x", "Speed X", base.DEC)
	local f_speed_y = ProtoField.int32("minetest.server.objectdata_player_speed_y", "Speed Y", base.DEC)
	local f_speed_z = ProtoField.int32("minetest.server.objectdata_player_speed_z", "Speed Z", base.DEC)
	local f_pitch = ProtoField.int32("minetest.server.objectdata_player_pitch", "Pitch", base.DEC)
	local f_yaw = ProtoField.int32("minetest.server.objectdata_player_yaw", "Yaw", base.DEC)
	local f_block_count = ProtoField.uint16("minetest.server.objectdata_block_count",
		"Count of blocks", base.DEC)

	minetest_server_commands[0x28] = {
		"OBJECTDATA", 6,
		{ f_player_count, f_player, f_peer_id, f_x, f_y, f_z,
		  f_speed_x, f_speed_y, f_speed_z,f_pitch, f_yaw,
		  f_block_count },
		function(buffer, pinfo, tree, t)
			local t2, index, pos

			local player_count_pos = 2
			local player_count = buffer(player_count_pos, 2):uint()
			t:add(f_player_count, buffer(player_count_pos, 2))

			local block_count_pos = player_count_pos + 2 + 34 * player_count
			if not minetest_check_length(buffer, block_count_pos + 2, t) then
				return
			end

			for index = 0, player_count - 1 do
				pos = player_count_pos + 2 + 34 * index
				t2 = t:add(f_player, buffer(pos, 34))
				t2:set_text("Player position, ID: " .. buffer(pos, 2):uint())
				t2:add(f_peer_id, buffer(pos, 2))
				t2:add(f_x, buffer(pos + 2, 4))
				t2:add(f_y, buffer(pos + 6, 4))
				t2:add(f_z, buffer(pos + 10, 4))
				t2:add(f_speed_x, buffer(pos + 14, 4))
				t2:add(f_speed_y, buffer(pos + 18, 4))
				t2:add(f_speed_z, buffer(pos + 22, 4))
				t2:add(f_pitch, buffer(pos + 26, 4))
				t2:add(f_yaw, buffer(pos + 30, 4))
			end

			local block_count = buffer(block_count_pos, 2):uint()
			t:add(f_block_count, buffer(block_count_pos, 2))

			-- TODO: dissect blocks.
			-- NOTE: block_count > 0 is obsolete. (?)

			pinfo.cols.info:append(" * " .. (player_count + block_count))
		end
	}
end

-- TOCLIENT_TIME_OF_DAY

do
	local f_time = ProtoField.uint16("minetest.server.time_of_day", "Time", base.DEC)

	minetest_server_commands[0x29] = {
		"TIME_OF_DAY", 4,
		{ f_time },
		function(buffer, pinfo, tree, t)
			t:add(f_time, buffer(2,2))
		end
	}
end

-- TOCLIENT_CHAT_MESSAGE

do
	local f_length = ProtoField.uint16("minetest.server.chat_message_length", "Length", base.DEC)
	local f_message = ProtoField.string("minetest.server.chat_message", "Message")

	minetest_server_commands[0x30] = {
		"CHAT_MESSAGE", 4,
		{ f_length, f_message },
		function(buffer, pinfo, tree, t)
			t:add(f_length, buffer(2,2))
			local textlen = buffer(2,2):uint()
			if minetest_check_length(buffer, 4 + textlen*2, t) then
				t:add(f_message, minetest_convert_utf16(buffer(4, textlen*2), "Converted chat message"))
			end
		end
	}
end

-- TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD

do
	local f_removed_count = ProtoField.uint16(
		"minetest.server.active_object_remove_add_removed_count",
		"Count of removed objects", base.DEC)
	local f_removed = ProtoField.bytes(
		"minetest.server.active_object_remove_add_removed",
		"Removed object")
	local f_removed_id = ProtoField.uint16(
		"minetest.server.active_object_remove_add_removed_id",
		"ID", base.DEC)

	local f_added_count = ProtoField.uint16(
		"minetest.server.active_object_remove_add_added_count",
		"Count of added objects", base.DEC)
	local f_added = ProtoField.bytes(
		"minetest.server.active_object_remove_add_added",
		"Added object")
	local f_added_id = ProtoField.uint16(
		"minetest.server.active_object_remove_add_added_id",
		"ID", base.DEC)
	local f_added_type = ProtoField.uint8(
		"minetest.server.active_object_remove_add_added_type",
		"Type", base.DEC)
	local f_added_init_length = ProtoField.uint32(
		"minetest.server.active_object_remove_add_added_init_length",
		"Initialization data length", base.DEC)
	local f_added_init_data = ProtoField.bytes(
		"minetest.server.active_object_remove_add_added_init_data",
		"Initialization data")

	minetest_server_commands[0x31] = {
		"ACTIVE_OBJECT_REMOVE_ADD", 6,
		{ f_removed_count, f_removed, f_removed_id,
		  f_added_count, f_added, f_added_id,
		  f_added_type, f_added_init_length, f_added_init_data },
		function(buffer, pinfo, tree, t)
			local t2, index, pos

			local removed_count_pos = 2
			local removed_count = buffer(removed_count_pos, 2):uint()
			t:add(f_removed_count, buffer(removed_count_pos, 2))

			local added_count_pos = removed_count_pos + 2 + 2 * removed_count
			if not minetest_check_length(buffer, added_count_pos + 2, t) then
				return
			end

			-- Loop through removed active objects
			for index = 0, removed_count - 1 do
				pos = removed_count_pos + 2 + 2 * index
				t2 = t:add(f_removed, buffer(pos, 2))
				t2:set_text("Removed object, ID = " ..  buffer(pos, 2):uint())
				t2:add(f_removed_id, buffer(pos, 2))
			end

			local added_count = buffer(added_count_pos, 2):uint()
			t:add(f_added_count, buffer(added_count_pos, 2))

			-- Loop through added active objects
			pos = added_count_pos + 2
			for index = 0, added_count - 1 do
				if not minetest_check_length(buffer, pos + 7, t) then
					return
				end

				local init_length = buffer(pos + 3, 4):uint()
				if not minetest_check_length(buffer, pos + 7 + init_length, t) then
					return
				end

				t2 = t:add(f_added, buffer(pos, 7 + init_length))
				t2:set_text("Added object, ID = " .. buffer(pos, 2):uint())
				t2:add(f_added_id, buffer(pos, 2))
				t2:add(f_added_type, buffer(pos + 2, 1))
				t2:add(f_added_init_length, buffer(pos + 3, 4))
				t2:add(f_added_init_data, buffer(pos + 7, init_length))

				pos = pos + 7 + init_length
			end

			pinfo.cols.info:append(" * " .. (removed_count + added_count))
		end
	}
end

-- TOCLIENT_ACTIVE_OBJECT_MESSAGES

do
	local f_object_count = ProtoField.uint16(
		"minetest.server.active_object_messages_object_count",
		"Count of objects", base.DEC)
	local f_object = ProtoField.bytes(
		"minetest.server.active_object_messages_object",
		"Object")
	local f_object_id = ProtoField.uint16(
		"minetest.server.active_object_messages_id",
		"ID", base.DEC)
	local f_message_length = ProtoField.uint16(
		"minetest.server.active_object_messages_message_length",
		"Message length", base.DEC)
	local f_message = ProtoField.bytes(
		"minetest.server.active_object_messages_message",
		"Message")

	minetest_server_commands[0x32] = {
		"ACTIVE_OBJECT_MESSAGES", 2,
		{ f_object_count, f_object, f_object_id, f_message_length, f_message },
		function(buffer, pinfo, tree, t)
			local t2, count, pos, message_length

			count = 0
			pos = 2
			while pos < buffer:len() do
				if not minetest_check_length(buffer, pos + 4, t) then
					return
				end
				message_length = buffer(pos + 2, 2):uint()
				if not minetest_check_length(buffer, pos + 4 + message_length, t) then
					return
				end
				count = count + 1
				pos = pos + 4 + message_length
			end

			pinfo.cols.info:append(" * " .. count)
			t:add(f_object_count, count):set_generated()

			pos = 2
			while pos < buffer:len() do
				message_length = buffer(pos + 2, 2):uint()

				t2 = t:add(f_object, buffer(pos, 4 + message_length))
				t2:set_text("Object, ID = " ..  buffer(pos, 2):uint())
				t2:add(f_object_id, buffer(pos, 2))
				t2:add(f_message_length, buffer(pos + 2, 2))
				t2:add(f_message, buffer(pos + 4, message_length))

				pos = pos + 4 + message_length
			end
		end
	}
end

-- TOCLIENT_HP

do
	local f_hp = ProtoField.uint8("minetest.server.hp", "Hitpoints", base.DEC)

	minetest_server_commands[0x33] = {
		"HP", 3,
		{ f_hp },
		function(buffer, pinfo, tree, t)
			t:add(f_hp, buffer(2,1))
		end
	}
end

-- TOCLIENT_MOVE_PLAYER

do
	local f_x = ProtoField.int32("minetest.server.move_player_x", "Position X", base.DEC)
	local f_y = ProtoField.int32("minetest.server.move_player_y", "Position Y", base.DEC)
	local f_z = ProtoField.int32("minetest.server.move_player_z", "Position Z", base.DEC)
	local f_pitch = ProtoField.int32("minetest.server.move_player_pitch", "Pitch", base.DEC)
	local f_yaw = ProtoField.int32("minetest.server.move_player_yaw", "Yaw", base.DEC)
	local f_garbage = ProtoField.bytes("minetest.server.move_player_garbage", "Garbage")

	minetest_server_commands[0x34] = {
		"MOVE_PLAYER", 18,  -- actually 22, but see below
		{ f_x, f_y, f_z, f_pitch, f_yaw, f_garbage },
		function(buffer, pinfo, tree, t)
			t:add(f_x, buffer(2, 4))
			t:add(f_y, buffer(6, 4))
			t:add(f_z, buffer(10, 4))

			-- Compatibility note:
			-- Up to 2011-08-23, there was a bug in Minetest that
			-- caused the server to serialize the pitch and yaw
			-- with 2 bytes each instead of 4, creating a
			-- malformed message.
			if buffer:len() >= 22 then
				t:add(f_pitch, buffer(14, 4))
				t:add(f_yaw, buffer(18, 4))
			else
				t:add(f_garbage, buffer(14, 4))
				t:add_expert_info(PI_MALFORMED, PI_WARN, "Malformed pitch and yaw, possibly caused by a serialization bug in Minetest")
			end
		end
	}
end

-- TOCLIENT_ACCESS_DENIED

do
	local f_reason_length = ProtoField.uint16("minetest.server.access_denied_reason_length", "Reason length", base.DEC)
	local f_reason = ProtoField.string("minetest.server.access_denied_reason", "Reason")

	minetest_server_commands[0x35] = {
		"ACCESS_DENIED", 4,
		{ f_reason_length, f_reason },
		function(buffer, pinfo, tree, t)
			t:add(f_reason_length, buffer(2,2))
			local reason_length = buffer(2,2):uint()
			if minetest_check_length(buffer, 4 + reason_length * 2, t) then
				t:add(f_reason, minetest_convert_utf16(buffer(4, reason_length * 2), "Converted reason message"))
			end
		end
	}
end

-- TOCLIENT_PLAYERITEM

do
	local f_count = ProtoField.uint16(
		"minetest.server.playeritem_count",
		"Count of players", base.DEC)
	local f_player = ProtoField.bytes(
		"minetest.server.playeritem_player",
		"Player")
	local f_peer_id = ProtoField.uint16(
		"minetest.server.playeritem_peer_id",
		"Peer ID", base.DEC)
	local f_item_length = ProtoField.uint16(
		"minetest.server.playeritem_item_length",
		"Item information length", base.DEC)
	local f_item = ProtoField.string(
		"minetest.server.playeritem_item",
		"Item information")

	minetest_server_commands[0x36] = {
		"PLAYERITEM", 4,
		{ f_count, f_player, f_peer_id, f_item_length, f_item },
		function(buffer, pinfo, tree, t)
			local count, index, pos, item_length

			count = buffer(2,2):uint()
			pinfo.cols.info:append(" * " .. count)
			t:add(f_count, buffer(2,2))

			pos = 4
			for index = 0, count - 1 do
				if not minetest_check_length(buffer, pos + 4, t) then
					return
				end
				item_length = buffer(pos + 2, 2):uint()
				if not minetest_check_length(buffer, pos + 4 + item_length, t) then
					return
				end

				local t2 = t:add(f_player, buffer(pos, 4 + item_length))
				t2:set_text("Player, ID: " .. buffer(pos, 2):uint())
				t2:add(f_peer_id, buffer(pos, 2))
				t2:add(f_item_length, buffer(pos + 2, 2))
				t2:add(f_item, buffer(pos + 4, item_length))

				pos = pos + 4 + item_length
			end
		end
	}
end

-- TOCLIENT_DEATHSCREEN

do
	local vs_set_camera_point_target = {
		[0] = "False",
		[1] = "True"
	}

	local f_set_camera_point_target = ProtoField.uint8(
		"minetest.server.deathscreen_set_camera_point_target",
		"Set camera point target", base.DEC, vs_set_camera_point_target)
	local f_camera_point_target_x = ProtoField.int32(
		"minetest.server.deathscreen_camera_point_target_x",
		"Camera point target X", base.DEC)
	local f_camera_point_target_y = ProtoField.int32(
		"minetest.server.deathscreen_camera_point_target_y",
		"Camera point target Y", base.DEC)
	local f_camera_point_target_z = ProtoField.int32(
		"minetest.server.deathscreen_camera_point_target_z",
		"Camera point target Z", base.DEC)

	minetest_server_commands[0x37] = {
		"DEATHSCREEN", 15,
		{ f_set_camera_point_target, f_camera_point_target_x,
		  f_camera_point_target_y, f_camera_point_target_z},
		function(buffer, pinfo, tree, t)
			t:add(f_set_camera_point_target, buffer(2,1))
			t:add(f_camera_point_target_x, buffer(3,4))
			t:add(f_camera_point_target_y, buffer(7,4))
			t:add(f_camera_point_target_z, buffer(11,4))
		end
	}
end

------------------------------------
-- Part 3                         --
-- Wrapper protocol subdissectors --
------------------------------------

-- minetest.control dissector

do
	local p_control = Proto("minetest.control", "Minetest Control")

	local vs_control_type = {
		[0] = "Ack",
		[1] = "Set Peer ID",
		[2] = "Ping",
		[3] = "Disco"
	}

	local f_control_type = ProtoField.uint8("minetest.control.type", "Control Type", base.DEC, vs_control_type)
	local f_control_ack = ProtoField.uint16("minetest.control.ack", "ACK sequence number", base.DEC)
	local f_control_peerid = ProtoField.uint8("minetest.control.peerid", "New peer ID", base.DEC)
	p_control.fields = { f_control_type, f_control_ack, f_control_peerid }

	local data_dissector = Dissector.get("data")

	function p_control.dissector(buffer, pinfo, tree)
		local t = tree:add(p_control, buffer(0,1))
		t:add(f_control_type, buffer(0,1))

		pinfo.cols.info = "Control message"

		local pos = 1
		if buffer(0,1):uint() == 0 then
			pos = 3
			t:set_len(3)
			t:add(f_control_ack, buffer(1,2))
			pinfo.cols.info = "Ack " .. buffer(1,2):uint()
		elseif buffer(0,1):uint() == 1 then
			pos = 3
			t:set_len(3)
			t:add(f_control_peerid, buffer(1,2))
			pinfo.cols.info = "Set peer ID " .. buffer(1,2):uint()
		elseif buffer(0,1):uint() == 2 then
			pinfo.cols.info = "Ping"
		elseif buffer(0,1):uint() == 3 then
			pinfo.cols.info = "Disco"
		end

		data_dissector:call(buffer(pos):tvb(), pinfo, tree)
	end
end

-- minetest.client dissector
-- minetest.server dissector

-- Defines the minetest.client or minetest.server Proto. These two protocols
-- are created by the same function because they are so similar.
-- Parameter: proto: the Proto object
-- Parameter: this_peer: "Client" or "Server"
-- Parameter: other_peer: "Server" or "Client"
-- Parameter: commands: table of command information, built above
-- Parameter: obsolete: table of obsolete commands, built above
function minetest_define_client_or_server_proto(is_client)
	-- Differences between minetest.client and minetest.server
	local proto_name, this_peer, other_peer, empty_message_info
	local commands, obsolete
	if is_client then
		proto_name = "minetest.client"
		this_peer = "Client"
		other_peer = "Server"
		empty_message_info = "Empty message / Connect"
		commands = minetest_client_commands  -- defined in Part 1
		obsolete = minetest_client_obsolete  -- defined in Part 1
	else
		proto_name = "minetest.server"
		this_peer = "Server"
		other_peer = "Client"
		empty_message_info = "Empty message"
		commands = minetest_server_commands  -- defined in Part 2
		obsolete = minetest_server_obsolete  -- defined in Part 2
	end

	-- Create the protocol object.
	local proto = Proto(proto_name, "Minetest " .. this_peer .. " to " .. other_peer)

	-- Create a table vs_command that maps command codes to command names.
	local vs_command = {}
	local code, command_info
	for code, command_info in pairs(commands) do
		local command_name = command_info[1]
		vs_command[code] = "TO" .. other_peer:upper() .. "_" .. command_name
	end

	-- Field definitions
	local f_command = ProtoField.uint16(proto_name .. ".command", "Command", base.HEX, vs_command)
	local f_empty = ProtoField.bool(proto_name .. ".empty", "Is empty", BASE_NONE)
	proto.fields = { f_command, f_empty }

	-- Add command-specific fields to the protocol
	for code, command_info in pairs(commands) do
		local command_fields = command_info[3]
		if command_fields ~= nil then
			local index, field
			for index, field in ipairs(command_fields) do
				table.insert(proto.fields, field)
			end
		end
	end

	-- minetest.client or minetest.server dissector function
	function proto.dissector(buffer, pinfo, tree)
		local t = tree:add(proto, buffer)

		pinfo.cols.info = this_peer

		if buffer:len() == 0 then
			-- Empty message.
			t:add(f_empty, 1):set_generated()
			pinfo.cols.info:append(": " .. empty_message_info)

		elseif minetest_check_length(buffer, 2, t) then
			-- Get the command code.
			t:add(f_command, buffer(0,2))
			local code = buffer(0,2):uint()
			local command_info = commands[code]
			if command_info == nil then
				-- Error: Unknown command.
				pinfo.cols.info:append(": Unknown command")
				t:add_expert_info(PI_UNDECODED, PI_WARN, "Unknown " .. this_peer .. " to " .. other_peer .. " command")
			else
				-- Process a known command
				local command_name = command_info[1]
				local command_min_length = command_info[2]
				local command_fields = command_info[3]
				local command_dissector = command_info[4]
				if minetest_check_length(buffer, command_min_length, t) then
					pinfo.cols.info:append(": " .. command_name)
					if command_dissector ~= nil then
						command_dissector(buffer, pinfo, tree, t)
					end
				end
				if obsolete[code] then
					t:add_expert_info(PI_REQUEST_CODE, PI_WARN, "Obsolete command.")
				end
			end
		end
	end
end

minetest_define_client_or_server_proto(true)  -- minetest.client
minetest_define_client_or_server_proto(false) -- minetest.server

-- minetest.split dissector

do
	local p_split = Proto("minetest.split", "Minetest Split Message")

	local f_split_seq = ProtoField.uint16("minetest.split.seq", "Sequence number", base.DEC)
	local f_split_chunkcount = ProtoField.uint16("minetest.split.chunkcount", "Chunk count", base.DEC)
	local f_split_chunknum = ProtoField.uint16("minetest.split.chunknum", "Chunk number", base.DEC)
	local f_split_data = ProtoField.bytes("minetest.split.data", "Split message data")
	p_split.fields = { f_split_seq, f_split_chunkcount, f_split_chunknum, f_split_data }

	function p_split.dissector(buffer, pinfo, tree)
		local t = tree:add(p_split, buffer(0,6))
		t:add(f_split_seq, buffer(0,2))
		t:add(f_split_chunkcount, buffer(2,2))
		t:add(f_split_chunknum, buffer(4,2))
		t:add(f_split_data, buffer(6))
		pinfo.cols.info:append(" " .. buffer(0,2):uint() .. " chunk " .. buffer(4,2):uint() .. "/" .. buffer(2,2):uint())
	end
end

-------------------------------------
-- Part 4                          --
-- Wrapper protocol main dissector --
-------------------------------------

-- minetest dissector

do
	local p_minetest = Proto("minetest", "Minetest")

	local minetest_id = 0x4f457403
	local vs_id = {
		[minetest_id] = "Valid"
	}

	local vs_peer = {
		[0] = "Inexistent",
		[1] = "Server"
	}

	local vs_type = {
		[0] = "Control",
		[1] = "Original",
		[2] = "Split",
		[3] = "Reliable"
	}

	local f_id = ProtoField.uint32("minetest.id", "ID", base.HEX, vs_id)
	local f_peer = ProtoField.uint16("minetest.peer", "Peer", base.DEC, vs_peer)
	local f_channel = ProtoField.uint8("minetest.channel", "Channel", base.DEC)
	local f_type = ProtoField.uint8("minetest.type", "Type", base.DEC, vs_type)
	local f_seq = ProtoField.uint16("minetest.seq", "Sequence number", base.DEC)
	local f_subtype = ProtoField.uint8("minetest.subtype", "Subtype", base.DEC, vs_type)

	p_minetest.fields = { f_id, f_peer, f_channel, f_type, f_seq, f_subtype }

	local data_dissector = Dissector.get("data")
	local control_dissector = Dissector.get("minetest.control")
	local client_dissector = Dissector.get("minetest.client")
	local server_dissector = Dissector.get("minetest.server")
	local split_dissector = Dissector.get("minetest.split")

	function p_minetest.dissector(buffer, pinfo, tree)

		-- Add Minetest tree item and verify the ID
		local t = tree:add(p_minetest, buffer(0,8))
		t:add(f_id, buffer(0,4))
		if buffer(0,4):uint() ~= minetest_id then
			t:add_expert_info(PI_UNDECODED, PI_WARN, "Invalid ID, this is not a Minetest packet")
			return
		end

		-- ID is valid, so replace packet's shown protocol
		pinfo.cols.protocol = "Minetest"
		pinfo.cols.info = "Minetest"

		-- Set the other header fields
		t:add(f_peer, buffer(4,2))
		t:add(f_channel, buffer(6,1))
		t:add(f_type, buffer(7,1))
		t:set_text("Minetest, Peer: " .. buffer(4,2):uint() .. ", Channel: " .. buffer(6,1):uint())

		local reliability_info
		if buffer(7,1):uint() == 3 then
			-- Reliable message
			reliability_info = "Seq=" .. buffer(8,2):uint()
			t:set_len(11)
			t:add(f_seq, buffer(8,2))
			t:add(f_subtype, buffer(10,1))
			pos = 10
		else
			-- Unreliable message
			reliability_info = "Unrel"
			pos = 7
		end

		if buffer(pos,1):uint() == 0 then
			-- Control message, possibly reliable
			control_dissector:call(buffer(pos+1):tvb(), pinfo, tree)
		elseif buffer(pos,1):uint() == 1 then
			-- Original message, possibly reliable
			if buffer(4,2):uint() == 1 then
				server_dissector:call(buffer(pos+1):tvb(), pinfo, tree)
			else
				client_dissector:call(buffer(pos+1):tvb(), pinfo, tree)
			end
		elseif buffer(pos,1):uint() == 2 then
			-- Split message, possibly reliable
			if buffer(4,2):uint() == 1 then
				pinfo.cols.info = "Server: Split message"
			else
				pinfo.cols.info = "Client: Split message"
			end
			split_dissector:call(buffer(pos+1):tvb(), pinfo, tree)
		elseif buffer(pos,1):uint() == 3 then
			-- Doubly reliable message??
			t:add_expert_info(PI_MALFORMED, PI_ERROR, "Reliable message wrapped in reliable message")
		else
			data_dissector:call(buffer(pos+1):tvb(), pinfo, tree)
		end

		pinfo.cols.info:append(" (" .. reliability_info .. ")")

	end

	-- FIXME Is there a way to let the dissector table check if the first payload bytes are 0x4f457403?
	DissectorTable.get("udp.port"):add(30000, p_minetest)
	DissectorTable.get("udp.port"):add(30001, p_minetest)
end

-----------------------
-- Part 5            --
-- Utility functions --
-----------------------

-- Checks if a (sub-)Tvb is long enough to be further dissected.
-- If it is long enough, sets the dissector tree item length to min_len
-- and returns true. If it is not long enough, adds expert info to the
-- dissector tree and returns false.
-- Parameter: tvb: the Tvb
-- Parameter: min_len: required minimum length
-- Parameter: t: dissector tree item
-- Returns: true if tvb:len() >= min_len, false otherwise
function minetest_check_length(tvb, min_len, t)
	if tvb:len() >= min_len then
		t:set_len(min_len)
		return true

	-- Tvb:reported_length_remaining() has been added in August 2011
	-- and is not yet widely available, disable for the time being
	-- TODO: uncomment at a later date
	-- TODO: when uncommenting this, also re-check if other parts of
	-- the dissector could benefit from reported_length_remaining
	--elseif tvb:reported_length_remaining() >= min_len then
	--	t:add_expert_info(PI_UNDECODED, PI_INFO, "Only part of this packet was captured, unable to decode.")
	--	return false

	else
		t:add_expert_info(PI_MALFORMED, PI_ERROR, "Message is too short")
		return false
	end
end

-- Takes a Tvb or TvbRange (i.e. part of a packet) that
-- contains a UTF-16 string and returns a TvbRange containing
-- string converted to ASCII. Any characters outside the range
-- 0x20 to 0x7e are replaced by a question mark.
-- Parameter: tvb: Tvb or TvbRange that contains the UTF-16 data
-- Parameter: name: will be the name of the newly created Tvb.
-- Returns: New TvbRange containing the ASCII string.
-- TODO: Handle surrogates (should only produce one question mark)
-- TODO: Remove this when Wireshark supports UTF-16 strings natively.
function minetest_convert_utf16(tvb, name)
	local hex, pos, char
	hex = ""
	for pos = 0, tvb:len() - 2, 2 do
		char = tvb(pos, 2):uint()
		if (char >= 0x20) and (char <= 0x7e) then
			hex = hex .. string.format(" %02x", char)
		else
			hex = hex .. " 3F"
		end
	end
	if hex == "" then
		-- This is a hack to avoid a failed assertion in tvbuff.c
		-- (function: ensure_contiguous_no_exception)
		return ByteArray.new("00"):tvb(name):range(0,0)
	else
		return ByteArray.new(hex):tvb(name):range()
	end
end


code:
/build/
/install/
/release/
/sources/
/libreboot.conf
.version
.revision
.tarfiles
.epoch
push
*.vim
/TODO/
/docs/version
/bucts/
/coreboot/
/crossgcc/
/flashrom/
/grub/
/memtest86plus/
/seabios/
/bin/
/resources/utilities/ich9deblob/*.rom
/resources/utilities/ich9deblob/*.bin
/resources/utilities/ich9deblob/ich9deblob
/resources/utilities/ich9deblob/ich9gen
/resources/utilities/ich9deblob/demefactory
/resources/utilities/ich9deblob/obj/*.o
/resources/utilities/ich9deblob/obj/*/*.o
/resources/utilities/ich9deblob/mkdescriptor*.[ch]
/resources/utilities/ich9deblob/mkgbe*.[ch]
/resources/utilities/grub-assemble/grub_*.elf
/mkgbe.[ch]
/*.bin
/resources/utilities/i945-pwm/i945-pwm
/push
/ChangeLog
/NEWS
/version
/versiondate
/gm45macaddress
tocheck*
*.html
!www/template.html
/www/news/index.md
/www/feed.xml
/www/news/feed.xml

path: .gitignore

license: mit